/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 8926:
/***/ ((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;
/***/ }),
/***/ 9713:
/***/ ((module) => {
function _defineProperty(obj, key, value) {
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;
/***/ }),
/***/ 5318:
/***/ ((module) => {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 1553:
/***/ ((module) => {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = GeneratorFunctionPrototype;
define(Gp, "constructor", GeneratorFunctionPrototype);
define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
});
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
define(Gp, iteratorSymbol, function() {
return this;
});
define(Gp, "toString", function() {
return "[object Generator]";
});
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
true ? module.exports : 0
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, in modern engines
// we can explicitly access globalThis. In older engines we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime;
} else {
Function("r", "regeneratorRuntime = r")(runtime);
}
}
/***/ }),
/***/ 7757:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
module.exports = __webpack_require__(1553);
/***/ }),
/***/ 9494:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const atob = __webpack_require__(7672);
const btoa = __webpack_require__(4817);
module.exports = {
atob,
btoa
};
/***/ }),
/***/ 7672:
/***/ ((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) {
// 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;
/***/ }),
/***/ 4817:
/***/ ((module) => {
"use strict";
/**
* btoa() as defined by the HTML and Infra specs, which mostly just references
* RFC 4648.
*/
function btoa(s) {
let i;
// String conversion as required by Web IDL.
s = `${s}`;
// "The btoa() method must throw an "InvalidCharacterError" DOMException if
// data contains any character whose code point is greater than U+00FF."
for (i = 0; i < s.length; i++) {
if (s.charCodeAt(i) > 255) {
return null;
}
}
let out = "";
for (i = 0; i < s.length; i += 3) {
const groupsOfSix = [undefined, undefined, undefined, undefined];
groupsOfSix[0] = s.charCodeAt(i) >> 2;
groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4;
if (s.length > i + 1) {
groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4;
groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2;
}
if (s.length > i + 2) {
groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6;
groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f;
}
for (let j = 0; j < groupsOfSix.length; j++) {
if (typeof groupsOfSix[j] === "undefined") {
out += "=";
} else {
out += btoaLookup(groupsOfSix[j]);
}
}
}
return out;
}
/**
* Lookup table for btoa(), which converts a six-bit number into the
* corresponding ASCII character.
*/
const keystr =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function btoaLookup(index) {
if (index >= 0 && index < 64) {
return keystr[index];
}
// Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.
return undefined;
}
module.exports = btoa;
/***/ }),
/***/ 4223:
/***/ ((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
/***/ }),
/***/ 8677:
/***/ (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
};
});
/***/ }),
/***/ 9827:
/***/ (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;
});
/***/ }),
/***/ 5215:
/***/ (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__(7819), __webpack_require__(8677), __webpack_require__(9827));
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7819), __webpack_require__(8677), __webpack_require__(9827)], __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(); // 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;
});
/***/ }),
/***/ 7819:
/***/ (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
* @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 (; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT; // Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
} // Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength;) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base;; 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 state to ,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base;; 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
* @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);
/***/ }),
/***/ 517:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": () => (/* binding */ src_converse)
});
// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js
var URI = __webpack_require__(5215);
var URI_default = /*#__PURE__*/__webpack_require__.n(URI);
// EXTERNAL MODULE: ./node_modules/sprintf-js/src/sprintf.js
var sprintf = __webpack_require__(4223);
;// 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);
}
});
;// 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/_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/_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/_getPrototype.js
/** Built-in value references. */
var getPrototype = _overArg(Object.getPrototypeOf, Object);
/* harmony default export */ const _getPrototype = (getPrototype);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isPlainObject.js
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
isPlainObject_objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var isPlainObject_hasOwnProperty = isPlainObject_objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = 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) != 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 &&
funcToString.call(Ctor) == objectCtorString;
}
/* harmony default export */ const lodash_es_isPlainObject = (isPlainObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isElement.js
/**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('');
* // => false
*/
function isElement(value) {
return lodash_es_isObjectLike(value) && value.nodeType === 1 && !lodash_es_isPlainObject(value);
}
/* harmony default export */ const lodash_es_isElement = (isElement);
;// CONCATENATED MODULE: ./src/headless/log.js
var _console, _console2, _console3, _console4;
const LEVELS = {
'debug': 0,
'info': 1,
'warn': 2,
'error': 3,
'fatal': 4
};
const logger = Object.assign({
'debug': (_console = console) !== null && _console !== void 0 && _console.log ? console.log.bind(console) : function noop() {},
'error': (_console2 = console) !== null && _console2 !== void 0 && _console2.log ? console.log.bind(console) : function noop() {},
'info': (_console3 = console) !== null && _console3 !== void 0 && _console3.log ? console.log.bind(console) : function noop() {},
'warn': (_console4 = console) !== null && _console4 !== void 0 && _console4.log ? console.log.bind(console) : function noop() {}
}, console);
/**
* The log namespace
* @namespace log
*/
const log = {
/**
* The the log-level, which determines how verbose the logging is.
* @method log#setLogLevel
* @param { integer } level - The loglevel which allows for filtering of log messages
*/
setLogLevel(level) {
if (!['debug', 'info', 'warn', 'error', 'fatal'].includes(level)) {
throw new Error(`Invalid loglevel: ${level}`);
}
this.loglevel = level;
},
/**
* Logs messages to the browser's developer console.
* Available loglevels are 0 for 'debug', 1 for 'info', 2 for 'warn',
* 3 for 'error' and 4 for 'fatal'.
* When using the 'error' or 'warn' loglevels, a full stacktrace will be
* logged as well.
* @method log#log
* @param { string | Error } message - The message to be logged
* @param { integer } 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 (lodash_es_isElement(message)) {
message = message.outerHTML;
}
const prefix = style ? '%c' : '';
if (level === 'error') {
logger.error(`${prefix} ERROR: ${message}`, style);
} else if (level === 'warn') {
logger.warn(`${prefix} ${new Date().toISOString()} WARNING: ${message}`, style);
} else if (level === 'fatal') {
logger.error(`${prefix} FATAL: ${message}`, style);
} else if (level === 'debug') {
logger.debug(`${prefix} ${new Date().toISOString()} DEBUG: ${message}`, style);
} else {
logger.info(`${prefix} ${new Date().toISOString()} INFO: ${message}`, style);
}
},
debug(message, style) {
this.log(message, 'debug', style);
},
error(message, style) {
this.log(message, 'error', style);
},
info(message, style) {
this.log(message, 'info', style);
},
warn(message, style) {
this.log(message, 'warn', style);
},
fatal(message, style) {
this.log(message, 'fatal', style);
}
};
/* harmony default export */ const headless_log = (log);
;// CONCATENATED MODULE: ./src/strophe-shims.js
const WebSocket = window.WebSocket;
const strophe_shims_DOMParser = window.DOMParser;
function getDummyXMLDOMDocument() {
return document.implementation.createDocument('jabber:client', 'strophe', null);
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/md5.js
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Everything that isn't used by Strophe has been stripped here!
*/
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
const safe_add = function (x, y) {
const lsw = (x & 0xFFFF) + (y & 0xFFFF);
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xFFFF;
};
/*
* Bitwise rotate a 32-bit number to the left.
*/
const bit_rol = function (num, cnt) {
return num << cnt | num >>> 32 - cnt;
};
/*
* Convert a string to an array of little-endian words
*/
const str2binl = function (str) {
if (typeof str !== "string") {
throw new Error("str2binl was passed a non-string");
}
const bin = [];
for (let i = 0; i < str.length * 8; i += 8) {
bin[i >> 5] |= (str.charCodeAt(i / 8) & 255) << i % 32;
}
return bin;
};
/*
* Convert an array of little-endian words to a string
*/
const binl2str = function (bin) {
let str = "";
for (let i = 0; i < bin.length * 32; i += 8) {
str += String.fromCharCode(bin[i >> 5] >>> i % 32 & 255);
}
return str;
};
/*
* Convert an array of little-endian words to a hex string.
*/
const binl2hex = function (binarray) {
const hex_tab = "0123456789abcdef";
let str = "";
for (let i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 0xF) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 0xF);
}
return str;
};
/*
* These functions implement the four basic operations the algorithm uses.
*/
const md5_cmn = function (q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
};
const md5_ff = function (a, b, c, d, x, s, t) {
return md5_cmn(b & c | ~b & d, a, b, x, s, t);
};
const md5_gg = function (a, b, c, d, x, s, t) {
return md5_cmn(b & d | c & ~d, a, b, x, s, t);
};
const md5_hh = function (a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
};
const md5_ii = function (a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | ~d), a, b, x, s, t);
};
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
const core_md5 = function (x, len) {
/* append padding */
x[len >> 5] |= 0x80 << len % 32;
x[(len + 64 >>> 9 << 4) + 14] = len;
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
let olda, oldb, oldc, oldd;
for (let i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [a, b, c, d];
};
/*
* These are the functions you'll usually want to call.
* They take string arguments and return either hex or base-64 encoded
* strings.
*/
const MD5 = {
hexdigest: function (s) {
return binl2hex(core_md5(str2binl(s), s.length * 8));
},
hash: function (s) {
return binl2str(core_md5(str2binl(s), s.length * 8));
}
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl.js
/** Class: Strophe.SASLMechanism
*
* Encapsulates an SASL authentication mechanism.
*
* User code may override the priority for each mechanism or disable it completely.
* See for information about changing priority and for informatian on
* how to disable a mechanism.
*
* By default, all mechanisms are enabled and the priorities are
*
* SCRAM-SHA-1 - 60
* PLAIN - 50
* OAUTHBEARER - 40
* X-OAUTH2 - 30
* ANONYMOUS - 20
* EXTERNAL - 10
*
* See: Strophe.Connection.addSupportedSASLMechanisms
*/
class SASLMechanism {
/**
* PrivateConstructor: Strophe.SASLMechanism
* SASL auth mechanism abstraction.
*
* Parameters:
* (String) name - SASL Mechanism name.
* (Boolean) isClientFirst - If client should send response first without challenge.
* (Number) priority - Priority.
*
* Returns:
* A new Strophe.SASLMechanism object.
*/
constructor(name, isClientFirst, priority) {
/** PrivateVariable: mechname
* Mechanism name.
*/
this.mechname = name;
/** PrivateVariable: isClientFirst
* If client sends response without initial server challenge.
*/
this.isClientFirst = isClientFirst;
/** Variable: priority
* Determines which 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 for a list of available mechanisms.
*
*/
this.priority = priority;
}
/**
* Function: test
* Checks if mechanism able to run.
* To disable a mechanism, make this return false;
*
* To disable plain authentication run
* > Strophe.SASLPlain.test = function() {
* > return false;
* > }
*
* See for a list of available mechanisms.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
*
* Returns:
* (Boolean) If mechanism was able to run.
*/
test() {
// eslint-disable-line class-methods-use-this
return true;
}
/** PrivateFunction: onStart
* Called before starting mechanism on some connection.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
*/
onStart(connection) {
this._connection = connection;
}
/** PrivateFunction: onChallenge
* Called by protocol implementation on incoming challenge.
*
* By deafult, if the client is expected to send data first (isClientFirst === true),
* this method is called with `challenge` as null on the first call,
* unless `clientChallenge` is overridden in the relevant subclass.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
* (String) challenge - current challenge to handle.
*
* Returns:
* (String) Mechanism response.
*/
onChallenge(connection, challenge) {
// eslint-disable-line
throw new Error("You should implement challenge handling!");
}
/** PrivateFunction: clientChallenge
* Called by the protocol implementation if the client is expected to send
* data first in the authentication exchange (i.e. isClientFirst === true).
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
*
* Returns:
* (String) Mechanism response.
*/
clientChallenge(connection) {
if (!this.isClientFirst) {
throw new Error("clientChallenge should not be called if isClientFirst is false!");
}
return this.onChallenge(connection);
}
/** PrivateFunction: onFailure
* Protocol informs mechanism implementation about SASL failure.
*/
onFailure() {
this._connection = null;
}
/** PrivateFunction: onSuccess
* Protocol informs mechanism implementation about SASL success.
*/
onSuccess() {
this._connection = null;
}
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-anon.js
// Building SASL callbacks
class SASLAnonymous extends SASLMechanism {
/** PrivateConstructor: SASLAnonymous
* 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);
}
test(connection) {
// eslint-disable-line class-methods-use-this
return connection.authcid === null;
}
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-external.js
class SASLExternal extends SASLMechanism {
/** PrivateConstructor: SASLExternal
* SASL EXTERNAL authentication.
*
* The EXTERNAL mechanism allows a client to request the server to use
* credentials established by means external to the mechanism to
* authenticate the client. The external means may be, for instance,
* TLS services.
*/
constructor() {
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);
}
onChallenge(connection) {
// eslint-disable-line class-methods-use-this
/** According to XEP-178, an authzid SHOULD NOT be presented when the
* authcid contained or implied in the client certificate is the JID (i.e.
* authzid) with which the user wants to log in as.
*
* To NOT send the authzid, the user should therefore set the authcid equal
* to the JID when instantiating a new Strophe.Connection object.
*/
return connection.authcid === connection.authzid ? '' : connection.authzid;
}
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/utils.js
const utils = {
utf16to8: function (str) {
var i, c;
var out = "";
var len = str.length;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if (c >= 0x0000 && c <= 0x007F) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | c >> 12 & 0x0F);
out += String.fromCharCode(0x80 | c >> 6 & 0x3F);
out += String.fromCharCode(0x80 | c >> 0 & 0x3F);
} else {
out += String.fromCharCode(0xC0 | c >> 6 & 0x1F);
out += String.fromCharCode(0x80 | c >> 0 & 0x3F);
}
}
return out;
},
addCookies: function (cookies) {
/* Parameters:
* (Object) cookies - either a map of cookie names
* to string values or to maps of cookie values.
*
* For example:
* { "myCookie": "1234" }
*
* or:
* { "myCookie": {
* "value": "1234",
* "domain": ".example.org",
* "path": "/",
* "expires": expirationDate
* }
* }
*
* These values get passed to Strophe.Connection via
* options.cookies
*/
cookies = cookies || {};
for (const cookieName in cookies) {
if (Object.prototype.hasOwnProperty.call(cookies, cookieName)) {
let expires = '';
let domain = '';
let path = '';
const cookieObj = cookies[cookieName];
const isObj = typeof cookieObj === "object";
const cookieValue = escape(unescape(isObj ? cookieObj.value : cookieObj));
if (isObj) {
expires = cookieObj.expires ? ";expires=" + cookieObj.expires : '';
domain = cookieObj.domain ? ";domain=" + cookieObj.domain : '';
path = cookieObj.path ? ";path=" + cookieObj.path : '';
}
document.cookie = cookieName + '=' + cookieValue + expires + domain + path;
}
}
}
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-oauthbearer.js
class SASLOAuthBearer extends SASLMechanism {
/** PrivateConstructor: SASLOAuthBearer
* 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);
}
test(connection) {
// eslint-disable-line class-methods-use-this
return connection.pass !== null;
}
onChallenge(connection) {
// eslint-disable-line class-methods-use-this
let auth_str = 'n,';
if (connection.authcid !== null) {
auth_str = auth_str + 'a=' + connection.authzid;
}
auth_str = auth_str + ',';
auth_str = auth_str + "\u0001";
auth_str = auth_str + 'auth=Bearer ';
auth_str = auth_str + connection.pass;
auth_str = auth_str + "\u0001";
auth_str = auth_str + "\u0001";
return utils.utf16to8(auth_str);
}
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-plain.js
class SASLPlain extends SASLMechanism {
/** PrivateConstructor: SASLPlain
* 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);
}
test(connection) {
// eslint-disable-line class-methods-use-this
return connection.authcid !== null;
}
onChallenge(connection) {
// eslint-disable-line class-methods-use-this
const {
authcid,
authzid,
domain,
pass
} = connection;
if (!domain) {
throw new Error("SASLPlain onChallenge: domain is not defined!");
} // Only include authzid if it differs from authcid.
// See: https://tools.ietf.org/html/rfc6120#section-6.3.8
let auth_str = authzid !== `${authcid}@${domain}` ? authzid : '';
auth_str = auth_str + "\u0000";
auth_str = auth_str + authcid;
auth_str = auth_str + "\u0000";
auth_str = auth_str + pass;
return utils.utf16to8(auth_str);
}
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sha1.js
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/* global define */
/* Some functions and variables have been stripped for use with Strophe */
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << 24 - len % 32;
x[(len + 64 >> 9 << 4) + 15] = len;
var w = new Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
var i, j, t, olda, oldb, oldc, oldd, olde;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
olde = e;
for (j = 0; j < 80; j++) {
if (j < 16) {
w[j] = x[i + j];
} else {
w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
t = sha1_safe_add(sha1_safe_add(rol(a, 5), sha1_ft(j, b, c, d)), sha1_safe_add(sha1_safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = sha1_safe_add(a, olda);
b = sha1_safe_add(b, oldb);
c = sha1_safe_add(c, oldc);
d = sha1_safe_add(d, oldd);
e = sha1_safe_add(e, olde);
}
return [a, b, c, d, e];
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d) {
if (t < 20) {
return b & c | ~b & d;
}
if (t < 40) {
return b ^ c ^ d;
}
if (t < 60) {
return b & c | b & d | c & d;
}
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t) {
return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key, data) {
var bkey = str2binb(key);
if (bkey.length > 16) {
bkey = core_sha1(bkey, key.length * 8);
}
var ipad = new Array(16),
opad = new Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8);
return core_sha1(opad.concat(hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function sha1_safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xFFFF;
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt) {
return num << cnt | num >>> 32 - cnt;
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str) {
var bin = [];
var mask = 255;
for (var i = 0; i < str.length * 8; i += 8) {
bin[i >> 5] |= (str.charCodeAt(i / 8) & mask) << 24 - i % 32;
}
return bin;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray) {
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
var triplet, j;
for (var i = 0; i < binarray.length * 4; i += 3) {
triplet = (binarray[i >> 2] >> 8 * (3 - i % 4) & 0xFF) << 16 | (binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4) & 0xFF) << 8 | binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4) & 0xFF;
for (j = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) {
str += "=";
} else {
str += tab.charAt(triplet >> 6 * (3 - j) & 0x3F);
}
}
}
return str;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin) {
var str = "";
var mask = 255;
for (var i = 0; i < bin.length * 32; i += 8) {
str += String.fromCharCode(bin[i >> 5] >>> 24 - i % 32 & mask);
}
return str;
}
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
const SHA1 = {
b64_hmac_sha1: function (key, data) {
return binb2b64(core_hmac_sha1(key, data));
},
b64_sha1: function (s) {
return binb2b64(core_sha1(str2binb(s), s.length * 8));
},
binb2str: binb2str,
core_hmac_sha1: core_hmac_sha1,
str_hmac_sha1: function (key, data) {
return binb2str(core_hmac_sha1(key, data));
},
str_sha1: function (s) {
return binb2str(core_sha1(str2binb(s), s.length * 8));
}
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-sha1.js
class SASLSHA1 extends SASLMechanism {
/** PrivateConstructor: SASLSHA1
* 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);
}
test(connection) {
// eslint-disable-line class-methods-use-this
return connection.authcid !== null;
}
onChallenge(connection, challenge) {
// eslint-disable-line class-methods-use-this
let nonce, salt, iter, Hi, U, U_old, i, k;
let responseText = "c=biws,";
let authMessage = `${connection._sasl_data["client-first-message-bare"]},${challenge},`;
const cnonce = connection._sasl_data.cnonce;
const attribMatch = /([a-z]+)=([^,]+)(,|$)/;
while (challenge.match(attribMatch)) {
const matches = challenge.match(attribMatch);
challenge = challenge.replace(matches[0], "");
switch (matches[1]) {
case "r":
nonce = matches[2];
break;
case "s":
salt = matches[2];
break;
case "i":
iter = matches[2];
break;
}
}
if (nonce.slice(0, cnonce.length) !== cnonce) {
connection._sasl_data = {};
return connection._sasl_failure_cb();
}
responseText += "r=" + nonce;
authMessage += responseText;
salt = atob(salt);
salt += "\x00\x00\x00\x01";
const pass = utils.utf16to8(connection.pass);
Hi = U_old = SHA1.core_hmac_sha1(pass, salt);
for (i = 1; i < iter; i++) {
U = SHA1.core_hmac_sha1(pass, SHA1.binb2str(U_old));
for (k = 0; k < 5; k++) {
Hi[k] ^= U[k];
}
U_old = U;
}
Hi = SHA1.binb2str(Hi);
const clientKey = SHA1.core_hmac_sha1(Hi, "Client Key");
const serverKey = SHA1.str_hmac_sha1(Hi, "Server Key");
const clientSignature = SHA1.core_hmac_sha1(SHA1.str_sha1(SHA1.binb2str(clientKey)), authMessage);
connection._sasl_data["server-signature"] = SHA1.b64_hmac_sha1(serverKey, authMessage);
for (k = 0; k < 5; k++) {
clientKey[k] ^= clientSignature[k];
}
responseText += ",p=" + btoa(SHA1.binb2str(clientKey));
return responseText;
}
clientChallenge(connection, test_cnonce) {
// eslint-disable-line class-methods-use-this
const cnonce = test_cnonce || MD5.hexdigest("" + Math.random() * 1234567890);
let auth_str = "n=" + utils.utf16to8(connection.authcid);
auth_str += ",r=";
auth_str += cnonce;
connection._sasl_data.cnonce = cnonce;
connection._sasl_data["client-first-message-bare"] = auth_str;
auth_str = "n,," + auth_str;
return auth_str;
}
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-xoauth2.js
class SASLXOAuth2 extends SASLMechanism {
/** PrivateConstructor: SASLXOAuth2
* 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);
}
test(connection) {
// eslint-disable-line class-methods-use-this
return connection.pass !== null;
}
onChallenge(connection) {
// eslint-disable-line class-methods-use-this
let auth_str = '\u0000';
if (connection.authcid !== null) {
auth_str = auth_str + connection.authzid;
}
auth_str = auth_str + "\u0000";
auth_str = auth_str + connection.pass;
return utils.utf16to8(auth_str);
}
}
// EXTERNAL MODULE: ./node_modules/abab/index.js
var abab = __webpack_require__(9494);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/core.js
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2018, OGG, LLC
*/
/*global define, document, sessionStorage, setTimeout, clearTimeout, ActiveXObject, DOMParser, btoa, atob */
/** Function: $build
* Create a Strophe.Builder.
* This is an alias for 'new Strophe.Builder(name, attrs)'.
*
* Parameters:
* (String) name - The root element name.
* (Object) attrs - The attributes for the root element in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $build(name, attrs) {
return new Strophe.Builder(name, attrs);
}
/** Function: $msg
* Create a Strophe.Builder with a element as the root.
*
* Parameters:
* (Object) attrs - The element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $msg(attrs) {
return new Strophe.Builder("message", attrs);
}
/** Function: $iq
* Create a Strophe.Builder with an element as the root.
*
* Parameters:
* (Object) attrs - The element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $iq(attrs) {
return new Strophe.Builder("iq", attrs);
}
/** Function: $pres
* Create a Strophe.Builder with a element as the root.
*
* Parameters:
* (Object) attrs - The element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $pres(attrs) {
return new Strophe.Builder("presence", attrs);
}
/** Class: Strophe
* An object container for all Strophe library functions.
*
* This class is just a container for all the objects and constants
* used in the library. It is not meant to be instantiated, but to
* provide a namespace for library objects, constants, and functions.
*/
const Strophe = {
/** Constant: VERSION */
VERSION: "1.5.0",
/** Constants: XMPP Namespace Constants
* Common namespace constants from the XMPP RFCs and XEPs.
*
* NS.HTTPBIND - HTTP BIND namespace from XEP 124.
* NS.BOSH - BOSH namespace from XEP 206.
* NS.CLIENT - Main XMPP client namespace.
* NS.AUTH - Legacy authentication namespace.
* NS.ROSTER - Roster operations namespace.
* NS.PROFILE - Profile namespace.
* NS.DISCO_INFO - Service discovery info namespace from XEP 30.
* NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
* NS.MUC - Multi-User Chat namespace from XEP 45.
* NS.SASL - XMPP SASL namespace from RFC 3920.
* NS.STREAM - XMPP Streams namespace from RFC 3920.
* NS.BIND - XMPP Binding namespace from RFC 3920 and RFC 6120.
* NS.SESSION - XMPP Session namespace from RFC 3920.
* NS.XHTML_IM - XHTML-IM namespace from XEP 71.
* NS.XHTML - XHTML body namespace from XEP 71.
*/
NS: {
HTTPBIND: "http://jabber.org/protocol/httpbind",
BOSH: "urn:xmpp:xbosh",
CLIENT: "jabber:client",
AUTH: "jabber:iq:auth",
ROSTER: "jabber:iq:roster",
PROFILE: "jabber:iq:profile",
DISCO_INFO: "http://jabber.org/protocol/disco#info",
DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
MUC: "http://jabber.org/protocol/muc",
SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
STREAM: "http://etherx.jabber.org/streams",
FRAMING: "urn:ietf:params:xml:ns:xmpp-framing",
BIND: "urn:ietf:params:xml:ns:xmpp-bind",
SESSION: "urn:ietf:params:xml:ns:xmpp-session",
VERSION: "jabber:iq:version",
STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas",
XHTML_IM: "http://jabber.org/protocol/xhtml-im",
XHTML: "http://www.w3.org/1999/xhtml"
},
/** Constants: XHTML_IM Namespace
* contains allowed tags, tag attributes, and css properties.
* Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset.
* See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended
* allowed tags and their attributes.
*/
XHTML: {
tags: ['a', 'blockquote', 'br', 'cite', 'em', 'img', 'li', 'ol', 'p', 'span', 'strong', 'ul', 'body'],
attributes: {
'a': ['href'],
'blockquote': ['style'],
'br': [],
'cite': ['style'],
'em': [],
'img': ['src', 'alt', 'style', 'height', 'width'],
'li': ['style'],
'ol': ['style'],
'p': ['style'],
'span': ['style'],
'strong': [],
'ul': ['style'],
'body': []
},
css: ['background-color', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'margin-left', 'margin-right', 'text-align', 'text-decoration'],
/** Function: XHTML.validTag
*
* Utility method to determine whether a tag is allowed
* in the XHTML_IM namespace.
*
* XHTML tag names are case sensitive and must be lower case.
*/
validTag(tag) {
for (let i = 0; i < Strophe.XHTML.tags.length; i++) {
if (tag === Strophe.XHTML.tags[i]) {
return true;
}
}
return false;
},
/** Function: XHTML.validAttribute
*
* Utility method to determine whether an attribute is allowed
* as recommended per XEP-0071
*
* XHTML attribute names are case sensitive and must be lower case.
*/
validAttribute(tag, attribute) {
if (typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) {
for (let i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
if (attribute === Strophe.XHTML.attributes[tag][i]) {
return true;
}
}
}
return false;
},
validCSS(style) {
for (let i = 0; i < Strophe.XHTML.css.length; i++) {
if (style === Strophe.XHTML.css[i]) {
return true;
}
}
return false;
}
},
/** Constants: Connection Status Constants
* Connection status constants for use by the connection handler
* callback.
*
* Status.ERROR - An error has occurred
* Status.CONNECTING - The connection is currently being made
* Status.CONNFAIL - The connection attempt failed
* Status.AUTHENTICATING - The connection is authenticating
* Status.AUTHFAIL - The authentication attempt failed
* Status.CONNECTED - The connection has succeeded
* Status.DISCONNECTED - The connection has been terminated
* Status.DISCONNECTING - The connection is currently being terminated
* Status.ATTACHED - The connection has been attached
* Status.REDIRECT - The connection has been redirected
* Status.CONNTIMEOUT - The connection has timed out
*/
Status: {
ERROR: 0,
CONNECTING: 1,
CONNFAIL: 2,
AUTHENTICATING: 3,
AUTHFAIL: 4,
CONNECTED: 5,
DISCONNECTED: 6,
DISCONNECTING: 7,
ATTACHED: 8,
REDIRECT: 9,
CONNTIMEOUT: 10,
BINDREQUIRED: 11,
ATTACHFAIL: 12
},
ErrorCondition: {
BAD_FORMAT: "bad-format",
CONFLICT: "conflict",
MISSING_JID_NODE: "x-strophe-bad-non-anon-jid",
NO_AUTH_MECH: "no-auth-mech",
UNKNOWN_REASON: "unknown"
},
/** Constants: Log Level Constants
* Logging level indicators.
*
* LogLevel.DEBUG - Debug output
* LogLevel.INFO - Informational output
* LogLevel.WARN - Warnings
* LogLevel.ERROR - Errors
* LogLevel.FATAL - Fatal errors
*/
LogLevel: {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
FATAL: 4
},
/** PrivateConstants: DOM Element Type Constants
* DOM element types.
*
* ElementType.NORMAL - Normal element.
* ElementType.TEXT - Text data element.
* ElementType.FRAGMENT - XHTML fragment element.
*/
ElementType: {
NORMAL: 1,
TEXT: 3,
CDATA: 4,
FRAGMENT: 11
},
/** PrivateConstants: Timeout Values
* Timeout values for error states. These values are in seconds.
* These should not be changed unless you know exactly what you are
* doing.
*
* TIMEOUT - Timeout multiplier. A waiting request will be considered
* failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
* This defaults to 1.1, and with default wait, 66 seconds.
* SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where
* Strophe can detect early failure, it will consider the request
* failed if it doesn't return after
* Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed.
* This defaults to 0.1, and with default wait, 6 seconds.
*/
TIMEOUT: 1.1,
SECONDARY_TIMEOUT: 0.1,
/** Function: addNamespace
* This function is used to extend the current namespaces in
* Strophe.NS. It takes a key and a value with the key being the
* name of the new namespace, with its actual value.
* For example:
* Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
*
* Parameters:
* (String) name - The name under which the namespace will be
* referenced under Strophe.NS
* (String) value - The actual namespace.
*/
addNamespace(name, value) {
Strophe.NS[name] = value;
},
/** Function: forEachChild
* Map a function over some or all child elements of a given element.
*
* This is a small convenience function for mapping a function over
* some or all of the children of an element. If elemName is null, all
* children will be passed to the function, otherwise only children
* whose tag names match elemName will be passed.
*
* Parameters:
* (XMLElement) elem - The element to operate on.
* (String) elemName - The child element tag name filter.
* (Function) func - The function to apply to each child. This
* function should take a single argument, a DOM element.
*/
forEachChild(elem, elemName, func) {
for (let i = 0; i < elem.childNodes.length; i++) {
const childNode = elem.childNodes[i];
if (childNode.nodeType === Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) {
func(childNode);
}
}
},
/** Function: isTagEqual
* Compare an element's tag name with a string.
*
* This function is case sensitive.
*
* Parameters:
* (XMLElement) el - A DOM element.
* (String) name - The element name.
*
* Returns:
* true if the element's tag name matches _el_, and false
* otherwise.
*/
isTagEqual(el, name) {
return el.tagName === name;
},
/** PrivateVariable: _xmlGenerator
* _Private_ variable that caches a DOM document to
* generate elements.
*/
_xmlGenerator: null,
/** Function: xmlGenerator
* Get the DOM document to generate elements.
*
* Returns:
* The currently used DOM document.
*/
xmlGenerator() {
if (!Strophe._xmlGenerator) {
Strophe._xmlGenerator = getDummyXMLDOMDocument();
}
return Strophe._xmlGenerator;
},
/** Function: xmlElement
* Create an XML DOM element.
*
* This function creates an XML DOM element correctly across all
* implementations. Note that these are not HTML DOM elements, which
* aren't appropriate for XMPP stanzas.
*
* Parameters:
* (String) name - The name for the element.
* (Array|Object) attrs - An optional array or object containing
* key/value pairs to use as element attributes. The object should
* be in the format {'key': 'value'} or {key: 'value'}. The array
* should have the format [['key1', 'value1'], ['key2', 'value2']].
* (String) text - The text child data for the element.
*
* Returns:
* A new XML DOM element.
*/
xmlElement(name) {
if (!name) {
return null;
}
const node = Strophe.xmlGenerator().createElement(name); // FIXME: this should throw errors if args are the wrong type or
// there are more than two optional args
for (let a = 1; a < arguments.length; a++) {
const arg = arguments[a];
if (!arg) {
continue;
}
if (typeof arg === "string" || typeof arg === "number") {
node.appendChild(Strophe.xmlTextNode(arg));
} else if (typeof arg === "object" && typeof arg.sort === "function") {
for (let i = 0; i < arg.length; i++) {
const attr = arg[i];
if (typeof attr === "object" && typeof attr.sort === "function" && attr[1] !== undefined && attr[1] !== null) {
node.setAttribute(attr[0], attr[1]);
}
}
} else if (typeof arg === "object") {
for (const k in arg) {
if (Object.prototype.hasOwnProperty.call(arg, k) && arg[k] !== undefined && arg[k] !== null) {
node.setAttribute(k, arg[k]);
}
}
}
}
return node;
},
/* Function: xmlescape
* Excapes invalid xml characters.
*
* Parameters:
* (String) text - text to escape.
*
* Returns:
* Escaped text.
*/
xmlescape(text) {
text = text.replace(/\&/g, "&");
text = text.replace(//g, ">");
text = text.replace(/'/g, "'");
text = text.replace(/"/g, """);
return text;
},
/* Function: xmlunescape
* Unexcapes invalid xml characters.
*
* Parameters:
* (String) text - text to unescape.
*
* Returns:
* Unescaped text.
*/
xmlunescape(text) {
text = text.replace(/\&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(/'/g, "'");
text = text.replace(/"/g, "\"");
return text;
},
/** Function: xmlTextNode
* Creates an XML DOM text node.
*
* Provides a cross implementation version of document.createTextNode.
*
* Parameters:
* (String) text - The content of the text node.
*
* Returns:
* A new XML DOM text node.
*/
xmlTextNode(text) {
return Strophe.xmlGenerator().createTextNode(text);
},
/** Function: xmlHtmlNode
* Creates an XML DOM html node.
*
* Parameters:
* (String) html - The content of the html node.
*
* Returns:
* A new XML DOM text node.
*/
xmlHtmlNode(html) {
let node; //ensure text is escaped
if (strophe_shims_DOMParser) {
const parser = new strophe_shims_DOMParser();
node = parser.parseFromString(html, "text/xml");
} else {
node = new ActiveXObject("Microsoft.XMLDOM");
node.async = "false";
node.loadXML(html);
}
return node;
},
/** Function: getText
* Get the concatenation of all text children of an element.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* A String with the concatenated text of all text element children.
*/
getText(elem) {
if (!elem) {
return null;
}
let str = "";
if (elem.childNodes.length === 0 && elem.nodeType === Strophe.ElementType.TEXT) {
str += elem.nodeValue;
}
for (let i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeType === Strophe.ElementType.TEXT) {
str += elem.childNodes[i].nodeValue;
}
}
return Strophe.xmlescape(str);
},
/** Function: copyElement
* Copy an XML DOM element.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* A new, copied DOM element tree.
*/
copyElement(elem) {
let el;
if (elem.nodeType === Strophe.ElementType.NORMAL) {
el = Strophe.xmlElement(elem.tagName);
for (let i = 0; i < elem.attributes.length; i++) {
el.setAttribute(elem.attributes[i].nodeName, elem.attributes[i].value);
}
for (let i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.copyElement(elem.childNodes[i]));
}
} else if (elem.nodeType === Strophe.ElementType.TEXT) {
el = Strophe.xmlGenerator().createTextNode(elem.nodeValue);
}
return el;
},
/** Function: createHtml
* Copy an HTML DOM element into an XML DOM.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
*
* Parameters:
* (HTMLElement) elem - A DOM element.
*
* Returns:
* A new, copied DOM element tree.
*/
createHtml(elem) {
let el;
if (elem.nodeType === Strophe.ElementType.NORMAL) {
const tag = elem.nodeName.toLowerCase(); // XHTML tags must be lower case.
if (Strophe.XHTML.validTag(tag)) {
try {
el = Strophe.xmlElement(tag);
for (let i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
const attribute = Strophe.XHTML.attributes[tag][i];
let value = elem.getAttribute(attribute);
if (typeof value === 'undefined' || value === null || value === '' || value === false || value === 0) {
continue;
}
if (attribute === 'style' && typeof value === 'object' && typeof value.cssText !== 'undefined') {
value = value.cssText; // we're dealing with IE, need to get CSS out
} // filter out invalid css styles
if (attribute === 'style') {
const css = [];
const cssAttrs = value.split(';');
for (let j = 0; j < cssAttrs.length; j++) {
const attr = cssAttrs[j].split(':');
const cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();
if (Strophe.XHTML.validCSS(cssName)) {
const cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
css.push(cssName + ': ' + cssValue);
}
}
if (css.length > 0) {
value = css.join('; ');
el.setAttribute(attribute, value);
}
} else {
el.setAttribute(attribute, value);
}
}
for (let i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
} catch (e) {
// invalid elements
el = Strophe.xmlTextNode('');
}
} else {
el = Strophe.xmlGenerator().createDocumentFragment();
for (let i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
}
} else if (elem.nodeType === Strophe.ElementType.FRAGMENT) {
el = Strophe.xmlGenerator().createDocumentFragment();
for (let i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
} else if (elem.nodeType === Strophe.ElementType.TEXT) {
el = Strophe.xmlTextNode(elem.nodeValue);
}
return el;
},
/** Function: escapeNode
* Escape the node part (also called local part) of a JID.
*
* Parameters:
* (String) node - A node (or local part).
*
* Returns:
* An escaped node (or local part).
*/
escapeNode(node) {
if (typeof node !== "string") {
return node;
}
return node.replace(/^\s+|\s+$/g, '').replace(/\\/g, "\\5c").replace(/ /g, "\\20").replace(/\"/g, "\\22").replace(/\&/g, "\\26").replace(/\'/g, "\\27").replace(/\//g, "\\2f").replace(/:/g, "\\3a").replace(//g, "\\3e").replace(/@/g, "\\40");
},
/** Function: unescapeNode
* Unescape a node part (also called local part) of a JID.
*
* Parameters:
* (String) node - A node (or local part).
*
* Returns:
* An unescaped node (or local part).
*/
unescapeNode(node) {
if (typeof node !== "string") {
return node;
}
return node.replace(/\\20/g, " ").replace(/\\22/g, '"').replace(/\\26/g, "&").replace(/\\27/g, "'").replace(/\\2f/g, "/").replace(/\\3a/g, ":").replace(/\\3c/g, "<").replace(/\\3e/g, ">").replace(/\\40/g, "@").replace(/\\5c/g, "\\");
},
/** Function: getNodeFromJid
* Get the node portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the node.
*/
getNodeFromJid(jid) {
if (jid.indexOf("@") < 0) {
return null;
}
return jid.split("@")[0];
},
/** Function: getDomainFromJid
* Get the domain portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the domain.
*/
getDomainFromJid(jid) {
const bare = Strophe.getBareJidFromJid(jid);
if (bare.indexOf("@") < 0) {
return bare;
} else {
const parts = bare.split("@");
parts.splice(0, 1);
return parts.join('@');
}
},
/** Function: getResourceFromJid
* Get the resource portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the resource.
*/
getResourceFromJid(jid) {
if (!jid) {
return null;
}
const s = jid.split("/");
if (s.length < 2) {
return null;
}
s.splice(0, 1);
return s.join('/');
},
/** Function: getBareJidFromJid
* Get the bare JID from a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the bare JID.
*/
getBareJidFromJid(jid) {
return jid ? jid.split("/")[0] : null;
},
/** PrivateFunction: _handleError
* _Private_ function that properly logs an error to the console
*/
_handleError(e) {
if (typeof e.stack !== "undefined") {
Strophe.fatal(e.stack);
}
if (e.sourceURL) {
Strophe.fatal("error: " + this.handler + " " + e.sourceURL + ":" + e.line + " - " + e.name + ": " + e.message);
} else if (e.fileName) {
Strophe.fatal("error: " + this.handler + " " + e.fileName + ":" + e.lineNumber + " - " + e.name + ": " + e.message);
} else {
Strophe.fatal("error: " + e.message);
}
},
/** Function: log
* User overrideable logging function.
*
* This function is called whenever the Strophe library calls any
* of the logging functions. The default implementation of this
* function logs only fatal errors. If client code wishes to handle the logging
* messages, it should override this with
* > Strophe.log = function (level, msg) {
* > (user code here)
* > };
*
* Please note that data sent and received over the wire is logged
* via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().
*
* The different levels and their meanings are
*
* DEBUG - Messages useful for debugging purposes.
* INFO - Informational messages. This is mostly information like
* 'disconnect was called' or 'SASL auth succeeded'.
* WARN - Warnings about potential problems. This is mostly used
* to report transient connection errors like request timeouts.
* ERROR - Some error occurred.
* FATAL - A non-recoverable fatal error occurred.
*
* Parameters:
* (Integer) level - The log level of the log message. This will
* be one of the values in Strophe.LogLevel.
* (String) msg - The log message.
*/
log(level, msg) {
if (level === this.LogLevel.FATAL) {
var _console;
(_console = console) === null || _console === void 0 ? void 0 : _console.error(msg);
}
},
/** Function: debug
* Log a message at the Strophe.LogLevel.DEBUG level.
*
* Parameters:
* (String) msg - The log message.
*/
debug(msg) {
this.log(this.LogLevel.DEBUG, msg);
},
/** Function: info
* Log a message at the Strophe.LogLevel.INFO level.
*
* Parameters:
* (String) msg - The log message.
*/
info(msg) {
this.log(this.LogLevel.INFO, msg);
},
/** Function: warn
* Log a message at the Strophe.LogLevel.WARN level.
*
* Parameters:
* (String) msg - The log message.
*/
warn(msg) {
this.log(this.LogLevel.WARN, msg);
},
/** Function: error
* Log a message at the Strophe.LogLevel.ERROR level.
*
* Parameters:
* (String) msg - The log message.
*/
error(msg) {
this.log(this.LogLevel.ERROR, msg);
},
/** Function: fatal
* Log a message at the Strophe.LogLevel.FATAL level.
*
* Parameters:
* (String) msg - The log message.
*/
fatal(msg) {
this.log(this.LogLevel.FATAL, msg);
},
/** Function: serialize
* Render a DOM element and all descendants to a String.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* The serialized element tree as a String.
*/
serialize(elem) {
if (!elem) {
return null;
}
if (typeof elem.tree === "function") {
elem = elem.tree();
}
const names = [...Array(elem.attributes.length).keys()].map(i => elem.attributes[i].nodeName);
names.sort();
let result = names.reduce((a, n) => `${a} ${n}="${Strophe.xmlescape(elem.attributes.getNamedItem(n).value)}"`, `<${elem.nodeName}`);
if (elem.childNodes.length > 0) {
result += ">";
for (let i = 0; i < elem.childNodes.length; i++) {
const child = elem.childNodes[i];
switch (child.nodeType) {
case Strophe.ElementType.NORMAL:
// normal element, so recurse
result += Strophe.serialize(child);
break;
case Strophe.ElementType.TEXT:
// text element to escape values
result += Strophe.xmlescape(child.nodeValue);
break;
case Strophe.ElementType.CDATA:
// cdata section so don't escape values
result += "";
}
}
result += "" + elem.nodeName + ">";
} else {
result += "/>";
}
return result;
},
/** PrivateVariable: _requestId
* _Private_ variable that keeps track of the request ids for
* connections.
*/
_requestId: 0,
/** PrivateVariable: Strophe.connectionPlugins
* _Private_ variable Used to store plugin names that need
* initialization on Strophe.Connection construction.
*/
_connectionPlugins: {},
/** Function: addConnectionPlugin
* Extends the Strophe.Connection object with the given plugin.
*
* Parameters:
* (String) name - The name of the extension.
* (Object) ptype - The plugin's prototype.
*/
addConnectionPlugin(name, ptype) {
Strophe._connectionPlugins[name] = ptype;
}
};
/** Class: Strophe.Builder
* XML DOM builder.
*
* This object provides an interface similar to JQuery but for building
* DOM elements easily and rapidly. All the functions except for toString()
* and tree() return the object, so calls can be chained. Here's an
* example using the $iq() builder helper.
* > $iq({to: 'you', from: 'me', type: 'get', id: '1'})
* > .c('query', {xmlns: 'strophe:example'})
* > .c('example')
* > .toString()
*
* The above generates this XML fragment
* >
* >
* >
* >
* >
* The corresponding DOM manipulations to get a similar fragment would be
* a lot more tedious and probably involve several helper variables.
*
* Since adding children makes new operations operate on the child, up()
* is provided to traverse up the tree. To add two children, do
* > builder.c('child1', ...).up().c('child2', ...)
* The next operation on the Builder will be relative to the second child.
*/
/** Constructor: Strophe.Builder
* Create a Strophe.Builder object.
*
* The attributes should be passed in object notation. For example
* > let b = new Builder('message', {to: 'you', from: 'me'});
* or
* > let b = new Builder('messsage', {'xml:lang': 'en'});
*
* Parameters:
* (String) name - The name of the root element.
* (Object) attrs - The attributes for the root element in object notation.
*
* Returns:
* A new Strophe.Builder.
*/
Strophe.Builder = class Builder {
constructor(name, attrs) {
// Set correct namespace for jabber:client elements
if (name === "presence" || name === "message" || name === "iq") {
if (attrs && !attrs.xmlns) {
attrs.xmlns = Strophe.NS.CLIENT;
} else if (!attrs) {
attrs = {
xmlns: Strophe.NS.CLIENT
};
}
} // Holds the tree being built.
this.nodeTree = Strophe.xmlElement(name, attrs); // Points to the current operation node.
this.node = this.nodeTree;
}
/** Function: tree
* Return the DOM tree.
*
* This function returns the current DOM tree as an element object. This
* is suitable for passing to functions like Strophe.Connection.send().
*
* Returns:
* The DOM tree as a element object.
*/
tree() {
return this.nodeTree;
}
/** Function: toString
* Serialize the DOM tree to a String.
*
* This function returns a string serialization of the current DOM
* tree. It is often used internally to pass data to a
* Strophe.Request object.
*
* Returns:
* The serialized DOM tree in a String.
*/
toString() {
return Strophe.serialize(this.nodeTree);
}
/** Function: up
* Make the current parent element the new current element.
*
* This function is often used after c() to traverse back up the tree.
* For example, to add two children to the same element
* > builder.c('child1', {}).up().c('child2', {});
*
* Returns:
* The Stophe.Builder object.
*/
up() {
this.node = this.node.parentNode;
return this;
}
/** Function: root
* Make the root element the new current element.
*
* When at a deeply nested element in the tree, this function can be used
* to jump back to the root of the tree, instead of having to repeatedly
* call up().
*
* Returns:
* The Stophe.Builder object.
*/
root() {
this.node = this.nodeTree;
return this;
}
/** Function: attrs
* Add or modify attributes of the current element.
*
* The attributes should be passed in object notation. This function
* does not move the current element pointer.
*
* Parameters:
* (Object) moreattrs - The attributes to add/modify in object notation.
*
* Returns:
* The Strophe.Builder object.
*/
attrs(moreattrs) {
for (const k in moreattrs) {
if (Object.prototype.hasOwnProperty.call(moreattrs, k)) {
if (moreattrs[k] === undefined) {
this.node.removeAttribute(k);
} else {
this.node.setAttribute(k, moreattrs[k]);
}
}
}
return this;
}
/** Function: c
* Add a child to the current element and make it the new current
* element.
*
* This function moves the current element pointer to the child,
* unless text is provided. If you need to add another child, it
* is necessary to use up() to go back to the parent in the tree.
*
* Parameters:
* (String) name - The name of the child.
* (Object) attrs - The attributes of the child in object notation.
* (String) text - The text to add to the child.
*
* Returns:
* The Strophe.Builder object.
*/
c(name, attrs, text) {
const child = Strophe.xmlElement(name, attrs, text);
this.node.appendChild(child);
if (typeof text !== "string" && typeof text !== "number") {
this.node = child;
}
return this;
}
/** Function: cnode
* Add a child to the current element and make it the new current
* element.
*
* This function is the same as c() except that instead of using a
* name and an attributes object to create the child it uses an
* existing DOM element object.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* The Strophe.Builder object.
*/
cnode(elem) {
let impNode;
const xmlGen = Strophe.xmlGenerator();
try {
impNode = xmlGen.importNode !== undefined;
} catch (e) {
impNode = false;
}
const newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem);
this.node.appendChild(newElem);
this.node = newElem;
return this;
}
/** Function: t
* Add a child text element.
*
* This *does not* make the child the new current element since there
* are no children of text elements.
*
* Parameters:
* (String) text - The text data to append to the current element.
*
* Returns:
* The Strophe.Builder object.
*/
t(text) {
const child = Strophe.xmlTextNode(text);
this.node.appendChild(child);
return this;
}
/** Function: h
* Replace current element contents with the HTML passed in.
*
* This *does not* make the child the new current element
*
* Parameters:
* (String) html - The html to insert as contents of current element.
*
* Returns:
* The Strophe.Builder object.
*/
h(html) {
const fragment = Strophe.xmlGenerator().createElement('body'); // force the browser to try and fix any invalid HTML tags
fragment.innerHTML = html; // copy cleaned html into an xml dom
const xhtml = Strophe.createHtml(fragment);
while (xhtml.childNodes.length > 0) {
this.node.appendChild(xhtml.childNodes[0]);
}
return this;
}
};
/** PrivateClass: Strophe.Handler
* _Private_ helper class for managing stanza handlers.
*
* A Strophe.Handler encapsulates a user provided callback function to be
* executed when matching stanzas are received by the connection.
* Handlers can be either one-off or persistant depending on their
* return value. Returning true will cause a Handler to remain active, and
* returning false will remove the Handler.
*
* Users will not use Strophe.Handler objects directly, but instead they
* will use Strophe.Connection.addHandler() and
* Strophe.Connection.deleteHandler().
*/
/** PrivateConstructor: Strophe.Handler
* Create and initialize a new Strophe.Handler.
*
* Parameters:
* (Function) handler - A function to be executed when the handler is run.
* (String) ns - The namespace to match.
* (String) name - The element name to match.
* (String) type - The element type to match.
* (String) id - The element id attribute to match.
* (String) from - The element from attribute to match.
* (Object) options - Handler options
*
* Returns:
* A new Strophe.Handler object.
*/
Strophe.Handler = function (handler, ns, name, type, id, from, options) {
this.handler = handler;
this.ns = ns;
this.name = name;
this.type = type;
this.id = id;
this.options = options || {
'matchBareFromJid': false,
'ignoreNamespaceFragment': false
}; // BBB: Maintain backward compatibility with old `matchBare` option
if (this.options.matchBare) {
Strophe.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.');
this.options.matchBareFromJid = this.options.matchBare;
delete this.options.matchBare;
}
if (this.options.matchBareFromJid) {
this.from = from ? Strophe.getBareJidFromJid(from) : null;
} else {
this.from = from;
} // whether the handler is a user handler or a system handler
this.user = true;
};
Strophe.Handler.prototype = {
/** PrivateFunction: getNamespace
* Returns the XML namespace attribute on an element.
* If `ignoreNamespaceFragment` was passed in for this handler, then the
* URL fragment will be stripped.
*
* Parameters:
* (XMLElement) elem - The XML element with the namespace.
*
* Returns:
* The namespace, with optionally the fragment stripped.
*/
getNamespace(elem) {
let elNamespace = elem.getAttribute("xmlns");
if (elNamespace && this.options.ignoreNamespaceFragment) {
elNamespace = elNamespace.split('#')[0];
}
return elNamespace;
},
/** PrivateFunction: namespaceMatch
* Tests if a stanza matches the namespace set for this Strophe.Handler.
*
* Parameters:
* (XMLElement) elem - The XML element to test.
*
* Returns:
* true if the stanza matches and false otherwise.
*/
namespaceMatch(elem) {
let nsMatch = false;
if (!this.ns) {
return true;
} else {
Strophe.forEachChild(elem, null, elem => {
if (this.getNamespace(elem) === this.ns) {
nsMatch = true;
}
});
return nsMatch || this.getNamespace(elem) === this.ns;
}
},
/** PrivateFunction: isMatch
* Tests if a stanza matches the Strophe.Handler.
*
* Parameters:
* (XMLElement) elem - The XML element to test.
*
* Returns:
* true if the stanza matches and false otherwise.
*/
isMatch(elem) {
let from = elem.getAttribute('from');
if (this.options.matchBareFromJid) {
from = Strophe.getBareJidFromJid(from);
}
const elem_type = elem.getAttribute("type");
if (this.namespaceMatch(elem) && (!this.name || Strophe.isTagEqual(elem, this.name)) && (!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) !== -1 : elem_type === this.type)) && (!this.id || elem.getAttribute("id") === this.id) && (!this.from || from === this.from)) {
return true;
}
return false;
},
/** PrivateFunction: run
* Run the callback on a matching stanza.
*
* Parameters:
* (XMLElement) elem - The DOM element that triggered the
* Strophe.Handler.
*
* Returns:
* A boolean indicating if the handler should remain active.
*/
run(elem) {
let result = null;
try {
result = this.handler(elem);
} catch (e) {
Strophe._handleError(e);
throw e;
}
return result;
},
/** PrivateFunction: toString
* Get a String representation of the Strophe.Handler object.
*
* Returns:
* A String.
*/
toString() {
return "{Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ")}";
}
};
/** PrivateClass: Strophe.TimedHandler
* _Private_ helper class for managing timed handlers.
*
* A Strophe.TimedHandler encapsulates a user provided callback that
* should be called after a certain period of time or at regular
* intervals. The return value of the callback determines whether the
* Strophe.TimedHandler will continue to fire.
*
* Users will not use Strophe.TimedHandler objects directly, but instead
* they will use Strophe.Connection.addTimedHandler() and
* Strophe.Connection.deleteTimedHandler().
*/
Strophe.TimedHandler = class TimedHandler {
/** PrivateConstructor: Strophe.TimedHandler
* Create and initialize a new Strophe.TimedHandler object.
*
* Parameters:
* (Integer) period - The number of milliseconds to wait before the
* handler is called.
* (Function) handler - The callback to run when the handler fires. This
* function should take no arguments.
*
* Returns:
* A new Strophe.TimedHandler object.
*/
constructor(period, handler) {
this.period = period;
this.handler = handler;
this.lastCalled = new Date().getTime();
this.user = true;
}
/** PrivateFunction: run
* Run the callback for the Strophe.TimedHandler.
*
* Returns:
* true if the Strophe.TimedHandler should be called again, and false
* otherwise.
*/
run() {
this.lastCalled = new Date().getTime();
return this.handler();
}
/** PrivateFunction: reset
* Reset the last called time for the Strophe.TimedHandler.
*/
reset() {
this.lastCalled = new Date().getTime();
}
/** PrivateFunction: toString
* Get a string representation of the Strophe.TimedHandler object.
*
* Returns:
* The string representation.
*/
toString() {
return "{TimedHandler: " + this.handler + "(" + this.period + ")}";
}
};
/** Class: Strophe.Connection
* XMPP Connection manager.
*
* This class is the main part of Strophe. It manages a BOSH or websocket
* connection to an XMPP server and dispatches events to the user callbacks
* as data arrives. It supports SASL PLAIN, SASL SCRAM-SHA-1
* and legacy authentication.
*
* After creating a Strophe.Connection object, the user will typically
* call connect() with a user supplied callback to handle connection level
* events like authentication failure, disconnection, or connection
* complete.
*
* The user will also have several event handlers defined by using
* addHandler() and addTimedHandler(). These will allow the user code to
* respond to interesting stanzas or do something periodically with the
* connection. These handlers will be active once authentication is
* finished.
*
* To send data to the connection, use send().
*/
/** Constructor: Strophe.Connection
* Create and initialize a Strophe.Connection object.
*
* The transport-protocol for this connection will be chosen automatically
* based on the given service parameter. URLs starting with "ws://" or
* "wss://" will use WebSockets, URLs starting with "http://", "https://"
* or without a protocol will use BOSH.
*
* To make Strophe connect to the current host you can leave out the protocol
* and host part and just pass the path, e.g.
*
* > let conn = new Strophe.Connection("/http-bind/");
*
* Options common to both Websocket and BOSH:
* ------------------------------------------
*
* cookies:
*
* The *cookies* option allows you to pass in cookies to be added to the
* document. These cookies will then be included in the BOSH XMLHttpRequest
* or in the websocket connection.
*
* The passed in value must be a map of cookie names and string values.
*
* > { "myCookie": {
* > "value": "1234",
* > "domain": ".example.org",
* > "path": "/",
* > "expires": expirationDate
* > }
* > }
*
* Note that cookies can't be set in this way for other domains (i.e. cross-domain).
* Those cookies need to be set under those domains, for example they can be
* set server-side by making a XHR call to that domain to ask it to set any
* necessary cookies.
*
* mechanisms:
*
* The *mechanisms* option allows you to specify the SASL mechanisms that this
* instance of Strophe.Connection (and therefore your XMPP client) will
* support.
*
* The value must be an array of objects with Strophe.SASLMechanism
* prototypes.
*
* If nothing is specified, then the following mechanisms (and their
* priorities) are registered:
*
* SCRAM-SHA-1 - 60
* PLAIN - 50
* OAUTHBEARER - 40
* X-OAUTH2 - 30
* ANONYMOUS - 20
* EXTERNAL - 10
*
* explicitResourceBinding:
*
* If `explicitResourceBinding` is set to a truthy value, then the XMPP client
* needs to explicitly call `Strophe.Connection.prototype.bind` once the XMPP
* server has advertised the "urn:ietf:params:xml:ns:xmpp-bind" feature.
*
* Making this step explicit allows client authors to first finish other
* stream related tasks, such as setting up an XEP-0198 Stream Management
* session, before binding the JID resource for this session.
*
* WebSocket options:
* ------------------
*
* protocol:
*
* If you want to connect to the current host with a WebSocket connection you
* can tell Strophe to use WebSockets through a "protocol" attribute in the
* optional options parameter. Valid values are "ws" for WebSocket and "wss"
* for Secure WebSocket.
* So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call
*
* > let conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"});
*
* Note that relative URLs _NOT_ starting with a "/" will also include the path
* of the current site.
*
* Also because downgrading security is not permitted by browsers, when using
* relative URLs both BOSH and WebSocket connections will use their secure
* variants if the current connection to the site is also secure (https).
*
* worker:
*
* Set this option to URL from where the shared worker script should be loaded.
*
* To run the websocket connection inside a shared worker.
* This allows you to share a single websocket-based connection between
* multiple Strophe.Connection instances, for example one per browser tab.
*
* The script to use is the one in `src/shared-connection-worker.js`.
*
* BOSH options:
* -------------
*
* By adding "sync" to the options, you can control if requests will
* be made synchronously or not. The default behaviour is asynchronous.
* If you want to make requests synchronous, make "sync" evaluate to true.
* > let conn = new Strophe.Connection("/http-bind/", {sync: true});
*
* You can also toggle this on an already established connection.
* > conn.options.sync = true;
*
* The *customHeaders* option can be used to provide custom HTTP headers to be
* included in the XMLHttpRequests made.
*
* The *keepalive* option can be used to instruct Strophe to maintain the
* current BOSH session across interruptions such as webpage reloads.
*
* It will do this by caching the sessions tokens in sessionStorage, and when
* "restore" is called it will check whether there are cached tokens with
* which it can resume an existing session.
*
* The *withCredentials* option should receive a Boolean value and is used to
* indicate wether cookies should be included in ajax requests (by default
* they're not).
* Set this value to true if you are connecting to a BOSH service
* and for some reason need to send cookies to it.
* In order for this to work cross-domain, the server must also enable
* credentials by setting the Access-Control-Allow-Credentials response header
* to "true". For most usecases however this setting should be false (which
* is the default).
* Additionally, when using Access-Control-Allow-Credentials, the
* Access-Control-Allow-Origin header can't be set to the wildcard "*", but
* instead must be restricted to actual domains.
*
* The *contentType* option can be set to change the default Content-Type
* of "text/xml; charset=utf-8", which can be useful to reduce the amount of
* CORS preflight requests that are sent to the server.
*
* Parameters:
* (String) service - The BOSH or WebSocket service URL.
* (Object) options - A hash of configuration options
*
* Returns:
* A new Strophe.Connection object.
*/
Strophe.Connection = class Connection {
constructor(service, options) {
// The service URL
this.service = service; // Configuration options
this.options = options || {};
this.setProtocol();
/* The connected JID. */
this.jid = "";
/* the JIDs domain */
this.domain = null;
/* stream:features */
this.features = null; // SASL
this._sasl_data = {};
this.do_bind = false;
this.do_session = false;
this.mechanisms = {}; // handler lists
this.timedHandlers = [];
this.handlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
this.protocolErrorHandlers = {
'HTTP': {},
'websocket': {}
};
this._idleTimeout = null;
this._disconnectTimeout = null;
this.authenticated = false;
this.connected = false;
this.disconnecting = false;
this.do_authentication = true;
this.paused = false;
this.restored = false;
this._data = [];
this._uniqueId = 0;
this._sasl_success_handler = null;
this._sasl_failure_handler = null;
this._sasl_challenge_handler = null; // Max retries before disconnecting
this.maxRetries = 5; // Call onIdle callback every 1/10th of a second
this._idleTimeout = setTimeout(() => this._onIdle(), 100);
utils.addCookies(this.options.cookies);
this.registerSASLMechanisms(this.options.mechanisms); // 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 Strophe.Handler(iq => this.send($iq({
type: 'error',
id: iq.getAttribute('id')
}).c('error', {
'type': 'cancel'
}).c('service-unavailable', {
'xmlns': Strophe.NS.STANZAS
})), null, 'iq', ['get', 'set']); // initialize plugins
for (const k in Strophe._connectionPlugins) {
if (Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins, k)) {
const F = function () {};
F.prototype = Strophe._connectionPlugins[k];
this[k] = new F();
this[k].init(this);
}
}
}
/** Function: setProtocol
* Select protocal based on this.options or this.service
*/
setProtocol() {
const proto = this.options.protocol || "";
if (this.options.worker) {
this._proto = new Strophe.WorkerWebsocket(this);
} else if (this.service.indexOf("ws:") === 0 || this.service.indexOf("wss:") === 0 || proto.indexOf("ws") === 0) {
this._proto = new Strophe.Websocket(this);
} else {
this._proto = new Strophe.Bosh(this);
}
}
/** Function: reset
* Reset the connection.
*
* This function should be called after a connection is disconnected
* before that connection is reused.
*/
reset() {
this._proto._reset(); // SASL
this.do_session = false;
this.do_bind = false; // handler lists
this.timedHandlers = [];
this.handlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
this.authenticated = false;
this.connected = false;
this.disconnecting = false;
this.restored = false;
this._data = [];
this._requests = [];
this._uniqueId = 0;
}
/** Function: pause
* Pause the request manager.
*
* This will prevent Strophe from sending any more requests to the
* server. This is very useful for temporarily pausing
* BOSH-Connections while a lot of send() calls are happening quickly.
* This causes Strophe to send the data in a single request, saving
* many request trips.
*/
pause() {
this.paused = true;
}
/** Function: resume
* Resume the request manager.
*
* This resumes after pause() has been called.
*/
resume() {
this.paused = false;
}
/** Function: getUniqueId
* Generate a unique ID for use in elements.
*
* All stanzas are required to have unique id attributes. This
* function makes creating these easy. Each connection instance has
* a counter which starts from zero, and the value of this counter
* plus a colon followed by the suffix becomes the unique id. If no
* suffix is supplied, the counter is used as the unique id.
*
* Suffixes are used to make debugging easier when reading the stream
* data, and their use is recommended. The counter resets to 0 for
* every new connection for the same reason. For connections to the
* same server that authenticate the same way, all the ids should be
* the same, which makes it easy to see changes. This is useful for
* automated testing as well.
*
* Parameters:
* (String) suffix - A optional suffix to append to the id.
*
* Returns:
* A unique string to be used for the id attribute.
*/
getUniqueId(suffix) {
// eslint-disable-line class-methods-use-this
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0,
v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
if (typeof suffix === "string" || typeof suffix === "number") {
return uuid + ":" + suffix;
} else {
return uuid + "";
}
}
/** Function: addProtocolErrorHandler
* Register a handler function for when a protocol (websocker or HTTP)
* error occurs.
*
* NOTE: Currently only HTTP errors for BOSH requests are handled.
* Patches that handle websocket errors would be very welcome.
*
* Parameters:
* (String) protocol - 'HTTP' or 'websocket'
* (Integer) status_code - Error status code (e.g 500, 400 or 404)
* (Function) callback - Function that will fire on Http error
*
* Example:
* function onError(err_code){
* //do stuff
* }
*
* let conn = Strophe.connect('http://example.com/http-bind');
* conn.addProtocolErrorHandler('HTTP', 500, onError);
* // Triggers HTTP 500 error and onError handler will be called
* conn.connect('user_jid@incorrect_jabber_host', 'secret', onConnect);
*/
addProtocolErrorHandler(protocol, status_code, callback) {
this.protocolErrorHandlers[protocol][status_code] = callback;
}
/** Function: connect
* Starts the connection process.
*
* As the connection process proceeds, the user supplied callback will
* be triggered multiple times with status updates. The callback
* should take two arguments - the status code and the error condition.
*
* The status code will be one of the values in the Strophe.Status
* constants. The error condition will be one of the conditions
* defined in RFC 3920 or the condition 'strophe-parsererror'.
*
* The Parameters _wait_, _hold_ and _route_ are optional and only relevant
* for BOSH connections. Please see XEP 124 for a more detailed explanation
* of the optional parameters.
*
* Parameters:
* (String) jid - The user's JID. This may be a bare JID,
* or a full JID. If a node is not supplied, SASL OAUTHBEARER or
* SASL ANONYMOUS authentication will be attempted (OAUTHBEARER will
* process the provided password value as an access token).
* (String) pass - The user's password.
* (Function) callback - The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (String) route - The optional route value.
* (String) authcid - The optional alternative authentication identity
* (username) if intending to impersonate another user.
* When using the SASL-EXTERNAL authentication mechanism, for example
* with client certificates, then the authcid value is used to
* determine whether an authorization JID (authzid) should be sent to
* the server. The authzid should NOT be sent to the server if the
* authzid and authcid are the same. So to prevent it from being sent
* (for example when the JID is already contained in the client
* certificate), set authcid to that same JID. See XEP-178 for more
* details.
* (Integer) disconnection_timeout - 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;
/** Variable: authzid
* Authorization identity.
*/
this.authzid = Strophe.getBareJidFromJid(this.jid);
/** Variable: authcid
* Authentication identity (User name).
*/
this.authcid = authcid || Strophe.getNodeFromJid(this.jid);
/** Variable: pass
* Authentication identity (User password).
*/
this.pass = pass;
this.connect_callback = callback;
this.disconnecting = false;
this.connected = false;
this.authenticated = false;
this.restored = false;
this.disconnection_timeout = disconnection_timeout; // parse jid for domain
this.domain = Strophe.getDomainFromJid(this.jid);
this._changeConnectStatus(Strophe.Status.CONNECTING, null);
this._proto._connect(wait, hold, route);
}
/** Function: attach
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* (String) sid - The SID of the BOSH session.
* (String) rid - The current RID of the BOSH session. This RID
* will be used by the next request.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
attach(jid, sid, rid, callback, wait, hold, wind) {
if (this._proto._attach) {
return this._proto._attach(jid, sid, rid, callback, wait, hold, wind);
} else {
const error = new Error('The "attach" method is not available for your connection protocol');
error.name = 'StropheSessionError';
throw error;
}
}
/** Function: restore
* Attempt to restore a cached BOSH session.
*
* This function is only useful in conjunction with providing the
* "keepalive":true option when instantiating a new Strophe.Connection.
*
* When "keepalive" is set to true, Strophe will cache the BOSH tokens
* RID (Request ID) and SID (Session ID) and then when this function is
* called, it will attempt to restore the session from those cached
* tokens.
*
* This function must therefore be called instead of connect or attach.
*
* For an example on how to use it, please see examples/restore.js
*
* Parameters:
* (String) jid - The user's JID. This may be a bare JID or a full JID.
* (Function) callback - The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
restore(jid, callback, wait, hold, wind) {
if (this._sessionCachingSupported()) {
this._proto._restore(jid, callback, wait, hold, wind);
} else {
const error = new Error('The "restore" method can only be used with a BOSH connection.');
error.name = 'StropheSessionError';
throw error;
}
}
/** PrivateFunction: _sessionCachingSupported
* Checks whether sessionStorage and JSON are supported and whether we're
* using BOSH.
*/
_sessionCachingSupported() {
if (this._proto instanceof Strophe.Bosh) {
if (!JSON) {
return false;
}
try {
sessionStorage.setItem('_strophe_', '_strophe_');
sessionStorage.removeItem('_strophe_');
} catch (e) {
return false;
}
return true;
}
return false;
}
/** Function: xmlInput
* User overrideable function that receives XML data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlInput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a tag. See
* if you want to strip this tag.
*
* Parameters:
* (XMLElement) elem - The XML data received by the connection.
*/
xmlInput(elem) {
// eslint-disable-line
return;
}
/** Function: xmlOutput
* User overrideable function that receives XML data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlOutput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a tag. See
* if you want to strip this tag.
*
* Parameters:
* (XMLElement) elem - The XMLdata sent by the connection.
*/
xmlOutput(elem) {
// eslint-disable-line
return;
}
/** Function: rawInput
* User overrideable function that receives raw data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawInput = function (data) {
* > (user code)
* > };
*
* Parameters:
* (String) data - The data received by the connection.
*/
rawInput(data) {
// eslint-disable-line
return;
}
/** Function: rawOutput
* User overrideable function that receives raw data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawOutput = function (data) {
* > (user code)
* > };
*
* Parameters:
* (String) data - The data sent by the connection.
*/
rawOutput(data) {
// eslint-disable-line
return;
}
/** Function: nextValidRid
* User overrideable function that receives the new valid rid.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.nextValidRid = function (rid) {
* > (user code)
* > };
*
* Parameters:
* (Number) rid - The next valid rid
*/
nextValidRid(rid) {
// eslint-disable-line
return;
}
/** Function: send
* Send a stanza.
*
* This function is called to push data onto the send queue to
* go out over the wire. Whenever a request is sent to the BOSH
* server, all pending data is sent and the queue is flushed.
*
* Parameters:
* (XMLElement |
* [XMLElement] |
* Strophe.Builder) elem - The stanza to send.
*/
send(elem) {
if (elem === null) {
return;
}
if (typeof elem.sort === "function") {
for (let i = 0; i < elem.length; i++) {
this._queueData(elem[i]);
}
} else if (typeof elem.tree === "function") {
this._queueData(elem.tree());
} else {
this._queueData(elem);
}
this._proto._send();
}
/** Function: flush
* Immediately send any pending outgoing data.
*
* Normally send() queues outgoing data until the next idle period
* (100ms), which optimizes network use in the common cases when
* several send()s are called in succession. flush() can be used to
* immediately send all pending data.
*/
flush() {
// cancel the pending idle period and run the idle function
// immediately
clearTimeout(this._idleTimeout);
this._onIdle();
}
/** Function: sendPresence
* Helper function to send presence stanzas. The main benefit is for
* sending presence stanzas for which you expect a responding presence
* stanza with the same id (for example when leaving a chat room).
*
* Parameters:
* (XMLElement) elem - The stanza to send.
* (Function) callback - The callback function for a successful request.
* (Function) errback - The callback function for a failed or timed
* out request. On timeout, the stanza will be null.
* (Integer) timeout - The time specified in milliseconds for a
* timeout to occur.
*
* Returns:
* The id used to send the presence.
*/
sendPresence(elem, callback, errback, timeout) {
let timeoutHandler = null;
if (typeof elem.tree === "function") {
elem = elem.tree();
}
let id = elem.getAttribute('id');
if (!id) {
// inject id if not found
id = this.getUniqueId("sendPresence");
elem.setAttribute("id", id);
}
if (typeof callback === "function" || typeof errback === "function") {
const handler = this.addHandler(stanza => {
// remove timeout handler if there is one
if (timeoutHandler) {
this.deleteTimedHandler(timeoutHandler);
}
if (stanza.getAttribute('type') === 'error') {
if (errback) {
errback(stanza);
}
} else if (callback) {
callback(stanza);
}
}, null, 'presence', null, id); // if timeout specified, set up a timeout handler.
if (timeout) {
timeoutHandler = this.addTimedHandler(timeout, () => {
// get rid of normal handler
this.deleteHandler(handler); // call errback on timeout with null stanza
if (errback) {
errback(null);
}
return false;
});
}
}
this.send(elem);
return id;
}
/** Function: sendIQ
* Helper function to send IQ stanzas.
*
* Parameters:
* (XMLElement) elem - The stanza to send.
* (Function) callback - The callback function for a successful request.
* (Function) errback - The callback function for a failed or timed
* out request. On timeout, the stanza will be null.
* (Integer) timeout - The time specified in milliseconds for a
* timeout to occur.
*
* Returns:
* The id used to send the IQ.
*/
sendIQ(elem, callback, errback, timeout) {
let timeoutHandler = null;
if (typeof elem.tree === "function") {
elem = elem.tree();
}
let id = elem.getAttribute('id');
if (!id) {
// inject id if not found
id = this.getUniqueId("sendIQ");
elem.setAttribute("id", id);
}
if (typeof callback === "function" || typeof errback === "function") {
const handler = this.addHandler(stanza => {
// remove timeout handler if there is one
if (timeoutHandler) {
this.deleteTimedHandler(timeoutHandler);
}
const iqtype = stanza.getAttribute('type');
if (iqtype === 'result') {
if (callback) {
callback(stanza);
}
} else if (iqtype === 'error') {
if (errback) {
errback(stanza);
}
} else {
const error = new Error(`Got bad IQ type of ${iqtype}`);
error.name = "StropheError";
throw error;
}
}, null, 'iq', ['error', 'result'], id); // if timeout specified, set up a timeout handler.
if (timeout) {
timeoutHandler = this.addTimedHandler(timeout, () => {
// get rid of normal handler
this.deleteHandler(handler); // call errback on timeout with null stanza
if (errback) {
errback(null);
}
return false;
});
}
}
this.send(elem);
return id;
}
/** PrivateFunction: _queueData
* Queue outgoing data for later sending. Also ensures that the data
* is a DOMElement.
*/
_queueData(element) {
if (element === null || !element.tagName || !element.childNodes) {
const error = new Error("Cannot queue non-DOMElement.");
error.name = "StropheError";
throw error;
}
this._data.push(element);
}
/** PrivateFunction: _sendRestart
* Send an xmpp:restart stanza.
*/
_sendRestart() {
this._data.push("restart");
this._proto._sendRestart();
this._idleTimeout = setTimeout(() => this._onIdle(), 100);
}
/** Function: addTimedHandler
* Add a timed handler to the connection.
*
* This function adds a timed handler. The provided handler will
* be called every period milliseconds until it returns false,
* the connection is terminated, or the handler is removed. Handlers
* that wish to continue being invoked should return true.
*
* Because of method binding it is necessary to save the result of
* this function if you wish to remove a handler with
* deleteTimedHandler().
*
* Note that user handlers are not active until authentication is
* successful.
*
* Parameters:
* (Integer) period - The period of the handler.
* (Function) handler - The callback function.
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
addTimedHandler(period, handler) {
const thand = new Strophe.TimedHandler(period, handler);
this.addTimeds.push(thand);
return thand;
}
/** Function: deleteTimedHandler
* Delete a timed handler for a connection.
*
* This function removes a timed handler from the connection. The
* handRef parameter is *not* the function passed to addTimedHandler(),
* but is the reference returned from addTimedHandler().
*
* Parameters:
* (Strophe.TimedHandler) handRef - The handler reference.
*/
deleteTimedHandler(handRef) {
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeTimeds.push(handRef);
}
/** Function: addHandler
* Add a stanza handler for the connection.
*
* This function adds a stanza handler to the connection. The
* handler callback will be called for any stanza that matches
* the parameters. Note that if multiple parameters are supplied,
* they must all match for the handler to be invoked.
*
* The handler will receive the stanza that triggered it as its argument.
* *The handler should return true if it is to be invoked again;
* returning false will remove the handler after it returns.*
*
* As a convenience, the ns parameters applies to the top level element
* and also any of its immediate children. This is primarily to make
* matching /iq/query elements easy.
*
* Options
* ~~~~~~~
* With the options argument, you can specify boolean flags that affect how
* matches are being done.
*
* Currently two flags exist:
*
* - matchBareFromJid:
* When set to true, the from parameter and the
* from attribute on the stanza will be matched as bare JIDs instead
* of full JIDs. To use this, pass {matchBareFromJid: true} as the
* value of options. The default value for matchBareFromJid is false.
*
* - ignoreNamespaceFragment:
* When set to true, a fragment specified on the stanza's namespace
* URL will be ignored when it's matched with the one configured for
* the handler.
*
* This means that if you register like this:
* > connection.addHandler(
* > handler,
* > 'http://jabber.org/protocol/muc',
* > null, null, null, null,
* > {'ignoreNamespaceFragment': true}
* > );
*
* Then a stanza with XML namespace of
* 'http://jabber.org/protocol/muc#user' will also be matched. If
* 'ignoreNamespaceFragment' is false, then only stanzas with
* 'http://jabber.org/protocol/muc' will be matched.
*
* Deleting the handler
* ~~~~~~~~~~~~~~~~~~~~
* The return value should be saved if you wish to remove the handler
* with deleteHandler().
*
* Parameters:
* (Function) handler - The user callback.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String|Array) type - The stanza type (or types if an array) to match.
* (String) id - The stanza id attribute to match.
* (String) from - The stanza from attribute to match.
* (String) options - The handler options
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
addHandler(handler, ns, name, type, id, from, options) {
const hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
this.addHandlers.push(hand);
return hand;
}
/** Function: deleteHandler
* Delete a stanza handler for a connection.
*
* This function removes a stanza handler from the connection. The
* handRef parameter is *not* the function passed to addHandler(),
* but is the reference returned from addHandler().
*
* Parameters:
* (Strophe.Handler) handRef - The handler reference.
*/
deleteHandler(handRef) {
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeHandlers.push(handRef); // If a handler is being deleted while it is being added,
// prevent it from getting added
const i = this.addHandlers.indexOf(handRef);
if (i >= 0) {
this.addHandlers.splice(i, 1);
}
}
/** Function: registerSASLMechanisms
*
* Register the SASL mechanisms which will be supported by this instance of
* Strophe.Connection (i.e. which this XMPP client will support).
*
* Parameters:
* (Array) mechanisms - Array of objects with Strophe.SASLMechanism prototypes
*
*/
registerSASLMechanisms(mechanisms) {
this.mechanisms = {};
mechanisms = mechanisms || [Strophe.SASLAnonymous, Strophe.SASLExternal, Strophe.SASLOAuthBearer, Strophe.SASLXOAuth2, Strophe.SASLPlain, Strophe.SASLSHA1];
mechanisms.forEach(m => this.registerSASLMechanism(m));
}
/** Function: registerSASLMechanism
*
* Register a single SASL mechanism, to be supported by this client.
*
* Parameters:
* (Object) mechanism - Object with a Strophe.SASLMechanism prototype
*
*/
registerSASLMechanism(Mechanism) {
const mechanism = new Mechanism();
this.mechanisms[mechanism.mechname] = mechanism;
}
/** Function: disconnect
* Start the graceful disconnection process.
*
* This function starts the disconnection process. This process starts
* by sending unavailable presence and sending BOSH body of type
* terminate. A timeout handler makes sure that disconnection happens
* even if the BOSH server does not respond.
* If the Connection object isn't connected, at least tries to abort all pending requests
* so the connection object won't generate successful requests (which were already opened).
*
* The user supplied connection callback will be notified of the
* progress as this process happens.
*
* Parameters:
* (String) reason - The reason the disconnect is occuring.
*/
disconnect(reason) {
this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);
if (reason) {
Strophe.warn("Disconnect was called because: " + reason);
} else {
Strophe.info("Disconnect was called");
}
if (this.connected) {
let pres = false;
this.disconnecting = true;
if (this.authenticated) {
pres = $pres({
'xmlns': Strophe.NS.CLIENT,
'type': 'unavailable'
});
} // setup timeout handler
this._disconnectTimeout = this._addSysTimedHandler(this.disconnection_timeout, this._onDisconnectTimeout.bind(this));
this._proto._disconnect(pres);
} else {
Strophe.warn("Disconnect was called before Strophe connected to the server");
this._proto._abortAllRequests();
this._doDisconnect();
}
}
/** PrivateFunction: _changeConnectStatus
* _Private_ helper function that makes sure plugins and the user's
* callback are notified of connection status changes.
*
* Parameters:
* (Integer) status - the new connection status, one of the values
* in Strophe.Status
* (String) condition - the error condition or null
* (XMLElement) elem - The triggering stanza.
*/
_changeConnectStatus(status, condition, elem) {
// notify all plugins listening for status changes
for (const k in Strophe._connectionPlugins) {
if (Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins, k)) {
const plugin = this[k];
if (plugin.statusChanged) {
try {
plugin.statusChanged(status, condition);
} catch (err) {
Strophe.error(`${k} plugin caused an exception changing status: ${err}`);
}
}
}
} // notify the user's callback
if (this.connect_callback) {
try {
this.connect_callback(status, condition, elem);
} catch (e) {
Strophe._handleError(e);
Strophe.error(`User connection callback caused an exception: ${e}`);
}
}
}
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* This is the last piece of the disconnection logic. This resets the
* connection and alerts the user's connection callback.
*/
_doDisconnect(condition) {
if (typeof this._idleTimeout === "number") {
clearTimeout(this._idleTimeout);
} // Cancel Disconnect Timeout
if (this._disconnectTimeout !== null) {
this.deleteTimedHandler(this._disconnectTimeout);
this._disconnectTimeout = null;
}
Strophe.debug("_doDisconnect was called");
this._proto._doDisconnect();
this.authenticated = false;
this.disconnecting = false;
this.restored = false; // delete handlers
this.handlers = [];
this.timedHandlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = []; // tell the parent we disconnected
this._changeConnectStatus(Strophe.Status.DISCONNECTED, condition);
this.connected = false;
}
/** PrivateFunction: _dataRecv
* _Private_ handler to processes incoming data from the the connection.
*
* Except for _connect_cb handling the initial connection request,
* this function handles the incoming data for all requests. This
* function also fires stanza handlers that match each incoming
* stanza.
*
* Parameters:
* (Strophe.Request) req - The request that has data ready.
* (string) req - The stanza a raw string (optiona).
*/
_dataRecv(req, raw) {
const elem = this._proto._reqToData(req);
if (elem === null) {
return;
}
if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
if (elem.nodeName === this._proto.strip && elem.childNodes.length) {
this.xmlInput(elem.childNodes[0]);
} else {
this.xmlInput(elem);
}
}
if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(Strophe.serialize(elem));
}
} // remove handlers scheduled for deletion
while (this.removeHandlers.length > 0) {
const hand = this.removeHandlers.pop();
const i = this.handlers.indexOf(hand);
if (i >= 0) {
this.handlers.splice(i, 1);
}
} // add handlers scheduled for addition
while (this.addHandlers.length > 0) {
this.handlers.push(this.addHandlers.pop());
} // handle graceful disconnect
if (this.disconnecting && this._proto._emptyQueue()) {
this._doDisconnect();
return;
}
const type = elem.getAttribute("type");
if (type !== null && type === "terminate") {
// Don't process stanzas that come in after disconnect
if (this.disconnecting) {
return;
} // an error occurred
let cond = elem.getAttribute("condition");
const conflict = elem.getElementsByTagName("conflict");
if (cond !== null) {
if (cond === "remote-stream-error" && conflict.length > 0) {
cond = "conflict";
}
this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
} else {
this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.UNKOWN_REASON);
}
this._doDisconnect(cond);
return;
} // send each incoming stanza through the handler chain
Strophe.forEachChild(elem, null, child => {
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
Strophe.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);
}
});
}
/** PrivateFunction: _connect_cb
* _Private_ handler for initial connection request.
*
* This handler is used to process the initial connection request
* response from the BOSH server. It is used to set up authentication
* handlers and start the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
* Parameters:
* (Strophe.Request) req - The current request.
* (Function) _callback - low level (xmpp) connect callback function.
* Useful for plugins with their own xmpp connect callback (when they
* want to do something special).
*/
_connect_cb(req, _callback, raw) {
Strophe.debug("_connect_cb was called");
this.connected = true;
let bodyWrap;
try {
bodyWrap = this._proto._reqToData(req);
} catch (e) {
if (e.name !== Strophe.ErrorCondition.BAD_FORMAT) {
throw e;
}
this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.BAD_FORMAT);
this._doDisconnect(Strophe.ErrorCondition.BAD_FORMAT);
}
if (!bodyWrap) {
return;
}
if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) {
this.xmlInput(bodyWrap.childNodes[0]);
} else {
this.xmlInput(bodyWrap);
}
}
if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(Strophe.serialize(bodyWrap));
}
}
const conncheck = this._proto._connect_cb(bodyWrap);
if (conncheck === Strophe.Status.CONNFAIL) {
return;
} // Check for the stream:features tag
let hasFeatures;
if (bodyWrap.getElementsByTagNameNS) {
hasFeatures = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "features").length > 0;
} else {
hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0 || bodyWrap.getElementsByTagName("features").length > 0;
}
if (!hasFeatures) {
this._proto._no_auth_received(_callback);
return;
}
const matched = Array.from(bodyWrap.getElementsByTagName("mechanism")).map(m => this.mechanisms[m.textContent]).filter(m => m);
if (matched.length === 0) {
if (bodyWrap.getElementsByTagName("auth").length === 0) {
// There are no matching SASL mechanisms and also no legacy
// auth available.
this._proto._no_auth_received(_callback);
return;
}
}
if (this.do_authentication !== false) {
this.authenticate(matched);
}
}
/** Function: sortMechanismsByPriority
*
* Sorts an array of objects with prototype SASLMechanism according to
* their priorities.
*
* Parameters:
* (Array) mechanisms - Array of SASL mechanisms.
*
*/
sortMechanismsByPriority(mechanisms) {
// eslint-disable-line class-methods-use-this
// Sorting mechanisms according to priority.
for (let i = 0; i < mechanisms.length - 1; ++i) {
let higher = i;
for (let j = i + 1; j < mechanisms.length; ++j) {
if (mechanisms[j].priority > mechanisms[higher].priority) {
higher = j;
}
}
if (higher !== i) {
const swap = mechanisms[i];
mechanisms[i] = mechanisms[higher];
mechanisms[higher] = swap;
}
}
return mechanisms;
}
/** Function: authenticate
* Set up authentication
*
* Continues the initial connection request by setting up authentication
* handlers and starting the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
* Parameters:
* (Array) matched - Array of SASL mechanisms supported.
*
*/
authenticate(matched) {
if (!this._attemptSASLAuth(matched)) {
this._attemptLegacyAuth();
}
}
/** PrivateFunction: _attemptSASLAuth
*
* Iterate through an array of SASL mechanisms and attempt authentication
* with the highest priority (enabled) mechanism.
*
* Parameters:
* (Array) mechanisms - Array of SASL mechanisms.
*
* Returns:
* (Boolean) mechanism_found - true or false, depending on whether a
* valid SASL mechanism was found with which authentication could be
* started.
*/
_attemptSASLAuth(mechanisms) {
mechanisms = this.sortMechanismsByPriority(mechanisms || []);
let mechanism_found = false;
for (let i = 0; i < mechanisms.length; ++i) {
if (!mechanisms[i].test(this)) {
continue;
}
this._sasl_success_handler = this._addSysHandler(this._sasl_success_cb.bind(this), null, "success", null, null);
this._sasl_failure_handler = this._addSysHandler(this._sasl_failure_cb.bind(this), null, "failure", null, null);
this._sasl_challenge_handler = this._addSysHandler(this._sasl_challenge_cb.bind(this), null, "challenge", null, null);
this._sasl_mechanism = mechanisms[i];
this._sasl_mechanism.onStart(this);
const request_auth_exchange = $build("auth", {
'xmlns': Strophe.NS.SASL,
'mechanism': this._sasl_mechanism.mechname
});
if (this._sasl_mechanism.isClientFirst) {
const response = this._sasl_mechanism.clientChallenge(this);
request_auth_exchange.t((0,abab.btoa)(response));
}
this.send(request_auth_exchange.tree());
mechanism_found = true;
break;
}
return mechanism_found;
}
/** PrivateFunction: _sasl_challenge_cb
* _Private_ handler for the SASL challenge
*
*/
_sasl_challenge_cb(elem) {
const challenge = (0,abab.atob)(Strophe.getText(elem));
const response = this._sasl_mechanism.onChallenge(this, challenge);
const stanza = $build('response', {
'xmlns': Strophe.NS.SASL
});
if (response !== "") {
stanza.t((0,abab.btoa)(response));
}
this.send(stanza.tree());
return true;
}
/** PrivateFunction: _attemptLegacyAuth
*
* Attempt legacy (i.e. non-SASL) authentication.
*/
_attemptLegacyAuth() {
if (Strophe.getNodeFromJid(this.jid) === null) {
// we don't have a node, which is required for non-anonymous
// client connections
this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.MISSING_JID_NODE);
this.disconnect(Strophe.ErrorCondition.MISSING_JID_NODE);
} else {
// Fall back to legacy authentication
this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
this._addSysHandler(this._onLegacyAuthIQResult.bind(this), null, null, null, "_auth_1");
this.send($iq({
'type': "get",
'to': this.domain,
'id': "_auth_1"
}).c("query", {
xmlns: Strophe.NS.AUTH
}).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree());
}
}
/** PrivateFunction: _onLegacyAuthIQResult
* _Private_ handler for legacy authentication.
*
* This handler is called in response to the initial
* for legacy authentication. It builds an authentication and
* sends it, creating a handler (calling back to _auth2_cb()) to
* handle the result
*
* Parameters:
* (XMLElement) elem - The stanza that triggered the callback.
*
* Returns:
* false to remove the handler.
*/
_onLegacyAuthIQResult(elem) {
// eslint-disable-line no-unused-vars
// build plaintext auth iq
const iq = $iq({
type: "set",
id: "_auth_2"
}).c('query', {
xmlns: Strophe.NS.AUTH
}).c('username', {}).t(Strophe.getNodeFromJid(this.jid)).up().c('password').t(this.pass);
if (!Strophe.getResourceFromJid(this.jid)) {
// since the user has not supplied a resource, we pick
// a default one here. unlike other auth methods, the server
// cannot do this for us.
this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
}
iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));
this._addSysHandler(this._auth2_cb.bind(this), null, null, null, "_auth_2");
this.send(iq.tree());
return false;
}
/** PrivateFunction: _sasl_success_cb
* _Private_ handler for succesful SASL authentication.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_success_cb(elem) {
if (this._sasl_data["server-signature"]) {
let serverSignature;
const success = (0,abab.atob)(Strophe.getText(elem));
const attribMatch = /([a-z]+)=([^,]+)(,|$)/;
const matches = success.match(attribMatch);
if (matches[1] === "v") {
serverSignature = matches[2];
}
if (serverSignature !== this._sasl_data["server-signature"]) {
// remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
this._sasl_data = {};
return this._sasl_failure_cb(null);
}
}
Strophe.info("SASL authentication succeeded.");
if (this._sasl_mechanism) {
this._sasl_mechanism.onSuccess();
} // remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
const streamfeature_handlers = [];
const wrapper = (handlers, elem) => {
while (handlers.length) {
this.deleteHandler(handlers.pop());
}
this._onStreamFeaturesAfterSASL(elem);
return false;
};
streamfeature_handlers.push(this._addSysHandler(elem => wrapper(streamfeature_handlers, elem), null, "stream:features", null, null));
streamfeature_handlers.push(this._addSysHandler(elem => wrapper(streamfeature_handlers, elem), Strophe.NS.STREAM, "features", null, null)); // we must send an xmpp:restart now
this._sendRestart();
return false;
}
/** PrivateFunction: _onStreamFeaturesAfterSASL
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_onStreamFeaturesAfterSASL(elem) {
// save stream:features for future usage
this.features = elem;
for (let i = 0; i < elem.childNodes.length; i++) {
const child = elem.childNodes[i];
if (child.nodeName === 'bind') {
this.do_bind = true;
}
if (child.nodeName === 'session') {
this.do_session = true;
}
}
if (!this.do_bind) {
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
} else if (!this.options.explicitResourceBinding) {
this.bind();
} else {
this._changeConnectStatus(Strophe.Status.BINDREQUIRED, null);
}
return false;
}
/** Function: bind
*
* Sends an IQ to the XMPP server to bind a JID resource for this session.
*
* https://tools.ietf.org/html/rfc6120#section-7.5
*
* If `explicitResourceBinding` was set to a truthy value in the options
* passed to the Strophe.Connection constructor, then this function needs
* to be called explicitly by the client author.
*
* Otherwise it'll be called automatically as soon as the XMPP server
* advertises the "urn:ietf:params:xml:ns:xmpp-bind" stream feature.
*/
bind() {
if (!this.do_bind) {
Strophe.log(Strophe.LogLevel.INFO, `Strophe.Connection.prototype.bind called but "do_bind" is false`);
return;
}
this._addSysHandler(this._onResourceBindResultIQ.bind(this), null, null, null, "_bind_auth_2");
const resource = Strophe.getResourceFromJid(this.jid);
if (resource) {
this.send($iq({
type: "set",
id: "_bind_auth_2"
}).c('bind', {
xmlns: Strophe.NS.BIND
}).c('resource', {}).t(resource).tree());
} else {
this.send($iq({
type: "set",
id: "_bind_auth_2"
}).c('bind', {
xmlns: Strophe.NS.BIND
}).tree());
}
}
/** PrivateFunction: _onResourceBindIQ
* _Private_ handler for binding result and session start.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_onResourceBindResultIQ(elem) {
if (elem.getAttribute("type") === "error") {
Strophe.warn("Resource binding failed.");
const conflict = elem.getElementsByTagName("conflict");
let condition;
if (conflict.length > 0) {
condition = Strophe.ErrorCondition.CONFLICT;
}
this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition, elem);
return false;
} // TODO - need to grab errors
const bind = elem.getElementsByTagName("bind");
if (bind.length > 0) {
const jidNode = bind[0].getElementsByTagName("jid");
if (jidNode.length > 0) {
this.authenticated = true;
this.jid = Strophe.getText(jidNode[0]);
if (this.do_session) {
this._establishSession();
} else {
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
}
}
} else {
Strophe.warn("Resource binding failed.");
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
return false;
}
}
/** PrivateFunction: _establishSession
* Send IQ request to establish a session with the XMPP server.
*
* See https://xmpp.org/rfcs/rfc3921.html#session
*
* Note: The protocol for session establishment has been determined as
* unnecessary and removed in RFC-6121.
*/
_establishSession() {
if (!this.do_session) {
throw new Error(`Strophe.Connection.prototype._establishSession ` + `called but apparently ${Strophe.NS.SESSION} wasn't advertised by the server`);
}
this._addSysHandler(this._onSessionResultIQ.bind(this), null, null, null, "_session_auth_2");
this.send($iq({
type: "set",
id: "_session_auth_2"
}).c('session', {
xmlns: Strophe.NS.SESSION
}).tree());
}
/** PrivateFunction: _onSessionResultIQ
* _Private_ handler for the server's IQ response to a client's session
* request.
*
* This sets Connection.authenticated to true on success, which
* starts the processing of user handlers.
*
* See https://xmpp.org/rfcs/rfc3921.html#session
*
* Note: The protocol for session establishment has been determined as
* unnecessary and removed in RFC-6121.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_onSessionResultIQ(elem) {
if (elem.getAttribute("type") === "result") {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
} else if (elem.getAttribute("type") === "error") {
this.authenticated = false;
Strophe.warn("Session creation failed.");
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
return false;
}
return false;
}
/** PrivateFunction: _sasl_failure_cb
* _Private_ handler for SASL authentication failure.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_failure_cb(elem) {
// delete unneeded handlers
if (this._sasl_success_handler) {
this.deleteHandler(this._sasl_success_handler);
this._sasl_success_handler = null;
}
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
if (this._sasl_mechanism) this._sasl_mechanism.onFailure();
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
return false;
}
/** PrivateFunction: _auth2_cb
* _Private_ handler to finish legacy authentication.
*
* This handler is called when the result from the jabber:iq:auth
* stanza is returned.
*
* Parameters:
* (XMLElement) elem - The stanza that triggered the callback.
*
* Returns:
* false to remove the handler.
*/
_auth2_cb(elem) {
if (elem.getAttribute("type") === "result") {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
} else if (elem.getAttribute("type") === "error") {
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
this.disconnect('authentication failed');
}
return false;
}
/** PrivateFunction: _addSysTimedHandler
* _Private_ function to add a system level timed handler.
*
* This function is used to add a Strophe.TimedHandler for the
* library code. System timed handlers are allowed to run before
* authentication is complete.
*
* Parameters:
* (Integer) period - The period of the handler.
* (Function) handler - The callback function.
*/
_addSysTimedHandler(period, handler) {
const thand = new Strophe.TimedHandler(period, handler);
thand.user = false;
this.addTimeds.push(thand);
return thand;
}
/** PrivateFunction: _addSysHandler
* _Private_ function to add a system level stanza handler.
*
* This function is used to add a Strophe.Handler for the
* library code. System stanza handlers are allowed to run before
* authentication is complete.
*
* Parameters:
* (Function) handler - The callback function.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String) type - The stanza type attribute to match.
* (String) id - The stanza id attribute to match.
*/
_addSysHandler(handler, ns, name, type, id) {
const hand = new Strophe.Handler(handler, ns, name, type, id);
hand.user = false;
this.addHandlers.push(hand);
return hand;
}
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* If the graceful disconnect process does not complete within the
* time allotted, this handler finishes the disconnect anyway.
*
* Returns:
* false to remove the handler.
*/
_onDisconnectTimeout() {
Strophe.debug("_onDisconnectTimeout was called");
this._changeConnectStatus(Strophe.Status.CONNTIMEOUT, null);
this._proto._onDisconnectTimeout(); // actually disconnect
this._doDisconnect();
return false;
}
/** PrivateFunction: _onIdle
* _Private_ handler to process events during idle cycle.
*
* This handler is called every 100ms to fire timed handlers that
* are ready and keep poll requests going.
*/
_onIdle() {
// add timed handlers scheduled for addition
// NOTE: we add before remove in the case a timed handler is
// added and then deleted before the next _onIdle() call.
while (this.addTimeds.length > 0) {
this.timedHandlers.push(this.addTimeds.pop());
} // remove timed handlers that have been scheduled for deletion
while (this.removeTimeds.length > 0) {
const thand = this.removeTimeds.pop();
const i = this.timedHandlers.indexOf(thand);
if (i >= 0) {
this.timedHandlers.splice(i, 1);
}
} // call ready timed handlers
const now = new Date().getTime();
const newList = [];
for (let i = 0; i < this.timedHandlers.length; i++) {
const thand = this.timedHandlers[i];
if (this.authenticated || !thand.user) {
const since = thand.lastCalled + thand.period;
if (since - now <= 0) {
if (thand.run()) {
newList.push(thand);
}
} else {
newList.push(thand);
}
}
}
this.timedHandlers = newList;
clearTimeout(this._idleTimeout);
this._proto._onIdle(); // reactivate the timer only if connected
if (this.connected) {
this._idleTimeout = setTimeout(() => this._onIdle(), 100);
}
}
};
Strophe.SASLMechanism = SASLMechanism;
/** Constants: SASL mechanisms
* Available authentication mechanisms
*
* Strophe.SASLAnonymous - SASL ANONYMOUS authentication.
* Strophe.SASLPlain - SASL PLAIN authentication.
* Strophe.SASLSHA1 - SASL SCRAM-SHA-1 authentication
* Strophe.SASLOAuthBearer - SASL OAuth Bearer authentication
* Strophe.SASLExternal - SASL EXTERNAL authentication
* Strophe.SASLXOAuth2 - SASL X-OAuth2 authentication
*/
Strophe.SASLAnonymous = SASLAnonymous;
Strophe.SASLPlain = SASLPlain;
Strophe.SASLSHA1 = SASLSHA1;
Strophe.SASLOAuthBearer = SASLOAuthBearer;
Strophe.SASLExternal = SASLExternal;
Strophe.SASLXOAuth2 = SASLXOAuth2;
/* harmony default export */ const core = ({
'Strophe': Strophe,
'$build': $build,
'$iq': $iq,
'$msg': $msg,
'$pres': $pres,
'SHA1': SHA1,
'MD5': MD5,
'b64_hmac_sha1': SHA1.b64_hmac_sha1,
'b64_sha1': SHA1.b64_sha1,
'str_hmac_sha1': SHA1.str_hmac_sha1,
'str_sha1': SHA1.str_sha1
});
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/bosh.js
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* global ActiveXObject */
/** PrivateClass: Strophe.Request
* _Private_ helper class that provides a cross implementation abstraction
* for a BOSH related XMLHttpRequest.
*
* The Strophe.Request class is used internally to encapsulate BOSH request
* information. It is not meant to be used from user's code.
*/
Strophe.Request = class Request {
/** PrivateConstructor: Strophe.Request
* Create and initialize a new Strophe.Request object.
*
* Parameters:
* (XMLElement) elem - The XML data to be sent in the request.
* (Function) func - The function that will be called when the
* XMLHttpRequest readyState changes.
* (Integer) rid - The BOSH rid attribute associated with this request.
* (Integer) sends - The number of times this same request has been sent.
*/
constructor(elem, func, rid, sends) {
this.id = ++Strophe._requestId;
this.xmlData = elem;
this.data = Strophe.serialize(elem); // save original function in case we need to make a new request
// from this one.
this.origFunc = func;
this.func = func;
this.rid = rid;
this.date = NaN;
this.sends = sends || 0;
this.abort = false;
this.dead = null;
this.age = function () {
if (!this.date) {
return 0;
}
const now = new Date();
return (now - this.date) / 1000;
};
this.timeDead = function () {
if (!this.dead) {
return 0;
}
const now = new Date();
return (now - this.dead) / 1000;
};
this.xhr = this._newXHR();
}
/** PrivateFunction: getResponse
* Get a response from the underlying XMLHttpRequest.
*
* This function attempts to get a response from the request and checks
* for errors.
*
* Throws:
* "parsererror" - A parser error occured.
* "bad-format" - The entity has sent XML that cannot be processed.
*
* Returns:
* The DOM element tree of the response.
*/
getResponse() {
let node = null;
if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
node = this.xhr.responseXML.documentElement;
if (node.tagName === "parsererror") {
Strophe.error("invalid response received");
Strophe.error("responseText: " + this.xhr.responseText);
Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML));
throw new Error("parsererror");
}
} else if (this.xhr.responseText) {
// In React Native, we may get responseText but no responseXML. We can try to parse it manually.
Strophe.debug("Got responseText but no responseXML; attempting to parse it with DOMParser...");
node = new strophe_shims_DOMParser().parseFromString(this.xhr.responseText, 'application/xml').documentElement;
if (!node) {
throw new Error('Parsing produced null node');
} else if (node.querySelector('parsererror')) {
Strophe.error("invalid response received: " + node.querySelector('parsererror').textContent);
Strophe.error("responseText: " + this.xhr.responseText);
const error = new Error();
error.name = Strophe.ErrorCondition.BAD_FORMAT;
throw error;
}
}
return node;
}
/** PrivateFunction: _newXHR
* _Private_ helper function to create XMLHttpRequests.
*
* This function creates XMLHttpRequests across all implementations.
*
* Returns:
* A new XMLHttpRequest.
*/
_newXHR() {
let xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType("text/xml; charset=utf-8");
}
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} // use Function.bind() to prepend ourselves as an argument
xhr.onreadystatechange = this.func.bind(null, this);
return xhr;
}
};
/** Class: Strophe.Bosh
* _Private_ helper class that handles BOSH Connections
*
* The Strophe.Bosh class is used internally by Strophe.Connection
* to encapsulate BOSH sessions. It is not meant to be used from user's code.
*/
/** File: bosh.js
* A JavaScript library to enable BOSH in Strophejs.
*
* this library uses Bidirectional-streams Over Synchronous HTTP (BOSH)
* to emulate a persistent, stateful, two-way connection to an XMPP server.
* More information on BOSH can be found in XEP 124.
*/
/** PrivateConstructor: Strophe.Bosh
* Create and initialize a Strophe.Bosh object.
*
* Parameters:
* (Strophe.Connection) connection - The Strophe.Connection that will use BOSH.
*
* Returns:
* A new Strophe.Bosh object.
*/
Strophe.Bosh = class Bosh {
constructor(connection) {
this._conn = connection;
/* request id for body tags */
this.rid = Math.floor(Math.random() * 4294967295);
/* The current session ID. */
this.sid = null; // default BOSH values
this.hold = 1;
this.wait = 60;
this.window = 5;
this.errors = 0;
this.inactivity = null;
this.lastResponseHeaders = null;
this._requests = [];
}
/** PrivateFunction: _buildBody
* _Private_ helper function to generate the wrapper for BOSH.
*
* Returns:
* A Strophe.Builder with a element.
*/
_buildBody() {
const bodyWrap = $build('body', {
'rid': this.rid++,
'xmlns': Strophe.NS.HTTPBIND
});
if (this.sid !== null) {
bodyWrap.attrs({
'sid': this.sid
});
}
if (this._conn.options.keepalive && this._conn._sessionCachingSupported()) {
this._cacheSession();
}
return bodyWrap;
}
/** PrivateFunction: _reset
* Reset the connection.
*
* This function is called by the reset function of the Strophe Connection
*/
_reset() {
this.rid = Math.floor(Math.random() * 4294967295);
this.sid = null;
this.errors = 0;
if (this._conn._sessionCachingSupported()) {
window.sessionStorage.removeItem('strophe-bosh-session');
}
this._conn.nextValidRid(this.rid);
}
/** PrivateFunction: _connect
* _Private_ function that initializes the BOSH connection.
*
* Creates and sends the Request that initializes the BOSH connection.
*/
_connect(wait, hold, route) {
this.wait = wait || this.wait;
this.hold = hold || this.hold;
this.errors = 0;
const body = this._buildBody().attrs({
"to": this._conn.domain,
"xml:lang": "en",
"wait": this.wait,
"hold": this.hold,
"content": "text/xml; charset=utf-8",
"ver": "1.6",
"xmpp:version": "1.0",
"xmlns:xmpp": Strophe.NS.BOSH
});
if (route) {
body.attrs({
'route': route
});
}
const _connect_cb = this._conn._connect_cb;
this._requests.push(new Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, _connect_cb.bind(this._conn)), body.tree().getAttribute("rid")));
this._throttledRequestHandler();
}
/** PrivateFunction: _attach
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* (String) sid - The SID of the BOSH session.
* (String) rid - The current RID of the BOSH session. This RID
* will be used by the next request.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
_attach(jid, sid, rid, callback, wait, hold, wind) {
this._conn.jid = jid;
this.sid = sid;
this.rid = rid;
this._conn.connect_callback = callback;
this._conn.domain = Strophe.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(Strophe.Status.ATTACHED, null);
}
/** PrivateFunction: _restore
* Attempt to restore a cached BOSH session
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* This parameter is optional but recommended, specifically in cases
* where prebinded BOSH sessions are used where it's important to know
* that the right session is being restored.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
_restore(jid, callback, wait, hold, wind) {
const session = JSON.parse(window.sessionStorage.getItem('strophe-bosh-session'));
if (typeof session !== "undefined" && session !== null && session.rid && session.sid && session.jid && (typeof jid === "undefined" || jid === null || Strophe.getBareJidFromJid(session.jid) === Strophe.getBareJidFromJid(jid) || // If authcid is null, then it's an anonymous login, so
// we compare only the domains:
Strophe.getNodeFromJid(jid) === null && Strophe.getDomainFromJid(session.jid) === jid)) {
this._conn.restored = true;
this._attach(session.jid, session.sid, session.rid, callback, wait, hold, wind);
} else {
const error = new Error("_restore: no restoreable session.");
error.name = "StropheSessionError";
throw error;
}
}
/** PrivateFunction: _cacheSession
* _Private_ handler for the beforeunload event.
*
* This handler is used to process the Bosh-part of the initial request.
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_cacheSession() {
if (this._conn.authenticated) {
if (this._conn.jid && this.rid && this.sid) {
window.sessionStorage.setItem('strophe-bosh-session', JSON.stringify({
'jid': this._conn.jid,
'rid': this.rid,
'sid': this.sid
}));
}
} else {
window.sessionStorage.removeItem('strophe-bosh-session');
}
}
/** PrivateFunction: _connect_cb
* _Private_ handler for initial connection request.
*
* This handler is used to process the Bosh-part of the initial request.
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_connect_cb(bodyWrap) {
const typ = bodyWrap.getAttribute("type");
if (typ !== null && typ === "terminate") {
// an error occurred
let cond = bodyWrap.getAttribute("condition");
Strophe.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(Strophe.Status.CONNFAIL, cond);
} else {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
}
this._conn._doDisconnect(cond);
return Strophe.Status.CONNFAIL;
} // check to make sure we don't overwrite these if _connect_cb is
// called multiple times in the case of missing stream:features
if (!this.sid) {
this.sid = bodyWrap.getAttribute("sid");
}
const wind = bodyWrap.getAttribute('requests');
if (wind) {
this.window = parseInt(wind, 10);
}
const hold = bodyWrap.getAttribute('hold');
if (hold) {
this.hold = parseInt(hold, 10);
}
const wait = bodyWrap.getAttribute('wait');
if (wait) {
this.wait = parseInt(wait, 10);
}
const inactivity = bodyWrap.getAttribute('inactivity');
if (inactivity) {
this.inactivity = parseInt(inactivity, 10);
}
}
/** PrivateFunction: _disconnect
* _Private_ part of Connection.disconnect for Bosh
*
* Parameters:
* (Request) pres - This stanza will be sent before disconnecting.
*/
_disconnect(pres) {
this._sendTerminate(pres);
}
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* Resets the SID and RID.
*/
_doDisconnect() {
this.sid = null;
this.rid = Math.floor(Math.random() * 4294967295);
if (this._conn._sessionCachingSupported()) {
window.sessionStorage.removeItem('strophe-bosh-session');
}
this._conn.nextValidRid(this.rid);
}
/** PrivateFunction: _emptyQueue
* _Private_ function to check if the Request queue is empty.
*
* Returns:
* True, if there are no Requests queued, False otherwise.
*/
_emptyQueue() {
return this._requests.length === 0;
}
/** PrivateFunction: _callProtocolErrorHandlers
* _Private_ function to call error handlers registered for HTTP errors.
*
* Parameters:
* (Strophe.Request) req - The request that is changing readyState.
*/
_callProtocolErrorHandlers(req) {
const reqStatus = Bosh._getRequestStatus(req);
const err_callback = this._conn.protocolErrorHandlers.HTTP[reqStatus];
if (err_callback) {
err_callback.call(this, reqStatus);
}
}
/** PrivateFunction: _hitError
* _Private_ function to handle the error count.
*
* Requests are resent automatically until their error count reaches
* 5. Each time an error is encountered, this function is called to
* increment the count and disconnect if the count is too high.
*
* Parameters:
* (Integer) reqStatus - The request status.
*/
_hitError(reqStatus) {
this.errors++;
Strophe.warn("request errored, status: " + reqStatus + ", number of errors: " + this.errors);
if (this.errors > 4) {
this._conn._onDisconnectTimeout();
}
}
/** PrivateFunction: _no_auth_received
*
* Called on stream start/restart when no stream:features
* has been received and sends a blank poll request.
*/
_no_auth_received(callback) {
Strophe.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 Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, callback), body.tree().getAttribute("rid")));
this._throttledRequestHandler();
}
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* Cancels all remaining Requests and clears the queue.
*/
_onDisconnectTimeout() {
this._abortAllRequests();
}
/** PrivateFunction: _abortAllRequests
* _Private_ helper function that makes sure all pending requests are aborted.
*/
_abortAllRequests() {
while (this._requests.length > 0) {
const req = this._requests.pop();
req.abort = true;
req.xhr.abort();
req.xhr.onreadystatechange = function () {};
}
}
/** PrivateFunction: _onIdle
* _Private_ handler called by Strophe.Connection._onIdle
*
* Sends all queued Requests or polls with empty Request if there are none.
*/
_onIdle() {
const data = this._conn._data; // if no requests are in progress, poll
if (this._conn.authenticated && this._requests.length === 0 && data.length === 0 && !this._conn.disconnecting) {
Strophe.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": Strophe.NS.BOSH
});
} else {
body.cnode(data[i]).up();
}
}
}
delete this._conn._data;
this._conn._data = [];
this._requests.push(new Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid")));
this._throttledRequestHandler();
}
if (this._requests.length > 0) {
const time_elapsed = this._requests[0].age();
if (this._requests[0].dead !== null) {
if (this._requests[0].timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
this._throttledRequestHandler();
}
}
if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
Strophe.warn("Request " + this._requests[0].id + " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) + " seconds since last activity");
this._throttledRequestHandler();
}
}
}
/** PrivateFunction: _getRequestStatus
*
* Returns the HTTP status code from a Strophe.Request
*
* Parameters:
* (Strophe.Request) req - The Strophe.Request instance.
* (Integer) def - The default value that should be returned if no
* status value was found.
*/
static _getRequestStatus(req, def) {
let reqStatus;
if (req.xhr.readyState === 4) {
try {
reqStatus = req.xhr.status;
} catch (e) {
// ignore errors from undefined status attribute. Works
// around a browser bug
Strophe.error("Caught an error while retrieving a request's status, " + "reqStatus: " + reqStatus);
}
}
if (typeof reqStatus === "undefined") {
reqStatus = typeof def === 'number' ? def : 0;
}
return reqStatus;
}
/** PrivateFunction: _onRequestStateChange
* _Private_ handler for Strophe.Request state changes.
*
* This function is called when the XMLHttpRequest readyState changes.
* It contains a lot of error handling logic for the many ways that
* requests can fail, and calls the request callback when requests
* succeed.
*
* Parameters:
* (Function) func - The handler for the request.
* (Strophe.Request) req - The request that is changing readyState.
*/
_onRequestStateChange(func, req) {
Strophe.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);
Strophe.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(Strophe.SECONDARY_TIMEOUT * this.wait)) {
this._restartRequest(0);
}
this._conn.nextValidRid(Number(req.rid) + 1);
Strophe.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
Strophe.error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened");
this._hitError(reqStatus);
this._callProtocolErrorHandlers(req);
if (reqStatus >= 400 && reqStatus < 500) {
this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING, null);
this._conn._doDisconnect();
}
} else {
Strophe.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(Strophe.Status.CONNFAIL, "giving-up");
}
}
/** PrivateFunction: _processRequest
* _Private_ function to process a request in the queue.
*
* This function takes requests off the queue and sends them and
* restarts dead requests.
*
* Parameters:
* (Integer) i - The index of the request in the queue.
*/
_processRequest(i) {
let req = this._requests[i];
const reqStatus = Bosh._getRequestStatus(req, -1); // make sure we limit the number of retries
if (req.sends > this._conn.maxRetries) {
this._conn._onDisconnectTimeout();
return;
}
const time_elapsed = req.age();
const primary_timeout = !isNaN(time_elapsed) && time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait);
const secondary_timeout = req.dead !== null && req.timeDead() > Math.floor(Strophe.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) {
Strophe.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 Strophe.Request(req.xmlData, req.origFunc, req.rid, req.sends);
req = this._requests[i];
}
if (req.xhr.readyState === 0) {
Strophe.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) {
Strophe.error("XHR open failed: " + e2.toString());
if (!this._conn.connected) {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "bad-service");
}
this._conn.disconnect();
return;
} // Fires the XHR request -- may be invoked immediately
// or on a gradually expanding retry window for reconnects
const sendFunc = () => {
req.date = new Date();
if (this._conn.options.customHeaders) {
const headers = this._conn.options.customHeaders;
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
req.xhr.setRequestHeader(header, headers[header]);
}
}
}
req.xhr.send(req.data);
}; // Implement progressive backoff for reconnects --
// First retry (send === 1) should also be instantaneous
if (req.sends > 1) {
// Using a cube of the retry number creates a nicely
// expanding retry window
const backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait), Math.pow(req.sends, 3)) * 1000;
setTimeout(function () {
// XXX: setTimeout should be called only with function expressions (23974bc1)
sendFunc();
}, backoff);
} else {
sendFunc();
}
req.sends++;
if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) {
this._conn.xmlOutput(req.xmlData.childNodes[0]);
} else {
this._conn.xmlOutput(req.xmlData);
}
}
if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) {
this._conn.rawOutput(req.data);
}
} else {
Strophe.debug("_processRequest: " + (i === 0 ? "first" : "second") + " request has readyState of " + req.xhr.readyState);
}
}
/** PrivateFunction: _removeRequest
* _Private_ function to remove a request from the queue.
*
* Parameters:
* (Strophe.Request) req - The request to remove.
*/
_removeRequest(req) {
Strophe.debug("removing request");
for (let i = this._requests.length - 1; i >= 0; i--) {
if (req === this._requests[i]) {
this._requests.splice(i, 1);
}
} // IE6 fails on setting to null, so set to empty function
req.xhr.onreadystatechange = function () {};
this._throttledRequestHandler();
}
/** PrivateFunction: _restartRequest
* _Private_ function to restart a request that is presumed dead.
*
* Parameters:
* (Integer) i - The index of the request in the queue.
*/
_restartRequest(i) {
const req = this._requests[i];
if (req.dead === null) {
req.dead = new Date();
}
this._processRequest(i);
}
/** PrivateFunction: _reqToData
* _Private_ function to get a stanza out of a request.
*
* Tries to extract a stanza out of a Request Object.
* When this fails the current connection will be disconnected.
*
* Parameters:
* (Object) req - The Request.
*
* Returns:
* The stanza that was passed.
*/
_reqToData(req) {
try {
return req.getResponse();
} catch (e) {
if (e.message !== "parsererror") {
throw e;
}
this._conn.disconnect("strophe-parsererror");
}
}
/** PrivateFunction: _sendTerminate
* _Private_ function to send initial disconnect sequence.
*
* This is the first step in a graceful disconnect. It sends
* the BOSH server a terminate body and includes an unavailable
* presence if authentication has completed.
*/
_sendTerminate(pres) {
Strophe.debug("_sendTerminate was called");
const body = this._buildBody().attrs({
type: "terminate"
});
if (pres) {
body.cnode(pres.tree());
}
const req = new Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid"));
this._requests.push(req);
this._throttledRequestHandler();
}
/** PrivateFunction: _send
* _Private_ part of the Connection.send function for BOSH
*
* Just triggers the RequestHandler to send the messages that are in the queue
*/
_send() {
clearTimeout(this._conn._idleTimeout);
this._throttledRequestHandler();
this._conn._idleTimeout = setTimeout(() => this._conn._onIdle(), 100);
}
/** PrivateFunction: _sendRestart
*
* Send an xmpp:restart stanza.
*/
_sendRestart() {
this._throttledRequestHandler();
clearTimeout(this._conn._idleTimeout);
}
/** PrivateFunction: _throttledRequestHandler
* _Private_ function to throttle requests to the connection window.
*
* This function makes sure we don't send requests so fast that the
* request ids overflow the connection window in the case that one
* request died.
*/
_throttledRequestHandler() {
if (!this._requests) {
Strophe.debug("_throttledRequestHandler called with " + "undefined requests");
} else {
Strophe.debug("_throttledRequestHandler called with " + this._requests.length + " requests");
}
if (!this._requests || this._requests.length === 0) {
return;
}
if (this._requests.length > 0) {
this._processRequest(0);
}
if (this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window) {
this._processRequest(1);
}
}
};
/** Variable: strip
*
* BOSH-Connections will have all stanzas wrapped in a tag when
* passed to or .
* To strip this tag, User code can set to "body":
*
* > Strophe.Bosh.prototype.strip = "body";
*
* This will enable stripping of the body tag in both
* and .
*/
Strophe.Bosh.prototype.strip = null;
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/websocket.js
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* global window, clearTimeout, WebSocket, DOMParser */
/** Class: Strophe.WebSocket
* _Private_ helper class that handles WebSocket Connections
*
* The Strophe.WebSocket class is used internally by Strophe.Connection
* to encapsulate WebSocket sessions. It is not meant to be used from user's code.
*/
/** File: websocket.js
* A JavaScript library to enable XMPP over Websocket in Strophejs.
*
* This file implements XMPP over WebSockets for Strophejs.
* If a Connection is established with a Websocket url (ws://...)
* Strophe will use WebSockets.
* For more information on XMPP-over-WebSocket see RFC 7395:
* http://tools.ietf.org/html/rfc7395
*
* WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de)
*/
Strophe.Websocket = class Websocket {
/** PrivateConstructor: Strophe.Websocket
* Create and initialize a Strophe.WebSocket object.
* Currently only sets the connection Object.
*
* Parameters:
* (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets.
*
* Returns:
* A new Strophe.WebSocket object.
*/
constructor(connection) {
this._conn = connection;
this.strip = "wrapper";
const service = connection.service;
if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) {
// If the service is not an absolute URL, assume it is a path and put the absolute
// URL together from options, current URL and the path.
let new_service = "";
if (connection.options.protocol === "ws" && window.location.protocol !== "https:") {
new_service += "ws";
} else {
new_service += "wss";
}
new_service += "://" + window.location.host;
if (service.indexOf("/") !== 0) {
new_service += window.location.pathname + service;
} else {
new_service += service;
}
connection.service = new_service;
}
}
/** PrivateFunction: _buildStream
* _Private_ helper function to generate the start tag for WebSockets
*
* Returns:
* A Strophe.Builder with a element.
*/
_buildStream() {
return $build("open", {
"xmlns": Strophe.NS.FRAMING,
"to": this._conn.domain,
"version": '1.0'
});
}
/** PrivateFunction: _checkStreamError
* _Private_ checks a message for stream:error
*
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
* connectstatus - The ConnectStatus that will be set on error.
* Returns:
* true if there was a streamerror, false otherwise.
*/
_checkStreamError(bodyWrap, connectstatus) {
let errors;
if (bodyWrap.getElementsByTagNameNS) {
errors = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "error");
} else {
errors = bodyWrap.getElementsByTagName("stream:error");
}
if (errors.length === 0) {
return false;
}
const error = errors[0];
let condition = "";
let text = "";
const ns = "urn:ietf:params:xml:ns:xmpp-streams";
for (let i = 0; i < error.childNodes.length; i++) {
const e = error.childNodes[i];
if (e.getAttribute("xmlns") !== ns) {
break;
}
if (e.nodeName === "text") {
text = e.textContent;
} else {
condition = e.nodeName;
}
}
let errorString = "WebSocket stream error: ";
if (condition) {
errorString += condition;
} else {
errorString += "unknown";
}
if (text) {
errorString += " - " + text;
}
Strophe.error(errorString); // close the connection on stream_error
this._conn._changeConnectStatus(connectstatus, condition);
this._conn._doDisconnect();
return true;
}
/** PrivateFunction: _reset
* Reset the connection.
*
* This function is called by the reset function of the Strophe Connection.
* Is not needed by WebSockets.
*/
_reset() {
// eslint-disable-line class-methods-use-this
return;
}
/** PrivateFunction: _connect
* _Private_ function called by Strophe.Connection.connect
*
* Creates a WebSocket for a connection and assigns Callbacks to it.
* Does nothing if there already is a WebSocket.
*/
_connect() {
// Ensure that there is no open WebSocket from a previous Connection.
this._closeSocket();
this.socket = new WebSocket(this._conn.service, "xmpp");
this.socket.onopen = () => this._onOpen();
this.socket.onerror = e => this._onError(e);
this.socket.onclose = e => this._onClose(e); // Gets replaced with this._onMessage once _onInitialMessage is called
this.socket.onmessage = message => this._onInitialMessage(message);
}
/** PrivateFunction: _connect_cb
* _Private_ function called by Strophe.Connection._connect_cb
*
* checks for stream:error
*
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_connect_cb(bodyWrap) {
const error = this._checkStreamError(bodyWrap, Strophe.Status.CONNFAIL);
if (error) {
return Strophe.Status.CONNFAIL;
}
}
/** PrivateFunction: _handleStreamStart
* _Private_ function that checks the opening tag for errors.
*
* Disconnects if there is an error and returns false, true otherwise.
*
* Parameters:
* (Node) message - Stanza containing the tag.
*/
_handleStreamStart(message) {
let error = false; // Check for errors in the tag
const ns = message.getAttribute("xmlns");
if (typeof ns !== "string") {
error = "Missing xmlns in ";
} else if (ns !== Strophe.NS.FRAMING) {
error = "Wrong xmlns in : " + ns;
}
const ver = message.getAttribute("version");
if (typeof ver !== "string") {
error = "Missing version in ";
} else if (ver !== "1.0") {
error = "Wrong version in : " + ver;
}
if (error) {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, error);
this._conn._doDisconnect();
return false;
}
return true;
}
/** PrivateFunction: _onInitialMessage
* _Private_ function that handles the first connection messages.
*
* On receiving an opening stream tag this callback replaces itself with the real
* message handler. On receiving a stream error the connection is terminated.
*/
_onInitialMessage(message) {
if (message.data.indexOf("\s*)*/, "");
if (data === '') return;
const streamStart = new strophe_shims_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("WSS, WS->ANY
const isSecureRedirect = service.indexOf("wss:") >= 0 && see_uri.indexOf("wss:") >= 0 || service.indexOf("ws:") >= 0;
if (isSecureRedirect) {
this._conn._changeConnectStatus(Strophe.Status.REDIRECT, "Received see-other-uri, resetting connection");
this._conn.reset();
this._conn.service = see_uri;
this._connect();
}
} else {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Received closing stream");
this._conn._doDisconnect();
}
} else {
this._replaceMessageHandler();
const string = this._streamWrap(message.data);
const elem = new strophe_shims_DOMParser().parseFromString(string, "text/xml").documentElement;
this._conn._connect_cb(elem, null, message.data);
}
}
/** PrivateFunction: _replaceMessageHandler
*
* Called by _onInitialMessage in order to replace itself with the general message handler.
* This method is overridden by Strophe.WorkerWebsocket, which manages a
* websocket connection via a service worker and doesn't have direct access
* to the socket.
*/
_replaceMessageHandler() {
this.socket.onmessage = m => this._onMessage(m);
}
/** PrivateFunction: _disconnect
* _Private_ function called by Strophe.Connection.disconnect
*
* Disconnects and sends a last stanza if one is given
*
* Parameters:
* (Request) pres - This stanza will be sent before disconnecting.
*/
_disconnect(pres) {
if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
if (pres) {
this._conn.send(pres);
}
const close = $build("close", {
"xmlns": Strophe.NS.FRAMING
});
this._conn.xmlOutput(close.tree());
const closeString = Strophe.serialize(close);
this._conn.rawOutput(closeString);
try {
this.socket.send(closeString);
} catch (e) {
Strophe.warn("Couldn't send tag.");
}
}
setTimeout(() => this._conn._doDisconnect, 0);
}
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* Just closes the Socket for WebSockets
*/
_doDisconnect() {
Strophe.debug("WebSockets _doDisconnect was called");
this._closeSocket();
}
/** PrivateFunction _streamWrap
* _Private_ helper function to wrap a stanza in a tag.
* This is used so Strophe can process stanzas from WebSockets like BOSH
*/
_streamWrap(stanza) {
// eslint-disable-line class-methods-use-this
return "" + stanza + '';
}
/** PrivateFunction: _closeSocket
* _Private_ function to close the WebSocket.
*
* Closes the socket if it is still open and deletes it
*/
_closeSocket() {
if (this.socket) {
try {
this.socket.onclose = null;
this.socket.onerror = null;
this.socket.onmessage = null;
this.socket.close();
} catch (e) {
Strophe.debug(e.message);
}
}
this.socket = null;
}
/** PrivateFunction: _emptyQueue
* _Private_ function to check if the message queue is empty.
*
* Returns:
* True, because WebSocket messages are send immediately after queueing.
*/
_emptyQueue() {
// eslint-disable-line class-methods-use-this
return true;
}
/** PrivateFunction: _onClose
* _Private_ function to handle websockets closing.
*/
_onClose(e) {
if (this._conn.connected && !this._conn.disconnecting) {
Strophe.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.
Strophe.error("Websocket closed unexcectedly");
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");
this._conn._doDisconnect();
} else {
Strophe.debug("Websocket closed");
}
}
/** PrivateFunction: _no_auth_received
*
* Called on stream start/restart when no stream:features
* has been received.
*/
_no_auth_received(callback) {
Strophe.error("Server did not offer a supported authentication mechanism");
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.NO_AUTH_MECH);
if (callback) {
callback.call(this._conn);
}
this._conn._doDisconnect();
}
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* This does nothing for WebSockets
*/
_onDisconnectTimeout() {} // eslint-disable-line class-methods-use-this
/** PrivateFunction: _abortAllRequests
* _Private_ helper function that makes sure all pending requests are aborted.
*/
_abortAllRequests() {} // eslint-disable-line class-methods-use-this
/** PrivateFunction: _onError
* _Private_ function to handle websockets errors.
*
* Parameters:
* (Object) error - The websocket error.
*/
_onError(error) {
Strophe.error("Websocket error " + JSON.stringify(error));
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");
this._disconnect();
}
/** PrivateFunction: _onIdle
* _Private_ function called by Strophe.Connection._onIdle
*
* sends all queued stanzas
*/
_onIdle() {
const data = this._conn._data;
if (data.length > 0 && !this._conn.paused) {
for (let i = 0; i < data.length; i++) {
if (data[i] !== null) {
let stanza;
if (data[i] === "restart") {
stanza = this._buildStream().tree();
} else {
stanza = data[i];
}
const rawStanza = Strophe.serialize(stanza);
this._conn.xmlOutput(stanza);
this._conn.rawOutput(rawStanza);
this.socket.send(rawStanza);
}
}
this._conn._data = [];
}
}
/** PrivateFunction: _onMessage
* _Private_ function to handle websockets messages.
*
* This function parses each of the messages as if they are full documents.
* [TODO : We may actually want to use a SAX Push parser].
*
* Since all XMPP traffic starts with
*
*
* The first stanza will always fail to be parsed.
*
* Additionally, the seconds stanza will always be with
* the stream NS defined in the previous stanza, so we need to 'force'
* the inclusion of the NS in this stanza.
*
* Parameters:
* (string) message - The websocket message.
*/
_onMessage(message) {
let elem; // check for closing stream
const close = '';
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(" tag before we close the connection
return;
}
this._conn._dataRecv(elem, message.data);
}
/** PrivateFunction: _onOpen
* _Private_ function to handle websockets connection setup.
*
* The opening stream tag is sent here.
*/
_onOpen() {
Strophe.debug("Websocket open");
const start = this._buildStream();
this._conn.xmlOutput(start.tree());
const startString = Strophe.serialize(start);
this._conn.rawOutput(startString);
this.socket.send(startString);
}
/** PrivateFunction: _reqToData
* _Private_ function to get a stanza out of a request.
*
* WebSockets don't use requests, so the passed argument is just returned.
*
* Parameters:
* (Object) stanza - The stanza.
*
* Returns:
* The stanza that was passed.
*/
_reqToData(stanza) {
// eslint-disable-line class-methods-use-this
return stanza;
}
/** PrivateFunction: _send
* _Private_ part of the Connection.send function for WebSocket
*
* Just flushes the messages that are in the queue
*/
_send() {
this._conn.flush();
}
/** PrivateFunction: _sendRestart
*
* Send an xmpp:restart stanza.
*/
_sendRestart() {
clearTimeout(this._conn._idleTimeout);
this._conn._onIdle.bind(this._conn)();
}
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/worker-websocket.js
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2020, JC Brand
*/
const lmap = {};
lmap['debug'] = Strophe.LogLevel.DEBUG;
lmap['info'] = Strophe.LogLevel.INFO;
lmap['warn'] = Strophe.LogLevel.WARN;
lmap['error'] = Strophe.LogLevel.ERROR;
lmap['fatal'] = Strophe.LogLevel.FATAL;
/** Class: Strophe.WorkerWebsocket
* _Private_ helper class that handles a websocket connection inside a shared worker.
*/
Strophe.WorkerWebsocket = class WorkerWebsocket extends Strophe.Websocket {
/** PrivateConstructor: Strophe.WorkerWebsocket
* Create and initialize a Strophe.WorkerWebsocket object.
*
* Parameters:
* (Strophe.Connection) connection - The Strophe.Connection
*
* Returns:
* A new Strophe.WorkerWebsocket object.
*/
constructor(connection) {
super(connection);
this._conn = connection;
this.worker = new SharedWorker(this._conn.options.worker, 'Strophe XMPP Connection');
this.worker.onerror = e => {
var _console;
(_console = console) === null || _console === void 0 ? void 0 : _console.error(e);
Strophe.log(Strophe.LogLevel.ERROR, `Shared Worker Error: ${e}`);
};
}
get socket() {
return {
'send': str => this.worker.port.postMessage(['send', str])
};
}
_connect() {
this._messageHandler = m => this._onInitialMessage(m);
this.worker.port.start();
this.worker.port.onmessage = ev => this._onWorkerMessage(ev);
this.worker.port.postMessage(['_connect', this._conn.service, this._conn.jid]);
}
_attach(callback) {
this._messageHandler = m => this._onMessage(m);
this._conn.connect_callback = callback;
this.worker.port.start();
this.worker.port.onmessage = ev => this._onWorkerMessage(ev);
this.worker.port.postMessage(['_attach', this._conn.service]);
}
_attachCallback(status, jid) {
if (status === Strophe.Status.ATTACHED) {
this._conn.jid = jid;
this._conn.authenticated = true;
this._conn.connected = true;
this._conn.restored = true;
this._conn._changeConnectStatus(Strophe.Status.ATTACHED);
} else if (status === Strophe.Status.ATTACHFAIL) {
this._conn.authenticated = false;
this._conn.connected = false;
this._conn.restored = false;
this._conn._changeConnectStatus(Strophe.Status.ATTACHFAIL);
}
}
_disconnect(readyState, pres) {
pres && this._conn.send(pres);
const close = $build("close", {
"xmlns": Strophe.NS.FRAMING
});
this._conn.xmlOutput(close.tree());
const closeString = Strophe.serialize(close);
this._conn.rawOutput(closeString);
this.worker.port.postMessage(['send', closeString]);
this._conn._doDisconnect();
}
_onClose(e) {
if (this._conn.connected && !this._conn.disconnecting) {
Strophe.error("Websocket closed unexpectedly");
this._conn._doDisconnect();
} else if (e && e.code === 1006 && !this._conn.connected) {
// in case the onError callback was not called (Safari 10 does not
// call onerror when the initial connection fails) we need to
// dispatch a CONNFAIL status update to be consistent with the
// behavior on other browsers.
Strophe.error("Websocket closed unexcectedly");
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");
this._conn._doDisconnect();
} else {
Strophe.debug("Websocket closed");
}
}
_closeSocket() {
this.worker.port.postMessage(['_closeSocket']);
}
/** PrivateFunction: _replaceMessageHandler
*
* Called by _onInitialMessage in order to replace itself with the general message handler.
* This method is overridden by Strophe.WorkerWebsocket, which manages a
* websocket connection via a service worker and doesn't have direct access
* to the socket.
*/
_replaceMessageHandler() {
this._messageHandler = m => this._onMessage(m);
}
/** PrivateFunction: _onWorkerMessage
* _Private_ function that handles messages received from the service worker
*/
_onWorkerMessage(ev) {
const {
data
} = ev;
const method_name = data[0];
if (method_name === '_onMessage') {
this._messageHandler(data[1]);
} else if (method_name in this) {
try {
this[method_name].apply(this, ev.data.slice(1));
} catch (e) {
Strophe.log(Strophe.LogLevel.ERROR, e);
}
} else if (method_name === 'log') {
const level = data[1];
const msg = data[2];
Strophe.log(lmap[level], msg);
} else {
Strophe.log(Strophe.LogLevel.ERROR, `Found unhandled service worker message: ${data}`);
}
}
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/strophe.js
/*global global*/
__webpack_require__.g.$build = core.$build;
__webpack_require__.g.$iq = core.$iq;
__webpack_require__.g.$msg = core.$msg;
__webpack_require__.g.$pres = core.$pres;
__webpack_require__.g.Strophe = core.Strophe;
const {
b64_sha1
} = SHA1;
;// CONCATENATED MODULE: ./src/headless/shared/constants.js
const BOSH_WAIT = 59;
const CONNECTION_STATUS = {};
CONNECTION_STATUS[Strophe.Status.ATTACHED] = 'ATTACHED';
CONNECTION_STATUS[Strophe.Status.AUTHENTICATING] = 'AUTHENTICATING';
CONNECTION_STATUS[Strophe.Status.AUTHFAIL] = 'AUTHFAIL';
CONNECTION_STATUS[Strophe.Status.CONNECTED] = 'CONNECTED';
CONNECTION_STATUS[Strophe.Status.CONNECTING] = 'CONNECTING';
CONNECTION_STATUS[Strophe.Status.CONNFAIL] = 'CONNFAIL';
CONNECTION_STATUS[Strophe.Status.DISCONNECTED] = 'DISCONNECTED';
CONNECTION_STATUS[Strophe.Status.DISCONNECTING] = 'DISCONNECTING';
CONNECTION_STATUS[Strophe.Status.ERROR] = 'ERROR';
CONNECTION_STATUS[Strophe.Status.RECONNECTING] = 'RECONNECTING';
CONNECTION_STATUS[Strophe.Status.REDIRECT] = 'REDIRECT'; // 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-carbons', 'converse-chat', 'converse-chatboxes', 'converse-disco', 'converse-emoji', 'converse-headlines', 'converse-mam', 'converse-muc', 'converse-ping', 'converse-pubsub', 'converse-roster', 'converse-smacks', 'converse-status', 'converse-vcard'];
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
};
;// 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 _toSource_funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var _toSource_funcToString = _toSource_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 _toSource_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/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/isLength.js
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/* harmony default export */ const lodash_es_isLength = (isLength);
;// 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/_isIndex.js
/** Used as references for various `Number` constants. */
var _isIndex_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 ? _isIndex_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/_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/_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/_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/_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]',
_baseIsTypedArray_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[_baseIsTypedArray_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/_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/_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/_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/_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/_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/_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/_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/_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/_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/_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/_Uint8Array.js
/** Built-in value references. */
var _Uint8Array_Uint8Array = _root.Uint8Array;
/* harmony default export */ const _Uint8Array = (_Uint8Array_Uint8Array);
;// 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]',
symbolTag = '[object Symbol]';
var _equalByTag_arrayBufferTag = '[object ArrayBuffer]',
_equalByTag_dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = _Symbol ? _Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case _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 symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/* harmony default export */ const _equalByTag = (equalByTag);
;// 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/_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/_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/_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/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/_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/_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/_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/_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/_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/isSymbol.js
/** `Object#toString` result references. */
var isSymbol_symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(lodash_es_isObjectLike(value) && _baseGetTag(value) == isSymbol_symbolTag);
}
/* harmony default export */ 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/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 _baseToString_symbolProto = _Symbol ? _Symbol.prototype : undefined,
symbolToString = _baseToString_symbolProto ? _baseToString_symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (lodash_es_isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return _arrayMap(value, baseToString) + '';
}
if (lodash_es_isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/* harmony default export */ 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/_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/_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/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/_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/_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/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/_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/_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/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 Error {} // Helpers
// -------
// Helper function to correctly set up the prototype chain for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
//
function inherits(protoProps, staticProps) {
const parent = this;
let child; // The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent constructor.
if (protoProps && lodash_es_has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function () {
return parent.apply(this, arguments);
};
} // Add static properties to the constructor function, if supplied.
lodash_es_assignIn(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function and add the prototype properties.
child.prototype = lodash_es_create(parent.prototype, protoProps);
child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
}
function getResolveablePromise() {
const wrapper = {
isResolved: false,
isPending: true,
isRejected: false
};
const promise = new Promise((resolve, reject) => {
wrapper.resolve = resolve;
wrapper.reject = reject;
});
Object.assign(promise, wrapper);
promise.then(function (v) {
promise.isResolved = true;
promise.isPending = false;
promise.isRejected = false;
return v;
}, function (e) {
promise.isResolved = false;
promise.isPending = false;
promise.isRejected = true;
throw e;
});
return promise;
} // Throw an error when a URL is needed, and none is supplied.
function urlError() {
throw new Error('A "url" property or function must be specified');
} // Wrap an optional error callback with a fallback error event.
function wrapError(model, options) {
const error = options.error;
options.error = function (resp) {
if (error) error.call(options.context, model, resp, options);
model.trigger('error', model, resp, options);
};
} // Map from CRUD to HTTP for our default `sync` implementation.
const methodMap = {
create: 'POST',
update: 'PUT',
patch: 'PATCH',
delete: 'DELETE',
read: 'GET'
};
function getSyncMethod(model) {
const store = lodash_es_result(model, 'browserStorage') || lodash_es_result(model.collection, 'browserStorage');
return store ? store.sync() : 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/@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/errors.js
/**
* Custom error for indicating timeouts
* @namespace _converse
*/
class TimeoutError extends Error {}
// EXTERNAL MODULE: ./node_modules/localforage-driver-memory/_bundle/umd.js
var umd = __webpack_require__(3245);
;// 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/_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/_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/_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/_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,
_cloneSymbol_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 _cloneSymbol_symbolValueOf ? Object(_cloneSymbol_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/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__(9236);
}
/* 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 serialize(value, callback) {
var valueType = '';
if (value) {
valueType = serializer_toString.call(value);
} // Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (valueType === '[object ArrayBuffer]' || value.buffer && serializer_toString.call(value.buffer) === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueType === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueType === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueType === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueType === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueType === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueType === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueType === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueType === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueType === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
} // Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
} // The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType; // Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return utils_createBlob([buffer], {
type: blobType
});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
/* harmony default export */ 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/@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: ./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 !== null && options !== void 0 && options.dedupeArrays) {
return objValue.concat(srcValue.filter(i => objValue.indexOf(i) === -1));
} else {
return objValue.concat(srcValue);
}
}
}
function mergeArguments(args) {
var _lastArgs;
if ((_lastArgs = lastArgs) !== null && _lastArgs !== void 0 && _lastArgs.length) {
if (!args.length) {
return lastArgs;
}
if (options !== null && options !== void 0 && options.concatArrays || options !== null && options !== void 0 && 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.
function sessionStorage_setItem(key, value, callback) {
key = normalizeKey(key);
const promise = this.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
} // Save the original value to pass to the callback.
const originalValue = value;
return new Promise(function (resolve, reject) {
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
sessionStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// sessionStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
utils_executeCallback(promise, callback);
return promise;
}
function 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__(1459);
// EXTERNAL MODULE: ./node_modules/localforage-getitems/dist/localforage-getitems.js
var localforage_getitems = __webpack_require__(642);
;// 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);
function S4() {
// Generate four random hex digits.
return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
}
function guid() {
// Generate a pseudo-GUID by concatenating random hexadecimal.
return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
}
class Storage {
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() {
var _this$store$debounced;
return (_this$store$debounced = this.store.debouncedSetItems) === null || _this$store$debounced === void 0 ? void 0 : _this$store$debounced.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 !== null && keys !== void 0 && 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 = core_api.settings.get('persistent_store') === 'sessionStorage';
return is_non_persistent ? 'session' : 'persistent';
} else {
return 'session';
}
}
function storeUsesIndexedDB(store) {
return store === 'persistent' && core_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: ./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/_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/_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/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);
// EXTERNAL MODULE: ./node_modules/dompurify/dist/purify.js
var purify = __webpack_require__(7856);
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);
;// 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);
// EXTERNAL MODULE: ./node_modules/sizzle/dist/sizzle.js
var sizzle = __webpack_require__(1271);
var sizzle_default = /*#__PURE__*/__webpack_require__.n(sizzle);
;// 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/_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/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/_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/_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/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/@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: ./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__(7002);
// EXTERNAL MODULE: ./node_modules/localforage-webextensionstorage-driver/sync.js
var localforage_webextensionstorage_driver_sync = __webpack_require__(1063);
;// CONCATENATED MODULE: ./src/headless/shared/connection/index.js
const i = Object.keys(Strophe.Status).reduce((max, k) => Math.max(max, Strophe.Status[k]), 0);
Strophe.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 extends Strophe.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 core_api.trigger('beforeResourceBinding', {
'synchronous': true
});
super.bind();
}
async onDomainDiscovered(response) {
const text = await response.text();
const xrd = new window.DOMParser().parseFromString(text, "text/xml").firstElementChild;
if (xrd.nodeName != "XRD" || xrd.namespaceURI != "http://docs.oasis-open.org/ns/xri/xrd-1.0") {
return headless_log.warn("Could not discover XEP-0156 connection methods");
}
const bosh_links = sizzle_default()(`Link[rel="urn:xmpp:alt-connections:xbosh"]`, xrd);
const ws_links = sizzle_default()(`Link[rel="urn:xmpp:alt-connections:websocket"]`, xrd);
const bosh_methods = bosh_links.map(el => el.getAttribute('href'));
const ws_methods = ws_links.map(el => el.getAttribute('href'));
if (bosh_methods.length === 0 && ws_methods.length === 0) {
headless_log.warn("Neither BOSH nor WebSocket connection methods have been specified with XEP-0156.");
} else {
// TODO: support multiple endpoints
core_api.settings.set("websocket_url", ws_methods.pop());
core_api.settings.set('bosh_service_url', bosh_methods.pop());
this.service = core_api.settings.get("websocket_url") || core_api.settings.get('bosh_service_url');
this.setProtocol();
}
}
/**
* Adds support for XEP-0156 by quering the XMPP server for alternate
* connection methods. This allows users to use the websocket or BOSH
* connection of their own XMPP server instead of a proxy provided by the
* host of Converse.js.
* @method Connnection.discoverConnectionMethods
*/
async discoverConnectionMethods(domain) {
// Use XEP-0156 to check whether this host advertises websocket or BOSH connection methods.
const options = {
'mode': 'cors',
'headers': {
'Accept': 'application/xrd+xml, text/xml'
}
};
const url = `https://${domain}/.well-known/host-meta`;
let response;
try {
response = await fetch(url, options);
} catch (e) {
headless_log.error(`Failed to discover alternative connection methods at ${url}`);
headless_log.error(e);
return;
}
if (response.status >= 200 && response.status < 400) {
await this.onDomainDiscovered(response);
} else {
headless_log.warn("Could not discover XEP-0156 connection methods");
}
}
/**
* Establish a new XMPP session by logging in with the supplied JID and
* password.
* @method Connnection.connect
* @param { String } jid
* @param { String } password
* @param { Funtion } callback
*/
async connect(jid, password, callback) {
if (core_api.settings.get("discover_connection_methods")) {
const domain = Strophe.getDomainFromJid(jid);
await this.discoverConnectionMethods(domain);
}
if (!core_api.settings.get('bosh_service_url') && !core_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 (core_api.connection.isType('websocket') && core_api.settings.get('bosh_service_url')) {
await setUserJID(shared_converse.bare_jid);
this._proto._doDisconnect();
this._proto = new Strophe.Bosh(this);
this.service = core_api.settings.get('bosh_service_url');
} else if (core_api.connection.isType('bosh') && core_api.settings.get("websocket_url")) {
if (core_api.settings.get("authentication") === shared_converse.ANONYMOUS) {
// When reconnecting anonymously, we need to connect with only
// the domain, not the full JID that we had in our previous
// (now failed) session.
await setUserJID(core_api.settings.get("jid"));
} else {
await setUserJID(shared_converse.bare_jid);
}
this._proto._doDisconnect();
this._proto = new Strophe.Websocket(this);
this.service = core_api.settings.get("websocket_url");
}
}
async reconnect() {
headless_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 === Strophe.Status.CONNFAIL) {
this.switchTransport();
} else if (conn_status === Strophe.Status.AUTHFAIL && core_api.settings.get("authentication") === shared_converse.ANONYMOUS) {
// When reconnecting anonymously, we need to connect with only
// the domain, not the full JID that we had in our previous
// (now failed) session.
await setUserJID(core_api.settings.get("jid"));
}
/**
* Triggered when the connection has dropped, but Converse will attempt
* to reconnect again.
* @event _converse#will-reconnect
*/
core_api.trigger('will-reconnect');
if (core_api.settings.get("authentication") === shared_converse.ANONYMOUS) {
await clearSession();
}
return core_api.user.login();
}
/**
* Called as soon as a new connection has been established, either
* by logging in or by attaching to an existing BOSH session.
* @method Connection.onConnected
* @param { Boolean } reconnecting - Whether Converse.js reconnected from an earlier dropped session.
*/
async onConnected(reconnecting) {
delete this.reconnecting;
this.flush(); // Solves problem of returned PubSub BOSH response not received by browser
await setUserJID(this.jid);
/**
* Synchronous event triggered after we've sent an IQ to bind the
* user's JID resource for this session.
* @event _converse#afterResourceBinding
*/
await core_api.trigger('afterResourceBinding', reconnecting, {
'synchronous': true
});
if (reconnecting) {
/**
* After the connection has dropped and converse.js has reconnected.
* Any Strophe stanza handlers (as registered via `converse.listen.stanza`) will
* have to be registered anew.
* @event _converse#reconnected
* @example _converse.api.listen.on('reconnected', () => { ... });
*/
core_api.trigger('reconnected');
} else {
/**
* Triggered after the connection has been established and Converse
* has got all its ducks in a row.
* @event _converse#initialized
*/
core_api.trigger('connected');
}
}
/**
* Used to keep track of why we got disconnected, so that we can
* decide on what the next appropriate action is (in onDisconnected)
* @method Connection.setDisconnectionCause
* @param { Number } cause - The status number as received from Strophe.
* @param { String } [reason] - An optional user-facing message as to why
* there was a disconnection.
* @param { Boolean } [override] - An optional flag to replace any previous
* disconnection cause and reason.
*/
setDisconnectionCause(cause, reason, override) {
if (cause === undefined) {
delete this.disconnection_cause;
delete this.disconnection_reason;
} else if (this.disconnection_cause === undefined || override) {
this.disconnection_cause = cause;
this.disconnection_reason = reason;
}
}
setConnectionStatus(status, message) {
this.status = status;
shared_converse.connfeedback.set({
'connection_status': status,
message
});
}
async finishDisconnection() {
// Properly tear down the session so that it's possible to manually connect again.
headless_log.debug('DISCONNECTED');
delete this.reconnecting;
this.reset();
tearDown();
await clearSession();
delete shared_converse.connection;
/**
* Triggered after converse.js has disconnected from the XMPP server.
* @event _converse#disconnected
* @memberOf _converse
* @example _converse.api.listen.on('disconnected', () => { ... });
*/
core_api.trigger('disconnected');
}
/**
* Gets called once strophe's status reaches Strophe.Status.DISCONNECTED.
* Will either start a teardown process for converse.js or attempt
* to reconnect.
* @method onDisconnected
*/
onDisconnected() {
if (core_api.settings.get("auto_reconnect")) {
const reason = this.disconnection_reason;
if (this.disconnection_cause === Strophe.Status.AUTHFAIL) {
if (core_api.settings.get("credentials_url") || core_api.settings.get("authentication") === shared_converse.ANONYMOUS) {
// If `credentials_url` is set, we reconnect, because we might
// be receiving expirable tokens from the credentials_url.
//
// If `authentication` is anonymous, we reconnect because we
// might have tried to attach with stale BOSH session tokens
// or with a cached JID and password
return core_api.connection.reconnect();
} else {
return this.finishDisconnection();
}
} else if (this.status === Strophe.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(Strophe.Status.CONNFAIL, __('An error occurred while connecting to the chat server.'));
return this.finishDisconnection();
} else if (this.disconnection_cause === shared_converse.LOGOUT || reason === Strophe.ErrorCondition.NO_AUTH_MECH || reason === "host-unknown" || reason === "remote-connection-failed") {
return this.finishDisconnection();
}
core_api.connection.reconnect();
} else {
return this.finishDisconnection();
}
}
/**
* Callback method called by Strophe as the Connection goes
* through various states while establishing or tearing down a
* connection.
* @param { Number } status
* @param { String } message
*/
onConnectStatusChanged(status, message) {
const {
__
} = shared_converse;
headless_log.debug(`Status changed to: ${shared_converse.CONNECTION_STATUS[status]}`);
if (status === Strophe.Status.ATTACHFAIL) {
var _this$worker_attach_p;
this.setConnectionStatus(status);
(_this$worker_attach_p = this.worker_attach_promise) === null || _this$worker_attach_p === void 0 ? void 0 : _this$worker_attach_p.resolve(false);
} else if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
var _this$worker_attach_p2, _this$worker_attach_p3;
if ((_this$worker_attach_p2 = this.worker_attach_promise) !== null && _this$worker_attach_p2 !== void 0 && _this$worker_attach_p2.isResolved && this.status === Strophe.Status.ATTACHED) {
// A different tab must have attached, so nothing to do for us here.
return;
}
this.setConnectionStatus(status);
(_this$worker_attach_p3 = this.worker_attach_promise) === null || _this$worker_attach_p3 === void 0 ? void 0 : _this$worker_attach_p3.resolve(true); // By default we always want to send out an initial presence stanza.
shared_converse.send_initial_presence = true;
this.setDisconnectionCause();
if (this.reconnecting) {
headless_log.debug(status === Strophe.Status.CONNECTED ? 'Reconnected' : 'Reattached');
this.onConnected(true);
} else {
headless_log.debug(status === Strophe.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 === Strophe.Status.DISCONNECTED) {
this.setDisconnectionCause(status, message);
this.onDisconnected();
} else if (status === Strophe.Status.BINDREQUIRED) {
this.bind();
} else if (status === Strophe.Status.ERROR) {
this.setConnectionStatus(status, __('An error occurred while connecting to the chat server.'));
} else if (status === Strophe.Status.CONNECTING) {
this.setConnectionStatus(status);
} else if (status === Strophe.Status.AUTHENTICATING) {
this.setConnectionStatus(status);
} else if (status === Strophe.Status.AUTHFAIL) {
if (!message) {
message = __('Your XMPP address and/or password is incorrect. Please try again.');
}
this.setConnectionStatus(status, message);
this.setDisconnectionCause(status, message, true);
this.onDisconnected();
} else if (status === Strophe.Status.CONNFAIL) {
var _Strophe$ErrorConditi;
let feedback = message;
if (message === "host-unknown" || message == "remote-connection-failed") {
feedback = __("Sorry, we could not connect to the XMPP host with domain: %1$s", `\"${Strophe.getDomainFromJid(this.jid)}\"`);
} else if (message !== undefined && message === (Strophe === null || Strophe === void 0 ? void 0 : (_Strophe$ErrorConditi = Strophe.ErrorCondition) === null || _Strophe$ErrorConditi === void 0 ? void 0 : _Strophe$ErrorConditi.NO_AUTH_MECH)) {
feedback = __("The XMPP server did not offer a supported authentication mechanism");
}
this.setConnectionStatus(status, feedback);
this.setDisconnectionCause(status, message);
} else if (status === Strophe.Status.DISCONNECTING) {
this.setDisconnectionCause(status, message);
}
}
isType(type) {
if (type.toLowerCase() === 'websocket') {
return this._proto instanceof Strophe.Websocket;
} else if (type.toLowerCase() === 'bosh') {
return Strophe.Bosh && this._proto instanceof Strophe.Bosh;
}
}
hasResumed() {
var _api$settings$get;
if ((_api$settings$get = core_api.settings.get("connection_options")) !== null && _api$settings$get !== void 0 && _api$settings$get.worker || this.isType('bosh')) {
return shared_converse.connfeedback.get('connection_status') === Strophe.Status.ATTACHED;
} else {
// Not binding means that the session was resumed.
return !this.do_bind;
}
}
restoreWorkerSession() {
this.attach(this.onConnectStatusChanged);
this.worker_attach_promise = getOpenPromise();
return this.worker_attach_promise;
}
}
/**
* The MockConnection class is used during testing, to mock an XMPP connection.
* @class
*/
class MockConnection extends Connection {
constructor(service, options) {
super(service, options);
this.sent_stanzas = [];
this.IQ_stanzas = [];
this.IQ_ids = [];
this.features = Strophe.xmlHtmlNode('' + '' + '' + '' + '' + '' + '' + `` + '' + '' + '' + '').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(Strophe.Status.BINDREQUIRED);
};
}
_processRequest() {// eslint-disable-line class-methods-use-this
// Don't attempt to send out stanzas
}
sendIQ(iq, callback, errback) {
if (!lodash_es_isElement(iq)) {
iq = iq.nodeTree;
}
this.IQ_stanzas.push(iq);
const id = super.sendIQ(iq, callback, errback);
this.IQ_ids.push(id);
return id;
}
send(stanza) {
if (lodash_es_isElement(stanza)) {
this.sent_stanzas.push(stanza);
} else {
this.sent_stanzas.push(stanza.nodeTree);
}
return super.send(stanza);
}
async bind() {
await core_api.trigger('beforeResourceBinding', {
'synchronous': true
});
this.authenticated = true;
if (!shared_converse.no_connection_on_bind) {
this._changeConnectStatus(Strophe.Status.CONNECTED);
}
}
}
;// CONCATENATED MODULE: ./src/headless/utils/init.js
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") !== _converse.ANONYMOUS && !Strophe.getResourceFromJid(jid)) {
jid = jid.toLowerCase() + Connection.generateResource();
}
_converse.jid = jid;
_converse.bare_jid = Strophe.getBareJidFromJid(jid);
_converse.resource = Strophe.getResourceFromJid(jid);
_converse.domain = Strophe.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.
'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 _converse.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) {
var _converse$session;
const is_shared_session = _converse.api.settings.get('connection_options').worker;
const bare_jid = Strophe.getBareJidFromJid(jid).toLowerCase();
const id = `converse.session-${bare_jid}`;
if (((_converse$session = _converse.session) === null || _converse$session === void 0 ? void 0 : _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);
/**
* 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", _converse.saveWindowState);
_converse.saveWindowState({
'type': document.hidden ? "blur" : "focus"
}); // Set initial state
/**
* Called once Converse has registered its global event handlers
* (for events such as window resize or unload).
* Plugins can listen to this event as cue to register their own
* global event handlers.
* @event _converse#registeredGlobalEventHandlers
* @example _converse.api.listen.on('registeredGlobalEventHandlers', () => { ... });
*/
_converse.api.trigger('registeredGlobalEventHandlers');
}
function unregisterGlobalEventHandlers(_converse) {
const {
api
} = _converse;
document.removeEventListener("visibilitychange", _converse.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) {
var _converse$connection;
const {
api
} = _converse;
await api.trigger('cleanup', {
'synchronous': true
});
_converse.router.history.stop();
unregisterGlobalEventHandlers(_converse);
(_converse$connection = _converse.connection) === null || _converse$connection === void 0 ? void 0 : _converse$connection.reset();
_converse.stopListening();
_converse.off();
if (_converse.promises['initialized'].isResolved) {
api.promises.add('initialized');
}
}
async function getLoginCredentials() {
let credentials;
let wait = 0;
while (!credentials) {
try {
credentials = await fetchLoginCredentials(wait); // eslint-disable-line no-await-in-loop
} catch (e) {
headless_log.error('Could not fetch login credentials');
headless_log.error(e);
} // If unsuccessful, we wait 2 seconds between subsequent attempts to
// fetch the credentials.
wait = 2000;
}
return credentials;
}
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 attemptNonPreboundSession(credentials, automatic) {
const {
api
} = shared_converse;
if (api.settings.get("authentication") === shared_converse.LOGIN) {
// XXX: If EITHER ``keepalive`` or ``auto_login`` is ``true`` and
// ``authentication`` is set to ``login``, then Converse will try to log the user in,
// since we don't have a way to distinguish between wether we're
// restoring a previous session (``keepalive``) or whether we're
// automatically setting up a new session (``auto_login``).
// So we can't do the check (!automatic || _converse.api.settings.get("auto_login")) here.
if (credentials) {
connect(credentials);
} else if (api.settings.get("credentials_url")) {
// We give credentials_url preference, because
// _converse.connection.pass might be an expired token.
connect(await getLoginCredentials());
} else if (shared_converse.jid && (api.settings.get("password") || shared_converse.connection.pass)) {
connect();
} else if (!shared_converse.isTestEnv() && 'credentials' in navigator) {
connect(await getLoginCredentialsFromBrowser());
} else {
!shared_converse.isTestEnv() && headless_log.warn("attemptNonPreboundSession: Couldn't find credentials to log in with");
}
} else if ([shared_converse.ANONYMOUS, shared_converse.EXTERNAL].includes(api.settings.get("authentication")) && (!automatic || api.settings.get("auto_login"))) {
connect();
}
}
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 connect(credentials) {
const {
api
} = shared_converse;
if ([shared_converse.ANONYMOUS, shared_converse.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") === shared_converse.LOGIN) {
var _converse$connection2;
const password = (credentials === null || credentials === void 0 ? void 0 : credentials.password) ?? (((_converse$connection2 = shared_converse.connection) === null || _converse$connection2 === void 0 ? void 0 : _converse$connection2.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(Strophe.Status.AUTHFAIL, undefined, true);
api.connection.disconnect();
return;
}
if (!shared_converse.connection.reconnecting) {
shared_converse.connection.reset();
shared_converse.connection.service = getConnectionServiceURL();
}
shared_converse.connection.connect(shared_converse.jid, password);
}
}
;// 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) {
headless_log.warn('The api.settings.update method has been deprecated and will be removed. ' + 'Please use api.settings.extend instead.');
return this.extend(settings);
},
/**
* @method _converse.api.settings.get
* @returns {*} Value of the particular configuration setting.
* @example _converse.api.settings.get("play_sounds");
*/
get(key) {
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} [settings] An object containing configuration settings.
* @param {string} [key] Alternatively to passing in an object, you can pass in a key and a value.
* @param {string} [value]
* @example _converse.api.settings.set("play_sounds", true);
* @example
* _converse.api.settings.set({
* "play_sounds": true,
* "hide_offline_users": true
* });
*/
set(key, val) {
updateAppSettings(key, val);
},
/**
* 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 } callback 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}
* @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/core.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description This is the core utilities module.
*/
function isEmptyMessage(attrs) {
if (attrs instanceof Model) {
attrs = attrs.attributes;
}
return !attrs['oob_url'] && !attrs['file'] && !(attrs['is_encrypted'] && attrs['plaintext']) && !attrs['message'];
}
/* 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"));
}
async function tearDown() {
await shared_converse.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);
shared_converse.api.trigger('afterTearDown');
return shared_converse;
}
/**
* The utils object
* @namespace u
*/
const u = {};
u.isTagEqual = function (stanza, name) {
if (stanza.nodeTree) {
return u.isTagEqual(stanza.nodeTree, name);
} else if (!(stanza instanceof Element)) {
throw Error("isTagEqual called with value which isn't " + "an element or Strophe.Builder instance");
} else {
return Strophe.isTagEqual(stanza, name);
}
};
const parser = new DOMParser();
const parserErrorNS = parser.parseFromString('invalid', 'text/xml').getElementsByTagName("parsererror")[0].namespaceURI;
u.getJIDFromURI = function (jid) {
return jid.startsWith('xmpp:') && jid.endsWith('?join') ? jid.replace(/^xmpp:/, '').replace(/\?join$/, '') : jid;
};
u.toStanza = function (string) {
const node = parser.parseFromString(string, "text/xml");
if (node.getElementsByTagNameNS(parserErrorNS, 'parsererror').length) {
throw new Error(`Parser Error: ${string}`);
}
return node.firstElementChild;
};
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, '');
};
/**
* 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.isValidJID = function (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 Strophe.getBareJidFromJid(jid1).toLowerCase() === Strophe.getBareJidFromJid(jid2).toLowerCase();
};
u.isSameDomain = function (jid1, jid2) {
if (typeof jid1 !== 'string' || typeof jid2 !== 'string') {
return false;
}
return Strophe.getDomainFromJid(jid1).toLowerCase() === Strophe.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="${Strophe.NS.MAM}"]`, message).length && sizzle_default()(`delay[xmlns="${Strophe.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';
};
u.isErrorObject = function (o) {
return o instanceof Error;
};
u.isErrorStanza = function (stanza) {
if (!lodash_es_isElement(stanza)) {
return false;
}
return stanza.getAttribute('type') === 'error';
};
u.isForbiddenError = function (stanza) {
if (!lodash_es_isElement(stanza)) {
return false;
}
return sizzle_default()(`error[type="auth"] forbidden[xmlns="${Strophe.NS.STANZAS}"]`, stanza).length > 0;
};
u.isServiceUnavailableError = function (stanza) {
if (!lodash_es_isElement(stanza)) {
return false;
}
return sizzle_default()(`error[type="cancel"] service-unavailable[xmlns="${Strophe.NS.STANZAS}"]`, stanza).length > 0;
};
/**
* Merge the second object into the first one.
* @private
* @method u#merge
* @param { Object } first
* @param { Object } second
*/
u.merge = function merge(first, second) {
for (const k in second) {
if (lodash_es_isObject(first[k])) {
merge(first[k], second[k]);
} else {
first[k] = second[k];
}
}
};
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 { DOMElement } 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 { DOMElement } 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 {integer} [index] - An optional rightmost boundary index. If given, the text
* value of the input element will only be considered up until this index.
* @param {string} [delineator] - An optional string delineator to
* differentiate between words.
* @private
*/
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;
};
u.getRandomInt = function (max) {
return Math.floor(Math.random() * Math.floor(max));
};
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 = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
if (typeof suffix === "string" || typeof suffix === "number") {
return uuid + ":" + suffix;
} else {
return uuid;
}
}
u.httpToGeoUri = function (text) {
const replacement = 'geo:$1,$2';
return text.replace(settings_api.get("geouri_regex"), replacement);
};
/**
* 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
*/
u.waitUntil = function (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();
headless_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';
}
}
async function getLoginCredentialsFromBrowser() {
try {
const creds = await navigator.credentials.get({
'password': true
});
if (creds && creds.type == 'password' && u.isValidJID(creds.id)) {
await setUserJID(creds.id);
return {
'jid': creds.id,
'password': creds.password
};
}
} catch (e) {
headless_log.error(e);
}
}
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 {
headless_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;
}
/* harmony default export */ const utils_core = (Object.assign({
prefixMentions,
isEmptyMessage,
getUniqueId
}, u));
;// 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 } [auto_reconnect=true]
* @property { Array} [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 } [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} [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
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', 'eo', 'es', 'eu', 'en', 'fa', 'fi', 'fr', 'gl', 'he', 'hi', 'hu', 'id', 'it', 'ja', 'lt', 'nb', 'nl', 'mr', 'oc', 'pl', 'pt', 'pt_BR', 'ro', 'ru', 'sv', 'th', 'tr', '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,
view_mode: 'overlayed',
// Choices are 'overlayed', 'fullscreen', 'mobile'
websocket_url: undefined,
whitelisted_plugins: []
};
;// 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() {
var _user_settings;
if (!shared_converse.bare_jid) {
const msg = "No JID to fetch user settings for";
headless_log.error(msg);
throw Error(msg);
}
if (!((_user_settings = user_settings) !== null && _user_settings !== void 0 && _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/_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 = {
log: headless_log,
CONNECTION_STATUS: CONNECTION_STATUS,
templates: {},
promises: {
'initialized': getOpenPromise()
},
STATUS_WEIGHTS: {
'offline': 6,
'unavailable': 5,
'xa': 4,
'away': 3,
'dnd': 2,
'chat': 1,
// We currently don't differentiate between "chat" and "online"
'online': 1
},
ANONYMOUS: 'anonymous',
CLOSED: 'closed',
EXTERNAL: 'external',
LOGIN: 'login',
LOGOUT: 'logout',
OPENED: 'opened',
PREBIND: 'prebind',
/**
* @constant
* @type { integer }
*/
STANZA_TIMEOUT: 20000,
SUCCESS: 'success',
FAILURE: 'failure',
// Generated from css/images/user.svg
DEFAULT_IMAGE_TYPE: 'image/svg+xml',
DEFAULT_IMAGE: "PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iIzU1NSIvPgogPGNpcmNsZSBjeD0iNjQiIGN5PSI0MSIgcj0iMjQiIGZpbGw9IiNmZmYiLz4KIDxwYXRoIGQ9Im0yOC41IDExMiB2LTEyIGMwLTEyIDEwLTI0IDI0LTI0IGgyMyBjMTQgMCAyNCAxMiAyNCAyNCB2MTIiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg==",
TIMEOUTS: {
// Set as module attr so that we can override in tests.
PAUSED: 10000,
INACTIVE: 90000
},
// XEP-0085 Chat states
// https://xmpp.org/extensions/xep-0085.html
INACTIVE: 'inactive',
ACTIVE: 'active',
COMPOSING: 'composing',
PAUSED: 'paused',
GONE: 'gone',
// Chat types
PRIVATE_CHAT_TYPE: 'chatbox',
CHATROOMS_TYPE: 'chatroom',
HEADLINES_TYPE: 'headline',
CONTROLBOX_TYPE: 'controlbox',
default_connection_options: {
'explicitResourceBinding': true
},
router: new Router(),
TimeoutError: TimeoutError,
isTestEnv: () => {
return 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
};
/* harmony default export */ const shared_converse = (_converse);
// EXTERNAL MODULE: ./node_modules/dayjs/plugin/advancedFormat.js
var advancedFormat = __webpack_require__(8734);
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 api = ({
/**
* @method _converse.api.connection.connected
* @memberOf _converse.api.connection
* @returns {boolean} Whether there is an established connection or not.
*/
connected() {
var _converse$connection;
return (shared_converse === null || shared_converse === void 0 ? void 0 : (_converse$connection = shared_converse.connection) === null || _converse$connection === void 0 ? void 0 : _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(Strophe.Status.RECONNECTING, __('The connection has dropped, attempting to reconnect.'));
if (connection !== null && connection !== void 0 && 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);
}
});
// EXTERNAL MODULE: ./node_modules/dayjs/dayjs.min.js
var dayjs_min = __webpack_require__(7484);
var dayjs_min_default = /*#__PURE__*/__webpack_require__.n(dayjs_min);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseInvoke.js
/**
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
*/
function baseInvoke(object, path, args) {
path = _castPath(path, object);
object = _parent(object, path);
var func = object == null ? object : object[_toKey(lodash_es_last(path))];
return func == null ? undefined : _apply(func, object, args);
}
/* harmony default export */ const _baseInvoke = (baseInvoke);
;// CONCATENATED MODULE: ./node_modules/lodash-es/invoke.js
/**
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
*/
var invoke = _baseRest(_baseInvoke);
/* harmony default export */ const lodash_es_invoke = (invoke);
;// 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) {
var _plugin$dependencies;
(_plugin$dependencies = plugin.dependencies) === null || _plugin$dependencies === void 0 ? void 0 : _plugin$dependencies.forEach(name => {
const dep = this.plugins[name];
if (dep) {
var _dep$dependencies;
if ((_dep$dependencies = dep.dependencies) !== null && _dep$dependencies !== void 0 && _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) {
var _plugin$enabled;
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 = plugin.enabled) !== null && _plugin$enabled !== void 0 && _plugin$enabled.call(plugin, 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/_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) {
var _this$model$prototype;
return attrs[((_this$model$prototype = this.model.prototype) === null || _this$model$prototype === void 0 ? void 0 : _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/@lit/reactive-element/css-tag.js
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const css_tag_t=window.ShadowRoot&&(void 0===window.ShadyCSS||window.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,e=Symbol(),n=new Map;class s{constructor(t,n){if(this._$cssResult$=!0,n!==e)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t}get styleSheet(){let e=n.get(this.cssText);return css_tag_t&&void 0===e&&(n.set(this.cssText,e=new CSSStyleSheet),e.replaceSync(this.cssText)),e}toString(){return this.cssText}}const o=t=>new s("string"==typeof t?t:t+"",e),r=(t,...n)=>{const o=1===t.length?t[0]:n.reduce(((e,n,s)=>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.")})(n)+t[s+1]),t[0]);return new s(o,e)},css_tag_i=(e,n)=>{css_tag_t?e.adoptedStyleSheets=n.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet)):n.forEach((t=>{const n=document.createElement("style"),s=window.litNonce;void 0!==s&&n.setAttribute("nonce",s),n.textContent=t.cssText,e.appendChild(n)}))},S=css_tag_t?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return o(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.trustedTypes,reactive_element_r=reactive_element_e?reactive_element_e.emptyScript:"",h=window.reactiveElementPolyfillSupport,reactive_element_o={toAttribute(t,i){switch(i){case Boolean:t=t?reactive_element_r: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}},reactive_element_n=(t,i)=>i!==t&&(i==i||t==t),l={attribute:!0,type:String,converter:reactive_element_o,reflect:!1,hasChanged:reactive_element_n};class a extends HTMLElement{constructor(){super(),this._$Et=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Ei=null,this.o()}static addInitializer(t){var i;null!==(i=this.l)&&void 0!==i||(this.l=[]),this.l.push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach(((i,s)=>{const e=this._$Eh(s,i);void 0!==e&&(this._$Eu.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("finalized"))return!1;this.finalized=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),this.elementProperties=new Map(t.elementProperties),this._$Eu=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(S(i))}else void 0!==i&&s.push(S(i));return s}static _$Eh(t,i){const s=i.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof t?t.toLowerCase():void 0}o(){var t;this._$Ep=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$Em(),this.requestUpdate(),null===(t=this.constructor.l)||void 0===t||t.forEach((t=>t(this)))}addController(t){var i,s;(null!==(i=this._$Eg)&&void 0!==i?i:this._$Eg=[]).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._$Eg)||void 0===i||i.splice(this._$Eg.indexOf(t)>>>0,1)}_$Em(){this.constructor.elementProperties.forEach(((t,i)=>{this.hasOwnProperty(i)&&(this._$Et.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_i(s,this.constructor.elementStyles),s}connectedCallback(){var t;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(t=this._$Eg)||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._$Eg)||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)}_$ES(t,i,s=l){var e,r;const h=this.constructor._$Eh(t,s);if(void 0!==h&&!0===s.reflect){const n=(null!==(r=null===(e=s.converter)||void 0===e?void 0:e.toAttribute)&&void 0!==r?r:reactive_element_o.toAttribute)(i,s.type);this._$Ei=t,null==n?this.removeAttribute(h):this.setAttribute(h,n),this._$Ei=null}}_$AK(t,i){var s,e,r;const h=this.constructor,n=h._$Eu.get(t);if(void 0!==n&&this._$Ei!==n){const t=h.getPropertyOptions(n),l=t.converter,a=null!==(r=null!==(e=null===(s=l)||void 0===s?void 0:s.fromAttribute)&&void 0!==e?e:"function"==typeof l?l:null)&&void 0!==r?r:reactive_element_o.fromAttribute;this._$Ei=n,this[n]=a(i,t.type),this._$Ei=null}}requestUpdate(t,i,s){let e=!0;void 0!==t&&(((s=s||this.constructor.getPropertyOptions(t)).hasChanged||reactive_element_n)(this[t],i)?(this._$AL.has(t)||this._$AL.set(t,i),!0===s.reflect&&this._$Ei!==t&&(void 0===this._$EC&&(this._$EC=new Map),this._$EC.set(t,s))):e=!1),!this.isUpdatePending&&e&&(this._$Ep=this._$E_())}async _$E_(){this.isUpdatePending=!0;try{await this._$Ep}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._$Et&&(this._$Et.forEach(((t,i)=>this[i]=t)),this._$Et=void 0);let i=!1;const s=this._$AL;try{i=this.shouldUpdate(s),i?(this.willUpdate(s),null===(t=this._$Eg)||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._$EU()}catch(t){throw i=!1,this._$EU(),t}i&&this._$AE(s)}willUpdate(t){}_$AE(t){var i;null===(i=this._$Eg)||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)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$Ep}shouldUpdate(t){return!0}update(t){void 0!==this._$EC&&(this._$EC.forEach(((t,i)=>this._$ES(i,this[i],t))),this._$EC=void 0),this._$EU()}updated(t){}firstUpdated(t){}}a.finalized=!0,a.elementProperties=new Map,a.elementStyles=[],a.shadowRootOptions={mode:"open"},null==h||h({ReactiveElement:a}),(null!==(reactive_element_s=globalThis.reactiveElementVersions)&&void 0!==reactive_element_s?reactive_element_s:globalThis.reactiveElementVersions=[]).push("1.3.0");
//# 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 = globalThis.trustedTypes,
lit_html_s = lit_html_i ? lit_html_i.createPolicy("lit-html", {
createHTML: t => t
}) : void 0,
lit_html_e = `lit$${(Math.random() + "").slice(9)}$`,
lit_html_o = "?" + lit_html_e,
lit_html_n = `<${lit_html_o}>`,
lit_html_l = document,
lit_html_h = function () {
let t = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
return lit_html_l.createComment(t);
},
lit_html_r = t => null === t || "object" != typeof t && "function" != typeof t,
d = Array.isArray,
lit_html_u = t => {
var i;
return d(t) || "function" == typeof (null === (i = t) || void 0 === i ? void 0 : i[Symbol.iterator]);
},
c = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,
v = /-->/g,
lit_html_a = />/g,
f = />|[ \n\r](?:([^\s"'>=/]+)([ \n\r]*=[ \n\r]*(?:[^ \n\r"'`<>=]|("|')|))|$)/g,
_ = /'/g,
m = /"/g,
g = /^(?:script|style|textarea|title)$/i,
p = 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
};
},
$ = p(1),
y = p(2),
b = Symbol.for("lit-noChange"),
w = Symbol.for("lit-nothing"),
T = new WeakMap(),
x = (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 N(i.insertBefore(lit_html_h(), t), t, void 0, null != s ? s : {});
}
return l._$AI(t), l;
},
A = lit_html_l.createTreeWalker(lit_html_l, 129, null, !1),
C = (t, i) => {
const o = t.length - 1,
l = [];
let h,
r = 2 === i ? "" : "");
if (!Array.isArray(t) || !t.hasOwnProperty("raw")) throw Error("invalid template strings array");
return [void 0 !== lit_html_s ? lit_html_s.createHTML(u) : u, l];
};
class E {
constructor(_ref, n) {
let {
strings: t,
_$litType$: s
} = _ref;
let l;
this.parts = [];
let r = 0,
d = 0;
const u = t.length - 1,
c = this.parts,
[v, a] = C(t, s);
if (this.el = E.createElement(v, n), A.currentNode = this.el.content, 2 === s) {
const t = this.el.content,
i = t.firstChild;
i.remove(), t.append(...i.childNodes);
}
for (; null !== (l = A.nextNode()) && c.length < u;) {
if (1 === l.nodeType) {
if (l.hasAttributes()) {
const t = [];
for (const i of l.getAttributeNames()) if (i.endsWith("$lit$") || i.startsWith(lit_html_e)) {
const s = a[d++];
if (t.push(i), void 0 !== s) {
const t = l.getAttribute(s.toLowerCase() + "$lit$").split(lit_html_e),
i = /([.?@])?(.*)/.exec(s);
c.push({
type: 1,
index: r,
name: i[2],
strings: t,
ctor: "." === i[1] ? M : "?" === i[1] ? H : "@" === i[1] ? I : lit_html_S
});
} else c.push({
type: 6,
index: r
});
}
for (const i of t) l.removeAttribute(i);
}
if (g.test(l.tagName)) {
const t = l.textContent.split(lit_html_e),
s = t.length - 1;
if (s > 0) {
l.textContent = lit_html_i ? lit_html_i.emptyScript : "";
for (let i = 0; i < s; i++) l.append(t[i], lit_html_h()), A.nextNode(), c.push({
type: 2,
index: ++r
});
l.append(t[s], lit_html_h());
}
}
} else if (8 === l.nodeType) if (l.data === lit_html_o) c.push({
type: 2,
index: r
});else {
let t = -1;
for (; -1 !== (t = l.data.indexOf(lit_html_e, t + 1));) c.push({
type: 7,
index: r
}), t += lit_html_e.length - 1;
}
r++;
}
}
static createElement(t, i) {
const s = lit_html_l.createElement("template");
return s.innerHTML = t, s;
}
}
function P(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 === b) return i;
let d = void 0 !== e ? null === (o = s._$Cl) || void 0 === o ? void 0 : o[e] : s._$Cu;
const u = lit_html_r(i) ? void 0 : i._$litDirective$;
return (null == d ? void 0 : d.constructor) !== u && (null === (n = null == d ? void 0 : d._$AO) || void 0 === n || n.call(d, !1), void 0 === u ? d = void 0 : (d = new u(t), d._$AT(t, s, e)), void 0 !== e ? (null !== (l = (h = s)._$Cl) && void 0 !== l ? l : h._$Cl = [])[e] = d : s._$Cu = d), void 0 !== d && (i = P(t, d._$AS(t, i.values), d, e)), i;
}
class V {
constructor(t, i) {
this.v = [], this._$AN = void 0, this._$AD = t, this._$AM = i;
}
get parentNode() {
return this._$AM.parentNode;
}
get _$AU() {
return this._$AM._$AU;
}
p(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_l).importNode(s, !0);
A.currentNode = o;
let n = A.nextNode(),
h = 0,
r = 0,
d = e[0];
for (; void 0 !== d;) {
if (h === d.index) {
let i;
2 === d.type ? i = new N(n, n.nextSibling, this, t) : 1 === d.type ? i = new d.ctor(n, d.name, d.strings, this, t) : 6 === d.type && (i = new L(n, this, t)), this.v.push(i), d = e[++r];
}
h !== (null == d ? void 0 : d.index) && (n = A.nextNode(), h++);
}
return o;
}
m(t) {
let i = 0;
for (const s of this.v) void 0 !== s && (void 0 !== s.strings ? (s._$AI(t, s, i), i += s.strings.length - 2) : s._$AI(t[i])), i++;
}
}
class N {
constructor(t, i, s, e) {
var o;
this.type = 2, this._$AH = w, this._$AN = void 0, this._$AA = t, this._$AB = i, this._$AM = s, this.options = e, this._$Cg = 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._$Cg;
}
get parentNode() {
let t = this._$AA.parentNode;
const i = this._$AM;
return void 0 !== i && 11 === 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 = P(this, t, i), lit_html_r(t) ? t === w || null == t || "" === t ? (this._$AH !== w && this._$AR(), this._$AH = w) : t !== this._$AH && t !== b && this.$(t) : void 0 !== t._$litType$ ? this.T(t) : void 0 !== t.nodeType ? this.k(t) : lit_html_u(t) ? this.S(t) : this.$(t);
}
A(t) {
let i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._$AB;
return this._$AA.parentNode.insertBefore(t, i);
}
k(t) {
this._$AH !== t && (this._$AR(), this._$AH = this.A(t));
}
$(t) {
this._$AH !== w && lit_html_r(this._$AH) ? this._$AA.nextSibling.data = t : this.k(lit_html_l.createTextNode(t)), this._$AH = t;
}
T(t) {
var i;
const {
values: s,
_$litType$: e
} = t,
o = "number" == typeof e ? this._$AC(t) : (void 0 === e.el && (e.el = E.createElement(e.h, this.options)), e);
if ((null === (i = this._$AH) || void 0 === i ? void 0 : i._$AD) === o) this._$AH.m(s);else {
const t = new V(o, this),
i = t.p(this.options);
t.m(s), this.k(i), this._$AH = t;
}
}
_$AC(t) {
let i = T.get(t.strings);
return void 0 === i && T.set(t.strings, i = new E(t)), i;
}
S(t) {
d(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 N(this.A(lit_html_h()), this.A(lit_html_h()), 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._$Cg = t, null === (i = this._$AP) || void 0 === i || i.call(this, t));
}
}
class lit_html_S {
constructor(t, i, s, e, o) {
this.type = 1, this._$AH = w, 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 = w;
}
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 = P(this, t, i, 0), n = !lit_html_r(t) || t !== this._$AH && t !== b, n && (this._$AH = t);else {
const e = t;
let l, h;
for (t = o[0], l = 0; l < o.length - 1; l++) h = P(this, e[s + l], i, l), h === b && (h = this._$AH[l]), n || (n = !lit_html_r(h) || h !== this._$AH[l]), h === w ? t = w : t !== w && (t += (null != h ? h : "") + o[l + 1]), this._$AH[l] = h;
}
n && !e && this.C(t);
}
C(t) {
t === w ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, null != t ? t : "");
}
}
class M extends lit_html_S {
constructor() {
super(...arguments), this.type = 3;
}
C(t) {
this.element[this.name] = t === w ? void 0 : t;
}
}
const k = lit_html_i ? lit_html_i.emptyScript : "";
class H extends lit_html_S {
constructor() {
super(...arguments), this.type = 4;
}
C(t) {
t && t !== w ? this.element.setAttribute(this.name, k) : this.element.removeAttribute(this.name);
}
}
class I extends lit_html_S {
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 = P(this, t, i, 0)) && void 0 !== s ? s : w) === b) return;
const e = this._$AH,
o = t === w && e !== w || t.capture !== e.capture || t.once !== e.once || t.passive !== e.passive,
n = t !== w && (e === w || 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 L {
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) {
P(this, t);
}
}
const R = {
P: "$lit$",
L: lit_html_e,
V: lit_html_o,
I: 1,
N: C,
R: V,
D: lit_html_u,
j: P,
H: N,
O: lit_html_S,
F: H,
B: I,
W: M,
Z: L
},
z = window.litHtmlPolyfillSupport;
null == z || z(E, N), (null !== (lit_html_t = globalThis.litHtmlVersions) && void 0 !== lit_html_t ? lit_html_t : globalThis.litHtmlVersions = []).push("2.2.0");
;// 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 a{constructor(){super(...arguments),this.renderOptions={host:this},this._$Dt=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._$Dt=x(i,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this._$Dt)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this._$Dt)||void 0===t||t.setConnected(!1)}render(){return b}}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.2.0");
//# sourceMappingURL=lit-element.js.map
;// CONCATENATED MODULE: ./node_modules/lit/index.js
//# sourceMappingURL=index.js.map
;// CONCATENATED MODULE: ./src/headless/core.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
dayjs_min_default().extend((advancedFormat_default())); // Add Strophe Namespaces
Strophe.addNamespace('ACTIVITY', 'http://jabber.org/protocol/activity');
Strophe.addNamespace('CARBONS', 'urn:xmpp:carbons:2');
Strophe.addNamespace('CHATSTATES', 'http://jabber.org/protocol/chatstates');
Strophe.addNamespace('CSI', 'urn:xmpp:csi:0');
Strophe.addNamespace('DELAY', 'urn:xmpp:delay');
Strophe.addNamespace('EME', 'urn:xmpp:eme:0');
Strophe.addNamespace('FASTEN', 'urn:xmpp:fasten:0');
Strophe.addNamespace('FORWARD', 'urn:xmpp:forward:0');
Strophe.addNamespace('HINTS', 'urn:xmpp:hints');
Strophe.addNamespace('HTTPUPLOAD', 'urn:xmpp:http:upload:0');
Strophe.addNamespace('MAM', 'urn:xmpp:mam:2');
Strophe.addNamespace('MARKERS', 'urn:xmpp:chat-markers:0');
Strophe.addNamespace('MENTIONS', 'urn:xmpp:mmn:0');
Strophe.addNamespace('MESSAGE_CORRECT', 'urn:xmpp:message-correct:0');
Strophe.addNamespace('MODERATE', 'urn:xmpp:message-moderate:0');
Strophe.addNamespace('NICK', 'http://jabber.org/protocol/nick');
Strophe.addNamespace('OCCUPANTID', 'urn:xmpp:occupant-id:0');
Strophe.addNamespace('OMEMO', 'eu.siacs.conversations.axolotl');
Strophe.addNamespace('OUTOFBAND', 'jabber:x:oob');
Strophe.addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
Strophe.addNamespace('RAI', 'urn:xmpp:rai:0');
Strophe.addNamespace('RECEIPTS', 'urn:xmpp:receipts');
Strophe.addNamespace('REFERENCE', 'urn:xmpp:reference:0');
Strophe.addNamespace('REGISTER', 'jabber:iq:register');
Strophe.addNamespace('RETRACT', 'urn:xmpp:message-retract:0');
Strophe.addNamespace('ROSTERX', 'http://jabber.org/protocol/rosterx');
Strophe.addNamespace('RSM', 'http://jabber.org/protocol/rsm');
Strophe.addNamespace('SID', 'urn:xmpp:sid:0');
Strophe.addNamespace('SPOILER', 'urn:xmpp:spoiler:0');
Strophe.addNamespace('STANZAS', 'urn:ietf:params:xml:ns:xmpp-stanzas');
Strophe.addNamespace('STYLING', 'urn:xmpp:styling:0');
Strophe.addNamespace('VCARD', 'vcard-temp');
Strophe.addNamespace('VCARDUPDATE', 'vcard-temp:x:update');
Strophe.addNamespace('XFORM', 'jabber:x:data');
Strophe.addNamespace('XHTML', 'http://www.w3.org/1999/xhtml');
shared_converse.VERSION_NAME = "v9.1.1";
Object.assign(shared_converse, Events); // Make converse pluggable
pluggable.enable(shared_converse, '_converse', 'pluggable');
/**
* ### 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 core_api = shared_converse.api = {
connection: api,
settings: settings_api,
/**
* 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} - 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;
}
},
/**
* This grouping collects API functions related to the current logged in user.
*
* @namespace _converse.api.user
* @memberOf _converse.api
*/
user: {
settings: user_settings_api,
/**
* @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 {void}
*/
async login(jid, password) {
var _converse$connection, _api$settings$get;
let automatic = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
jid = jid || core_api.settings.get('jid');
if (!((_converse$connection = shared_converse.connection) !== null && _converse$connection !== void 0 && _converse$connection.jid) || jid && !utils_core.isSameDomain(shared_converse.connection.jid, jid)) {
await shared_converse.initConnection();
}
if ((_api$settings$get = core_api.settings.get("connection_options")) !== null && _api$settings$get !== void 0 && _api$settings$get.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 !== null && bosh_plugin !== void 0 && bosh_plugin.enabled()) {
if (await shared_converse.restoreBOSHSession()) {
return;
} else if (core_api.settings.get("authentication") === shared_converse.PREBIND && (!automatic || core_api.settings.get("auto_login"))) {
return shared_converse.startNewPreboundBOSHSession();
}
}
password = password || core_api.settings.get("password");
const credentials = jid && password ? {
jid,
password
} : null;
attemptNonPreboundSession(credentials, automatic);
},
/**
* Logs the user out of the current XMPP session.
* @method _converse.api.user.logout
* @example _converse.api.user.logout();
*/
async logout() {
/**
* Triggered before the user is logged out
* @event _converse#beforeLogout
*/
await core_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;
/**
* Triggered once the user has logged out.
* @event _converse#logout
*/
core_api.trigger('logout');
promise.resolve();
};
shared_converse.connection.setDisconnectionCause(shared_converse.LOGOUT, undefined, true);
if (shared_converse.connection !== undefined) {
core_api.listen.once('disconnected', () => complete());
shared_converse.connection.disconnect();
} else {
complete();
}
return 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;
});
}
},
/**
* 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 (lodash_es_isFunction(options)) {
handler = options;
options = {};
} else {
options = options || {};
}
shared_converse.connection.addHandler(handler, options.ns, name, options.type, options.id, options.from, options);
}
},
/**
* Wait until a promise is resolved or until the passed in function returns
* a truthy value.
* @method _converse.api.waitUntil
* @param {string|function} condition - The name of the promise to wait for,
* or a function which should eventually return a truthy value.
* @returns {Promise}
*/
waitUntil(condition) {
if (lodash_es_isFunction(condition)) {
return utils_core.waitUntil(condition);
} else {
const promise = shared_converse.promises[condition];
if (promise === undefined) {
return null;
}
return promise;
}
},
/**
* Allows you to send XML stanzas.
* @method _converse.api.send
* @param {XMLElement} stanza
* @return {void}
* @example
* const msg = converse.env.$msg({
* 'from': 'juliet@example.com/balcony',
* 'to': 'romeo@example.net',
* 'type':'chat'
* });
* _converse.api.send(msg);
*/
send(stanza) {
var _stanza;
if (!core_api.connection.connected()) {
headless_log.warn("Not sending stanza because we're not connected!");
headless_log.warn(Strophe.serialize(stanza));
return;
}
if (typeof stanza === 'string') {
stanza = utils_core.toStanza(stanza);
} else if ((_stanza = stanza) !== null && _stanza !== void 0 && _stanza.nodeTree) {
stanza = stanza.nodeTree;
}
if (stanza.tagName === 'iq') {
return core_api.sendIQ(stanza);
} else {
shared_converse.connection.send(stanza);
core_api.trigger('send', stanza);
}
},
/**
* Send an IQ stanza
* @method _converse.api.sendIQ
* @param {XMLElement} stanza
* @param {Integer} [timeout=_converse.STANZA_TIMEOUT]
* @param {Boolean} [reject=true] - Whether an error IQ should cause the promise
* to be rejected. If `false`, the promise will resolve instead of being rejected.
* @returns {Promise} A promise which resolves (or potentially rejected) once we
* receive a `result` or `error` stanza or once a timeout is reached.
* If the IQ stanza being sent is of type `result` or `error`, there's
* nothing to wait for, so an already resolved promise is returned.
*/
sendIQ(stanza) {
var _stanza2;
let timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : shared_converse.STANZA_TIMEOUT;
let reject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
let promise;
stanza = ((_stanza2 = stanza) === null || _stanza2 === void 0 ? void 0 : _stanza2.nodeTree) ?? stanza;
if (['get', 'set'].includes(stanza.getAttribute('type'))) {
timeout = timeout || shared_converse.STANZA_TIMEOUT;
if (reject) {
promise = new Promise((resolve, reject) => shared_converse.connection.sendIQ(stanza, resolve, reject, timeout));
promise.catch(e => {
if (e === null) {
throw new TimeoutError(`Timeout error after ${timeout}ms for the following IQ stanza: ${Strophe.serialize(stanza)}`);
}
});
} else {
promise = new Promise(resolve => shared_converse.connection.sendIQ(stanza, resolve, resolve, timeout));
}
} else {
shared_converse.connection.sendIQ(stanza);
promise = Promise.resolve();
}
core_api.trigger('send', stanza);
return promise;
}
};
shared_converse.shouldClearCache = () => !shared_converse.config.get('trusted') || core_api.settings.get('clear_cache_on_logout') || shared_converse.isTestEnv();
function clearSession() {
var _converse$session;
(_converse$session = shared_converse.session) === null || _converse$session === void 0 ? void 0 : _converse$session.destroy();
delete shared_converse.session;
shared_converse.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
});
}
shared_converse.initConnection = function () {
const api = shared_converse.api;
if (!api.settings.get('bosh_service_url')) {
if (api.settings.get("authentication") === shared_converse.PREBIND) {
throw new Error("authentication is set to 'prebind' but we don't have a BOSH connection");
}
}
const XMPPConnection = shared_converse.isTestEnv() ? MockConnection : 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 setUpXMLLogging() {
const lmap = {};
lmap[Strophe.LogLevel.DEBUG] = 'debug';
lmap[Strophe.LogLevel.INFO] = 'info';
lmap[Strophe.LogLevel.WARN] = 'warn';
lmap[Strophe.LogLevel.ERROR] = 'error';
lmap[Strophe.LogLevel.FATAL] = 'fatal';
Strophe.log = (level, msg) => headless_log.log(msg, lmap[level]);
Strophe.error = msg => headless_log.error(msg);
shared_converse.connection.xmlInput = body => headless_log.debug(body.outerHTML, 'color: darkgoldenrod');
shared_converse.connection.xmlOutput = body => headless_log.debug(body.outerHTML, 'color: darkcyan');
}
shared_converse.saveWindowState = function (ev) {
// XXX: eventually we should be able to just use
// document.visibilityState (when we drop support for older
// browsers).
let state;
const event_map = {
'focus': "visible",
'focusin': "visible",
'pageshow': "visible",
'blur': "hidden",
'focusout': "hidden",
'pagehide': "hidden"
};
ev = ev || document.createEvent('Events');
if (ev.type in event_map) {
state = event_map[ev.type];
} else {
state = document.hidden ? "hidden" : "visible";
}
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 => { ... });
*/
core_api.trigger('windowStateChanged', {
state
});
};
shared_converse.ConnectionFeedback = Model.extend({
defaults: {
'connection_status': Strophe.Status.DISCONNECTED,
'message': ''
},
initialize() {
this.on('change', () => core_api.trigger('connfeedback', shared_converse.connfeedback));
}
});
const core_converse = window.converse || {};
/**
* ### The Public API
*
* This namespace contains public API methods which are are
* accessible on the global `converse` object.
* They are public, because any JavaScript in the
* page can call them. Public methods therefore don’t expose any sensitive
* or closured data. To do that, you’ll need to create a plugin, which has
* access to the private API method.
*
* @global
* @namespace converse
*/
Object.assign(core_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) {
var _api$elements;
await cleanup(shared_converse);
setUnloadEvent();
initAppSettings(settings);
shared_converse.strict_plugin_dependencies = settings.strict_plugin_dependencies; // Needed by pluggable.js
headless_log.setLogLevel(core_api.settings.get("loglevel"));
if (core_api.settings.get("authentication") === shared_converse.ANONYMOUS) {
if (core_api.settings.get("auto_login") && !core_api.settings.get('jid')) {
throw new Error("Config Error: you need to provide the server's " + "domain via the 'jid' option when using anonymous " + "authentication with auto_login.");
}
}
shared_converse.router.route(/^converse\?loglevel=(debug|info|warn|error|fatal)$/, 'loglevel', l => headless_log.setLogLevel(l));
shared_converse.connfeedback = new shared_converse.ConnectionFeedback();
/* When reloading the page:
* For new sessions, we need to send out a presence stanza to notify
* the server/network that we're online.
* When re-attaching to an existing session we don't need to again send out a presence stanza,
* because it's as if "we never left" (see onConnectStatusChanged).
* https://github.com/conversejs/converse.js/issues/521
*/
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 = core_api.elements) === null || _api$elements === void 0 ? void 0 : _api$elements.register();
registerGlobalEventHandlers(shared_converse);
try {
!History.started && shared_converse.router.history.start();
} catch (e) {
headless_log.error(e);
}
const plugins = shared_converse.pluggable.plugins;
if (core_api.settings.get("auto_login") || core_api.settings.get("keepalive") && lodash_es_invoke(plugins['converse-bosh'], 'enabled')) {
await core_api.user.login(null, null, true);
}
/**
* Triggered once converse.initialize has finished.
* @event _converse#initialized
*/
core_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 {function} converse.env.$build - Creates a Strophe.Builder, for creating stanza objects.
* @property {function} converse.env.$iq - Creates a Strophe.Builder with an element as the root.
* @property {function} converse.env.$msg - Creates a Strophe.Builder with an element as the root.
* @property {function} converse.env.$pres - Creates a Strophe.Builder with an 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: Strophe,
URI: (URI_default()),
dayjs: (dayjs_min_default()),
html: $,
log: headless_log,
sizzle: (sizzle_default()),
sprintf: sprintf.sprintf,
u: utils_core
}
});
;// CONCATENATED MODULE: ./src/headless/shared/actions.js
const actions_u = core_converse.env.utils;
function rejectMessage(stanza, text) {
// Reject an incoming message by replying with an error message of type "cancel".
core_api.send($msg({
'to': stanza.getAttribute('from'),
'type': 'error',
'id': stanza.getAttribute('id')
}).c('error', {
'type': 'cancel'
}).c('not-allowed', {
xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
}).up().c('text', {
xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
}).t(text));
headless_log.warn(`Rejecting message stanza with the following reason: ${text}`);
headless_log.warn(stanza);
}
/**
* 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': Strophe.NS.MARKERS,
'id': id
});
core_api.send(stanza);
}
;// CONCATENATED MODULE: ./src/headless/utils/url.js
const {
u: url_u
} = core_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) {
headless_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 = core_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 = core_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 = core_api.settings.get(setting);
if (!Array.isArray(allowed_domains)) {
return true;
}
try {
return isDomainWhitelisted(allowed_domains, url);
} catch (error) {
headless_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 = core_api.settings.get('image_urls_regex');
return (regex === null || regex === void 0 ? void 0 : 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
} = Strophe;
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 { XMLElement } stanza - The message stanza
* @returns { Object }
*/
function getStanzaIDs(stanza, original_stanza) {
const attrs = {}; // Store generic stanza ids
const sids = sizzle_default()(`stanza-id[xmlns="${Strophe.NS.SID}"]`, stanza);
const sid_attrs = sids.reduce((acc, s) => {
acc[`stanza_id ${s.getAttribute('by')}`] = s.getAttribute('id');
return acc;
}, {});
Object.assign(attrs, sid_attrs); // Store the archive id
const result = sizzle_default()(`message > result[xmlns="${Strophe.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="${Strophe.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="${Strophe.NS.EME}"]`, stanza).pop();
const namespace = eme_tag === null || eme_tag === void 0 ? void 0 : eme_tag.getAttribute('namespace');
const attrs = {};
if (namespace) {
attrs.is_encrypted = true;
attrs.encryption_namespace = namespace;
} else if (sizzle_default()(`encrypted[xmlns="${Strophe.NS.OMEMO}"]`, stanza).pop()) {
attrs.is_encrypted = true;
attrs.encryption_namespace = Strophe.NS.OMEMO;
}
return attrs;
}
/**
* @private
* @param { XMLElement } stanza - The message stanza
* @param { XMLElement } original_stanza - The original stanza, that contains the
* message stanza, if it was contained, otherwise it's the message stanza itself.
* @returns { Object }
*/
function getRetractionAttributes(stanza, original_stanza) {
const fastening = sizzle_default()(`> apply-to[xmlns="${Strophe.NS.FASTEN}"]`, stanza).pop();
if (fastening) {
const applies_to_id = fastening.getAttribute('id');
const retracted = sizzle_default()(`> retract[xmlns="${Strophe.NS.RETRACT}"]`, fastening).pop();
if (retracted) {
const delay = sizzle_default()(`delay[xmlns="${Strophe.NS.DELAY}"]`, original_stanza).pop();
const time = delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString();
return {
'editable': false,
'retracted': time,
'retracted_id': applies_to_id
};
}
} else {
const tombstone = sizzle_default()(`> retracted[xmlns="${Strophe.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="${Strophe.NS.MESSAGE_CORRECT}"]`, stanza).pop();
if (el) {
const replace_id = el.getAttribute('id');
if (replace_id) {
const delay = sizzle_default()(`delay[xmlns="${Strophe.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="${Strophe.NS.FASTEN}"]`, stanza).pop();
if (fastening) {
const applies_to_id = fastening.getAttribute('id');
const meta = sizzle_default()(`> meta[xmlns="${Strophe.NS.XHTML}"]`, fastening);
if (meta.length) {
const msg_limit = core_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) {
headless_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="${Strophe.NS.SPOILER}"]`, stanza).pop();
return {
'is_spoiler': !!spoiler,
'spoiler_hint': spoiler === null || spoiler === void 0 ? void 0 : spoiler.textContent
};
}
function getOutOfBandAttributes(stanza) {
const xform = sizzle_default()(`x[xmlns="${Strophe.NS.OUTOFBAND}"]`, stanza).pop();
if (xform) {
var _xform$querySelector, _xform$querySelector2;
return {
'oob_url': (_xform$querySelector = xform.querySelector('url')) === null || _xform$querySelector === void 0 ? void 0 : _xform$querySelector.textContent,
'oob_desc': (_xform$querySelector2 = xform.querySelector('desc')) === null || _xform$querySelector2 === void 0 ? void 0 : _xform$querySelector2.textContent
};
}
return {};
}
/**
* Returns the human readable error message contained in a `groupchat` message stanza of type `error`.
* @private
* @param { XMLElement } stanza - The message stanza
*/
function getErrorAttributes(stanza) {
if (stanza.getAttribute('type') === 'error') {
const error = stanza.querySelector('error');
const text = sizzle_default()(`text[xmlns="${Strophe.NS.STANZAS}"]`, error).pop();
return {
'is_error': true,
'error_text': text === null || text === void 0 ? void 0 : text.textContent,
'error_type': error.getAttribute('type'),
'error_condition': error.firstElementChild.nodeName
};
}
return {};
}
function getReferences(stanza) {
return sizzle_default()(`reference[xmlns="${Strophe.NS.REFERENCE}"]`, stanza).map(ref => {
var _stanza$querySelector;
const anchor = ref.getAttribute('anchor');
const text = (_stanza$querySelector = stanza.querySelector(anchor ? `#${anchor}` : 'body')) === null || _stanza$querySelector === void 0 ? void 0 : _stanza$querySelector.textContent;
if (!text) {
headless_log.warn(`Could not find referenced text for ${ref}`);
return null;
}
const begin = ref.getAttribute('begin');
const end = ref.getAttribute('end');
return {
'begin': begin,
'end': end,
'type': ref.getAttribute('type'),
'value': text.slice(begin, end),
'uri': ref.getAttribute('uri')
};
}).filter(r => r);
}
function getReceiptId(stanza) {
const receipt = sizzle_default()(`received[xmlns="${Strophe.NS.RECEIPTS}"]`, stanza).pop();
return receipt === null || receipt === void 0 ? void 0 : receipt.getAttribute('id');
}
/**
* Determines whether the passed in stanza is a XEP-0280 Carbon
* @private
* @param { XMLElement } stanza - The message stanza
* @returns { Boolean }
*/
function isCarbon(stanza) {
const xmlns = Strophe.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 { XMLElement } stanza - The message stanza
*/
function getChatState(stanza) {
var _sizzle$pop;
return (_sizzle$pop = sizzle_default()(`
composing[xmlns="${NS.CHATSTATES}"],
paused[xmlns="${NS.CHATSTATES}"],
inactive[xmlns="${NS.CHATSTATES}"],
active[xmlns="${NS.CHATSTATES}"],
gone[xmlns="${NS.CHATSTATES}"]`, stanza).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.nodeName;
}
function isValidReceiptRequest(stanza, attrs) {
return attrs.sender !== 'me' && !attrs.is_carbon && !attrs.is_archived && sizzle_default()(`request[xmlns="${Strophe.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 { XMLElement } stanza
*/
function throwErrorIfInvalidForward(stanza) {
const bare_forward = sizzle_default()(`message > forwarded[xmlns="${Strophe.NS.FORWARD}"]`, stanza).length;
if (bare_forward) {
rejectMessage(stanza, 'Forwarded messages not part of an encapsulating protocol are not supported');
const from_jid = stanza.getAttribute('from');
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 { XMLElement } 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="${Strophe.NS.MARKERS}"],
displayed[xmlns="${Strophe.NS.MARKERS}"],
received[xmlns="${Strophe.NS.MARKERS}"]`, stanza).pop();
}
function isHeadline(stanza) {
return stanza.getAttribute('type') === 'headline';
}
function isServerMessage(stanza) {
if (sizzle_default()(`mentions[xmlns="${Strophe.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 { XMLElement } stanza - The message stanza
* @returns { Boolean }
*/
function isArchived(original_stanza) {
return !!sizzle_default()(`message > result[xmlns="${Strophe.NS.MAM}"]`, original_stanza).pop();
}
/**
* Returns an object containing all attribute names and values for a particular element.
* @method getAttributes
* @param { XMLElement } stanza
* @returns { Object }
*/
function getAttributes(stanza) {
return stanza.getAttributeNames().reduce((acc, name) => {
acc[name] = Strophe.xmlunescape(stanza.getAttribute(name));
return acc;
}, {});
}
;// CONCATENATED MODULE: ./src/headless/plugins/adhoc.js
const {
Strophe: adhoc_Strophe
} = core_converse.env;
let adhoc_converse, adhoc_api;
adhoc_Strophe.addNamespace('ADHOC', 'http://jabber.org/protocol/commands');
function parseForCommands(stanza) {
const items = sizzle_default()(`query[xmlns="${adhoc_Strophe.NS.DISCO_ITEMS}"][node="${adhoc_Strophe.NS.ADHOC}"] item`, stanza);
return items.map(getAttributes);
}
const adhoc_adhoc_api = {
/**
* The XEP-0050 Ad-Hoc Commands API
*
* This API lets you discover ad-hoc commands available for an entity in the XMPP network.
*
* @namespace api.adhoc
* @memberOf api
*/
adhoc: {
/**
* @method api.adhoc.getCommands
* @param { String } to_jid
*/
async getCommands(to_jid) {
let commands = [];
try {
commands = parseForCommands(await adhoc_api.disco.items(to_jid, adhoc_Strophe.NS.ADHOC));
} catch (e) {
if (e === null) {
headless_log.error(`Error: timeout while fetching ad-hoc commands for ${to_jid}`);
} else {
headless_log.error(`Error while fetching ad-hoc commands for ${to_jid}`);
headless_log.error(e);
}
}
return commands;
}
}
};
core_converse.plugins.add('converse-adhoc', {
dependencies: ["converse-disco"],
initialize() {
adhoc_converse = this._converse;
adhoc_api = adhoc_converse.api;
Object.assign(adhoc_api, adhoc_adhoc_api);
}
});
/* harmony default export */ const adhoc = ((/* unused pure expression or super */ null && (adhoc_adhoc_api)));
;// CONCATENATED MODULE: ./src/headless/plugins/chat/model-with-contact.js
const ModelWithContact = Model.extend({
initialize() {
this.rosterContactAdded = getOpenPromise();
},
async setRosterContact(jid) {
const contact = await core_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);
// EXTERNAL MODULE: ./node_modules/filesize/lib/filesize.min.js
var filesize_min = __webpack_require__(6755);
var filesize_min_default = /*#__PURE__*/__webpack_require__.n(filesize_min);
;// 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
} = core_converse.env;
function pruneHistory(model) {
const max_history = core_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 => { ... });
*/
core_api.trigger('historyPruned', model);
}
}
}
}
/**
* Given an array of {@link MediaURLMetadata} objects and text, return an
* array of {@link MediaURL} objects.
* @param { Array } arr
* @param { String } text
* @returns{ Array }
*/
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);
}
const debouncedPruneHistory = lodash_es_debounce(pruneHistory, 500);
;// CONCATENATED MODULE: ./src/headless/plugins/chat/parsers.js
const {
Strophe: parsers_Strophe,
sizzle: parsers_sizzle
} = core_converse.env;
/**
* Parses a passed in message stanza and returns an object of attributes.
* @method st#parseMessage
* @param { XMLElement } stanza - The message stanza
* @param { _converse } _converse
* @returns { (MessageAttributes|Error) }
*/
async function parseMessage(stanza) {
var _stanza$querySelector, _stanza$querySelector2, _contact, _contact$attributes, _stanza$querySelector3, _stanza$querySelector4;
throwErrorIfInvalidForward(stanza);
let to_jid = stanza.getAttribute('to');
const to_resource = parsers_Strophe.getResourceFromJid(to_jid);
if (core_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 core_api.contacts.get(contact_jid);
if (contact === undefined && !core_api.settings.get('allow_non_roster_messaging')) {
headless_log.error(stanza);
return new StanzaParseError(`Blocking messaging with a JID not in our roster because allow_non_roster_messaging is false.`, stanza);
}
}
/**
* @typedef { Object } MessageAttributes
* The object which {@link parseMessage} returns
* @property { ('me'|'them') } sender - Whether the message was sent by the current user or someone else
* @property { Array