/* @license The following license applies to all parts of this software except as documented below. Copyright (c) 2019, Twilio, inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Twilio nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software includes javascript-state-machine under the following license. Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE This software includes loglevel under the following license. Copyright (c) 2013 Tim Perry Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software includes q under the following license. Copyright 2009–2014 Kristopher Michael Kowal. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software includes platform.js under the following license. Copyright 2014 Benjamin Tan Copyright 2011-2015 John-David Dalton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ this.Twilio = this.Twilio || {}; this.Twilio.Conversations = (function (exports) { 'use strict'; var global = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getAugmentedNamespace(n) { if (n.__esModule) return n; var a = Object.defineProperty({}, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } var check = function (it) { return it && it.Math == Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global$D = // eslint-disable-next-line es/no-global-this -- safe check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || // eslint-disable-next-line no-restricted-globals -- safe check(typeof self == 'object' && self) || check(typeof commonjsGlobal == 'object' && commonjsGlobal) || // eslint-disable-next-line no-new-func -- fallback (function () { return this; })() || Function('return this')(); var objectGetOwnPropertyDescriptor = {}; var fails$B = function (exec) { try { return !!exec(); } catch (error) { return true; } }; var fails$A = fails$B; // Detect IE8's incomplete defineProperty implementation var descriptors = !fails$A(function () { // eslint-disable-next-line es/no-object-defineproperty -- required for testing return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7; }); var objectPropertyIsEnumerable = {}; var $propertyIsEnumerable$1 = {}.propertyIsEnumerable; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var getOwnPropertyDescriptor$4 = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor$4 && !$propertyIsEnumerable$1.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor$4(this, V); return !!descriptor && descriptor.enumerable; } : $propertyIsEnumerable$1; var createPropertyDescriptor$7 = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var toString$e = {}.toString; var classofRaw$1 = function (it) { return toString$e.call(it).slice(8, -1); }; var fails$z = fails$B; var classof$b = classofRaw$1; var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings var indexedObject = fails$z(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins -- safe return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classof$b(it) == 'String' ? split.call(it, '') : Object(it); } : Object; // `RequireObjectCoercible` abstract operation // https://tc39.es/ecma262/#sec-requireobjectcoercible var requireObjectCoercible$a = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; // toObject with fallback for non-array-like ES3 strings var IndexedObject$4 = indexedObject; var requireObjectCoercible$9 = requireObjectCoercible$a; var toIndexedObject$c = function (it) { return IndexedObject$4(requireObjectCoercible$9(it)); }; var isObject$p = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; var global$C = global$D; var aFunction$a = function (variable) { return typeof variable == 'function' ? variable : undefined; }; var getBuiltIn$a = function (namespace, method) { return arguments.length < 2 ? aFunction$a(global$C[namespace]) : global$C[namespace] && global$C[namespace][method]; }; var getBuiltIn$9 = getBuiltIn$a; var engineUserAgent = getBuiltIn$9('navigator', 'userAgent') || ''; var global$B = global$D; var userAgent$5 = engineUserAgent; var process$3 = global$B.process; var Deno = global$B.Deno; var versions = process$3 && process$3.versions || Deno && Deno.version; var v8 = versions && versions.v8; var match, version$2; if (v8) { match = v8.split('.'); version$2 = match[0] < 4 ? 1 : match[0] + match[1]; } else if (userAgent$5) { match = userAgent$5.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = userAgent$5.match(/Chrome\/(\d+)/); if (match) version$2 = match[1]; } } var engineV8Version = version$2 && +version$2; /* eslint-disable es/no-symbol -- required for testing */ var V8_VERSION$3 = engineV8Version; var fails$y = fails$B; // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing var nativeSymbol$1 = !!Object.getOwnPropertySymbols && !fails$y(function () { var symbol = Symbol(); // Chrome 38 Symbol has incorrect toString conversion // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances return !String(symbol) || !(Object(symbol) instanceof Symbol) || // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances !Symbol.sham && V8_VERSION$3 && V8_VERSION$3 < 41; }); /* eslint-disable es/no-symbol -- required for testing */ var NATIVE_SYMBOL$2 = nativeSymbol$1; var useSymbolAsUid = NATIVE_SYMBOL$2 && !Symbol.sham && typeof Symbol.iterator == 'symbol'; var getBuiltIn$8 = getBuiltIn$a; var USE_SYMBOL_AS_UID$1 = useSymbolAsUid; var isSymbol$6 = USE_SYMBOL_AS_UID$1 ? function (it) { return typeof it == 'symbol'; } : function (it) { var $Symbol = getBuiltIn$8('Symbol'); return typeof $Symbol == 'function' && Object(it) instanceof $Symbol; }; var isObject$o = isObject$p; // `OrdinaryToPrimitive` abstract operation // https://tc39.es/ecma262/#sec-ordinarytoprimitive var ordinaryToPrimitive$1 = function (input, pref) { var fn, val; if (pref === 'string' && typeof (fn = input.toString) == 'function' && !isObject$o(val = fn.call(input))) return val; if (typeof (fn = input.valueOf) == 'function' && !isObject$o(val = fn.call(input))) return val; if (pref !== 'string' && typeof (fn = input.toString) == 'function' && !isObject$o(val = fn.call(input))) return val; throw TypeError("Can't convert object to primitive value"); }; var shared$5 = {exports: {}}; var isPure = false; var global$A = global$D; var setGlobal$3 = function (key, value) { try { // eslint-disable-next-line es/no-object-defineproperty -- safe Object.defineProperty(global$A, key, { value: value, configurable: true, writable: true }); } catch (error) { global$A[key] = value; } return value; }; var global$z = global$D; var setGlobal$2 = setGlobal$3; var SHARED = '__core-js_shared__'; var store$3 = global$z[SHARED] || setGlobal$2(SHARED, {}); var sharedStore = store$3; var store$2 = sharedStore; (shared$5.exports = function (key, value) { return store$2[key] || (store$2[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.17.3', mode: 'global', copyright: '© 2021 Denis Pushkarev (zloirock.ru)' }); var requireObjectCoercible$8 = requireObjectCoercible$a; // `ToObject` abstract operation // https://tc39.es/ecma262/#sec-toobject var toObject$g = function (argument) { return Object(requireObjectCoercible$8(argument)); }; var toObject$f = toObject$g; var hasOwnProperty = {}.hasOwnProperty; var has$g = Object.hasOwn || function hasOwn(it, key) { return hasOwnProperty.call(toObject$f(it), key); }; var id$1 = 0; var postfix = Math.random(); var uid$5 = function (key) { return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id$1 + postfix).toString(36); }; var global$y = global$D; var shared$4 = shared$5.exports; var has$f = has$g; var uid$4 = uid$5; var NATIVE_SYMBOL$1 = nativeSymbol$1; var USE_SYMBOL_AS_UID = useSymbolAsUid; var WellKnownSymbolsStore$1 = shared$4('wks'); var Symbol$1 = global$y.Symbol; var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid$4; var wellKnownSymbol$s = function (name) { if (!has$f(WellKnownSymbolsStore$1, name) || !(NATIVE_SYMBOL$1 || typeof WellKnownSymbolsStore$1[name] == 'string')) { if (NATIVE_SYMBOL$1 && has$f(Symbol$1, name)) { WellKnownSymbolsStore$1[name] = Symbol$1[name]; } else { WellKnownSymbolsStore$1[name] = createWellKnownSymbol('Symbol.' + name); } } return WellKnownSymbolsStore$1[name]; }; var isObject$n = isObject$p; var isSymbol$5 = isSymbol$6; var ordinaryToPrimitive = ordinaryToPrimitive$1; var wellKnownSymbol$r = wellKnownSymbol$s; var TO_PRIMITIVE$1 = wellKnownSymbol$r('toPrimitive'); // `ToPrimitive` abstract operation // https://tc39.es/ecma262/#sec-toprimitive var toPrimitive$2 = function (input, pref) { if (!isObject$n(input) || isSymbol$5(input)) return input; var exoticToPrim = input[TO_PRIMITIVE$1]; var result; if (exoticToPrim !== undefined) { if (pref === undefined) pref = 'default'; result = exoticToPrim.call(input, pref); if (!isObject$n(result) || isSymbol$5(result)) return result; throw TypeError("Can't convert object to primitive value"); } if (pref === undefined) pref = 'number'; return ordinaryToPrimitive(input, pref); }; var toPrimitive$1 = toPrimitive$2; var isSymbol$4 = isSymbol$6; // `ToPropertyKey` abstract operation // https://tc39.es/ecma262/#sec-topropertykey var toPropertyKey$5 = function (argument) { var key = toPrimitive$1(argument, 'string'); return isSymbol$4(key) ? key : String(key); }; var global$x = global$D; var isObject$m = isObject$p; var document$3 = global$x.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject$m(document$3) && isObject$m(document$3.createElement); var documentCreateElement$2 = function (it) { return EXISTS ? document$3.createElement(it) : {}; }; var DESCRIPTORS$i = descriptors; var fails$x = fails$B; var createElement$1 = documentCreateElement$2; // Thank's IE8 for his funny defineProperty var ie8DomDefine = !DESCRIPTORS$i && !fails$x(function () { // eslint-disable-next-line es/no-object-defineproperty -- requied for testing return Object.defineProperty(createElement$1('div'), 'a', { get: function () { return 7; } }).a != 7; }); var DESCRIPTORS$h = descriptors; var propertyIsEnumerableModule$2 = objectPropertyIsEnumerable; var createPropertyDescriptor$6 = createPropertyDescriptor$7; var toIndexedObject$b = toIndexedObject$c; var toPropertyKey$4 = toPropertyKey$5; var has$e = has$g; var IE8_DOM_DEFINE$1 = ie8DomDefine; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var $getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor objectGetOwnPropertyDescriptor.f = DESCRIPTORS$h ? $getOwnPropertyDescriptor$1 : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject$b(O); P = toPropertyKey$4(P); if (IE8_DOM_DEFINE$1) try { return $getOwnPropertyDescriptor$1(O, P); } catch (error) { /* empty */ } if (has$e(O, P)) return createPropertyDescriptor$6(!propertyIsEnumerableModule$2.f.call(O, P), O[P]); }; var objectDefineProperty = {}; var isObject$l = isObject$p; var anObject$k = function (it) { if (!isObject$l(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; var DESCRIPTORS$g = descriptors; var IE8_DOM_DEFINE = ie8DomDefine; var anObject$j = anObject$k; var toPropertyKey$3 = toPropertyKey$5; // eslint-disable-next-line es/no-object-defineproperty -- safe var $defineProperty$1 = Object.defineProperty; // `Object.defineProperty` method // https://tc39.es/ecma262/#sec-object.defineproperty objectDefineProperty.f = DESCRIPTORS$g ? $defineProperty$1 : function defineProperty(O, P, Attributes) { anObject$j(O); P = toPropertyKey$3(P); anObject$j(Attributes); if (IE8_DOM_DEFINE) try { return $defineProperty$1(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var DESCRIPTORS$f = descriptors; var definePropertyModule$7 = objectDefineProperty; var createPropertyDescriptor$5 = createPropertyDescriptor$7; var createNonEnumerableProperty$c = DESCRIPTORS$f ? function (object, key, value) { return definePropertyModule$7.f(object, key, createPropertyDescriptor$5(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var redefine$d = {exports: {}}; var store$1 = sharedStore; var functionToString = Function.toString; // this helper broken in `[email protected]`, so we can't use `shared` helper if (typeof store$1.inspectSource != 'function') { store$1.inspectSource = function (it) { return functionToString.call(it); }; } var inspectSource$3 = store$1.inspectSource; var global$w = global$D; var inspectSource$2 = inspectSource$3; var WeakMap$1 = global$w.WeakMap; var nativeWeakMap = typeof WeakMap$1 === 'function' && /native code/.test(inspectSource$2(WeakMap$1)); var shared$3 = shared$5.exports; var uid$3 = uid$5; var keys$3 = shared$3('keys'); var sharedKey$4 = function (key) { return keys$3[key] || (keys$3[key] = uid$3(key)); }; var hiddenKeys$6 = {}; var NATIVE_WEAK_MAP = nativeWeakMap; var global$v = global$D; var isObject$k = isObject$p; var createNonEnumerableProperty$b = createNonEnumerableProperty$c; var objectHas = has$g; var shared$2 = sharedStore; var sharedKey$3 = sharedKey$4; var hiddenKeys$5 = hiddenKeys$6; var OBJECT_ALREADY_INITIALIZED = 'Object already initialized'; var WeakMap = global$v.WeakMap; var set$2, get$2, has$d; var enforce = function (it) { return has$d(it) ? get$2(it) : set$2(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject$k(it) || (state = get$2(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (NATIVE_WEAK_MAP || shared$2.state) { var store = shared$2.state || (shared$2.state = new WeakMap()); var wmget = store.get; var wmhas = store.has; var wmset = store.set; set$2 = function (it, metadata) { if (wmhas.call(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); metadata.facade = it; wmset.call(store, it, metadata); return metadata; }; get$2 = function (it) { return wmget.call(store, it) || {}; }; has$d = function (it) { return wmhas.call(store, it); }; } else { var STATE = sharedKey$3('state'); hiddenKeys$5[STATE] = true; set$2 = function (it, metadata) { if (objectHas(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); metadata.facade = it; createNonEnumerableProperty$b(it, STATE, metadata); return metadata; }; get$2 = function (it) { return objectHas(it, STATE) ? it[STATE] : {}; }; has$d = function (it) { return objectHas(it, STATE); }; } var internalState = { set: set$2, get: get$2, has: has$d, enforce: enforce, getterFor: getterFor }; var global$u = global$D; var createNonEnumerableProperty$a = createNonEnumerableProperty$c; var has$c = has$g; var setGlobal$1 = setGlobal$3; var inspectSource$1 = inspectSource$3; var InternalStateModule$9 = internalState; var getInternalState$7 = InternalStateModule$9.get; var enforceInternalState = InternalStateModule$9.enforce; var TEMPLATE = String(String).split('String'); (redefine$d.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; var state; if (typeof value == 'function') { if (typeof key == 'string' && !has$c(value, 'name')) { createNonEnumerableProperty$a(value, 'name', key); } state = enforceInternalState(value); if (!state.source) { state.source = TEMPLATE.join(typeof key == 'string' ? key : ''); } } if (O === global$u) { if (simple) O[key] = value; else setGlobal$1(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value; else createNonEnumerableProperty$a(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState$7(this).source || inspectSource$1(this); }); var objectGetOwnPropertyNames = {}; var ceil = Math.ceil; var floor$7 = Math.floor; // `ToInteger` abstract operation // https://tc39.es/ecma262/#sec-tointeger var toInteger$a = function (argument) { return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor$7 : ceil)(argument); }; var toInteger$9 = toInteger$a; var min$7 = Math.min; // `ToLength` abstract operation // https://tc39.es/ecma262/#sec-tolength var toLength$o = function (argument) { return argument > 0 ? min$7(toInteger$9(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; var toInteger$8 = toInteger$a; var max$3 = Math.max; var min$6 = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). var toAbsoluteIndex$6 = function (index, length) { var integer = toInteger$8(index); return integer < 0 ? max$3(integer + length, 0) : min$6(integer, length); }; var toIndexedObject$a = toIndexedObject$c; var toLength$n = toLength$o; var toAbsoluteIndex$5 = toAbsoluteIndex$6; // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod$5 = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject$a($this); var length = toLength$n(O.length); var index = toAbsoluteIndex$5(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare -- NaN check if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare -- NaN check if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; var arrayIncludes = { // `Array.prototype.includes` method // https://tc39.es/ecma262/#sec-array.prototype.includes includes: createMethod$5(true), // `Array.prototype.indexOf` method // https://tc39.es/ecma262/#sec-array.prototype.indexof indexOf: createMethod$5(false) }; var has$b = has$g; var toIndexedObject$9 = toIndexedObject$c; var indexOf = arrayIncludes.indexOf; var hiddenKeys$4 = hiddenKeys$6; var objectKeysInternal = function (object, names) { var O = toIndexedObject$9(object); var i = 0; var result = []; var key; for (key in O) !has$b(hiddenKeys$4, key) && has$b(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has$b(O, key = names[i++])) { ~indexOf(result, key) || result.push(key); } return result; }; // IE8- don't enum bug keys var enumBugKeys$3 = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var internalObjectKeys$1 = objectKeysInternal; var enumBugKeys$2 = enumBugKeys$3; var hiddenKeys$3 = enumBugKeys$2.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.es/ecma262/#sec-object.getownpropertynames // eslint-disable-next-line es/no-object-getownpropertynames -- safe objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return internalObjectKeys$1(O, hiddenKeys$3); }; var objectGetOwnPropertySymbols = {}; // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols; var getBuiltIn$7 = getBuiltIn$a; var getOwnPropertyNamesModule$2 = objectGetOwnPropertyNames; var getOwnPropertySymbolsModule$2 = objectGetOwnPropertySymbols; var anObject$i = anObject$k; // all object keys, includes non-enumerable and symbols var ownKeys$9 = getBuiltIn$7('Reflect', 'ownKeys') || function ownKeys(it) { var keys = getOwnPropertyNamesModule$2.f(anObject$i(it)); var getOwnPropertySymbols = getOwnPropertySymbolsModule$2.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; var has$a = has$g; var ownKeys$8 = ownKeys$9; var getOwnPropertyDescriptorModule$3 = objectGetOwnPropertyDescriptor; var definePropertyModule$6 = objectDefineProperty; var copyConstructorProperties$2 = function (target, source) { var keys = ownKeys$8(source); var defineProperty = definePropertyModule$6.f; var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule$3.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!has$a(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } }; var fails$w = fails$B; var replacement = /#|\.prototype\./; var isForced$4 = function (feature, detection) { var value = data[normalize(feature)]; return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails$w(detection) : !!detection; }; var normalize = isForced$4.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced$4.data = {}; var NATIVE = isForced$4.NATIVE = 'N'; var POLYFILL = isForced$4.POLYFILL = 'P'; var isForced_1 = isForced$4; var global$t = global$D; var getOwnPropertyDescriptor$3 = objectGetOwnPropertyDescriptor.f; var createNonEnumerableProperty$9 = createNonEnumerableProperty$c; var redefine$c = redefine$d.exports; var setGlobal = setGlobal$3; var copyConstructorProperties$1 = copyConstructorProperties$2; var isForced$3 = isForced_1; /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ var _export = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global$t; } else if (STATIC) { target = global$t[TARGET] || setGlobal(TARGET, {}); } else { target = (global$t[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor$3(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced$3(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties$1(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty$9(sourceProperty, 'sham', true); } // extend global redefine$c(target, key, sourceProperty, options); } }; var defineProperty$a = objectDefineProperty.f; var has$9 = has$g; var wellKnownSymbol$q = wellKnownSymbol$s; var TO_STRING_TAG$4 = wellKnownSymbol$q('toStringTag'); var setToStringTag$9 = function (it, TAG, STATIC) { if (it && !has$9(it = STATIC ? it : it.prototype, TO_STRING_TAG$4)) { defineProperty$a(it, TO_STRING_TAG$4, { configurable: true, value: TAG }); } }; var $$x = _export; var global$s = global$D; var setToStringTag$8 = setToStringTag$9; $$x({ global: true }, { Reflect: {} }); // Reflect[@@toStringTag] property // https://tc39.es/ecma262/#sec-reflect-@@tostringtag setToStringTag$8(global$s.Reflect, 'Reflect', true); var aFunction$9 = function (it) { if (typeof it != 'function') { throw TypeError(String(it) + ' is not a function'); } return it; }; var internalObjectKeys = objectKeysInternal; var enumBugKeys$1 = enumBugKeys$3; // `Object.keys` method // https://tc39.es/ecma262/#sec-object.keys // eslint-disable-next-line es/no-object-keys -- safe var objectKeys$4 = Object.keys || function keys(O) { return internalObjectKeys(O, enumBugKeys$1); }; var DESCRIPTORS$e = descriptors; var definePropertyModule$5 = objectDefineProperty; var anObject$h = anObject$k; var objectKeys$3 = objectKeys$4; // `Object.defineProperties` method // https://tc39.es/ecma262/#sec-object.defineproperties // eslint-disable-next-line es/no-object-defineproperties -- safe var objectDefineProperties = DESCRIPTORS$e ? Object.defineProperties : function defineProperties(O, Properties) { anObject$h(O); var keys = objectKeys$3(Properties); var length = keys.length; var index = 0; var key; while (length > index) definePropertyModule$5.f(O, key = keys[index++], Properties[key]); return O; }; var getBuiltIn$6 = getBuiltIn$a; var html$2 = getBuiltIn$6('document', 'documentElement'); /* global ActiveXObject -- old IE, WSH */ var anObject$g = anObject$k; var defineProperties$1 = objectDefineProperties; var enumBugKeys = enumBugKeys$3; var hiddenKeys$2 = hiddenKeys$6; var html$1 = html$2; var documentCreateElement$1 = documentCreateElement$2; var sharedKey$2 = sharedKey$4; var GT = '>'; var LT = '<'; var PROTOTYPE$2 = 'prototype'; var SCRIPT = 'script'; var IE_PROTO$1 = sharedKey$2('IE_PROTO'); var EmptyConstructor = function () { /* empty */ }; var scriptTag = function (content) { return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; }; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype var NullProtoObjectViaActiveX = function (activeXDocument) { activeXDocument.write(scriptTag('')); activeXDocument.close(); var temp = activeXDocument.parentWindow.Object; activeXDocument = null; // avoid memory leak return temp; }; // Create object with fake `null` prototype: use iframe Object with cleared prototype var NullProtoObjectViaIFrame = function () { // Thrash, waste and sodomy: IE GC bug var iframe = documentCreateElement$1('iframe'); var JS = 'java' + SCRIPT + ':'; var iframeDocument; iframe.style.display = 'none'; html$1.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475 iframe.src = String(JS); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(scriptTag('document.F=Object')); iframeDocument.close(); return iframeDocument.F; }; // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 // avoid IE GC bug var activeXDocument; var NullProtoObject = function () { try { activeXDocument = new ActiveXObject('htmlfile'); } catch (error) { /* ignore */ } NullProtoObject = typeof document != 'undefined' ? document.domain && activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) // old IE : NullProtoObjectViaIFrame() : NullProtoObjectViaActiveX(activeXDocument); // WSH var length = enumBugKeys.length; while (length--) delete NullProtoObject[PROTOTYPE$2][enumBugKeys[length]]; return NullProtoObject(); }; hiddenKeys$2[IE_PROTO$1] = true; // `Object.create` method // https://tc39.es/ecma262/#sec-object.create var objectCreate = Object.create || function create(O, Properties) { var result; if (O !== null) { EmptyConstructor[PROTOTYPE$2] = anObject$g(O); result = new EmptyConstructor(); EmptyConstructor[PROTOTYPE$2] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO$1] = O; } else result = NullProtoObject(); return Properties === undefined ? result : defineProperties$1(result, Properties); }; var aFunction$8 = aFunction$9; var isObject$j = isObject$p; var slice = [].slice; var factories = {}; var construct$1 = function (C, argsLength, args) { if (!(argsLength in factories)) { for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']'; // eslint-disable-next-line no-new-func -- we have no proper alternatives, IE8- only factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')'); } return factories[argsLength](C, args); }; // `Function.prototype.bind` method implementation // https://tc39.es/ecma262/#sec-function.prototype.bind var functionBind = Function.bind || function bind(that /* , ...args */) { var fn = aFunction$8(this); var partArgs = slice.call(arguments, 1); var boundFunction = function bound(/* args... */) { var args = partArgs.concat(slice.call(arguments)); return this instanceof boundFunction ? construct$1(fn, args.length, args) : fn.apply(that, args); }; if (isObject$j(fn.prototype)) boundFunction.prototype = fn.prototype; return boundFunction; }; var $$w = _export; var getBuiltIn$5 = getBuiltIn$a; var aFunction$7 = aFunction$9; var anObject$f = anObject$k; var isObject$i = isObject$p; var create$7 = objectCreate; var bind$8 = functionBind; var fails$v = fails$B; var nativeConstruct = getBuiltIn$5('Reflect', 'construct'); // `Reflect.construct` method // https://tc39.es/ecma262/#sec-reflect.construct // MS Edge supports only 2 arguments and argumentsList argument is optional // FF Nightly sets third argument as `new.target`, but does not create `this` from it var NEW_TARGET_BUG = fails$v(function () { function F() { /* empty */ } return !(nativeConstruct(function () { /* empty */ }, [], F) instanceof F); }); var ARGS_BUG = !fails$v(function () { nativeConstruct(function () { /* empty */ }); }); var FORCED$9 = NEW_TARGET_BUG || ARGS_BUG; $$w({ target: 'Reflect', stat: true, forced: FORCED$9, sham: FORCED$9 }, { construct: function construct(Target, args /* , newTarget */) { aFunction$7(Target); anObject$f(args); var newTarget = arguments.length < 3 ? Target : aFunction$7(arguments[2]); if (ARGS_BUG && !NEW_TARGET_BUG) return nativeConstruct(Target, args, newTarget); if (Target == newTarget) { // w/o altered newTarget, optimization for 0-4 arguments switch (args.length) { case 0: return new Target(); case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (bind$8.apply(Target, $args))(); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype; var instance = create$7(isObject$i(proto) ? proto : Object.prototype); var result = Function.apply.call(Target, instance, args); return isObject$i(result) ? result : instance; } }); var $$v = _export; var toObject$e = toObject$g; var nativeKeys = objectKeys$4; var fails$u = fails$B; var FAILS_ON_PRIMITIVES$2 = fails$u(function () { nativeKeys(1); }); // `Object.keys` method // https://tc39.es/ecma262/#sec-object.keys $$v({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$2 }, { keys: function keys(it) { return nativeKeys(toObject$e(it)); } }); var classof$a = classofRaw$1; // `IsArray` abstract operation // https://tc39.es/ecma262/#sec-isarray // eslint-disable-next-line es/no-array-isarray -- safe var isArray$4 = Array.isArray || function isArray(arg) { return classof$a(arg) == 'Array'; }; var isSymbol$3 = isSymbol$6; var toString$d = function (argument) { if (isSymbol$3(argument)) throw TypeError('Cannot convert a Symbol value to a string'); return String(argument); }; var objectGetOwnPropertyNamesExternal = {}; /* eslint-disable es/no-object-getownpropertynames -- safe */ var toIndexedObject$8 = toIndexedObject$c; var $getOwnPropertyNames$1 = objectGetOwnPropertyNames.f; var toString$c = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return $getOwnPropertyNames$1(it); } catch (error) { return windowNames.slice(); } }; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window objectGetOwnPropertyNamesExternal.f = function getOwnPropertyNames(it) { return windowNames && toString$c.call(it) == '[object Window]' ? getWindowNames(it) : $getOwnPropertyNames$1(toIndexedObject$8(it)); }; var wellKnownSymbolWrapped = {}; var wellKnownSymbol$p = wellKnownSymbol$s; wellKnownSymbolWrapped.f = wellKnownSymbol$p; var global$r = global$D; var path$1 = global$r; var path = path$1; var has$8 = has$g; var wrappedWellKnownSymbolModule$1 = wellKnownSymbolWrapped; var defineProperty$9 = objectDefineProperty.f; var defineWellKnownSymbol$2 = function (NAME) { var Symbol = path.Symbol || (path.Symbol = {}); if (!has$8(Symbol, NAME)) defineProperty$9(Symbol, NAME, { value: wrappedWellKnownSymbolModule$1.f(NAME) }); }; var aFunction$6 = aFunction$9; // optional / simple context binding var functionBindContext = function (fn, that, length) { aFunction$6(fn); if (that === undefined) return fn; switch (length) { case 0: return function () { return fn.call(that); }; case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; var isObject$h = isObject$p; var isArray$3 = isArray$4; var wellKnownSymbol$o = wellKnownSymbol$s; var SPECIES$6 = wellKnownSymbol$o('species'); // a part of `ArraySpeciesCreate` abstract operation // https://tc39.es/ecma262/#sec-arrayspeciescreate var arraySpeciesConstructor$1 = function (originalArray) { var C; if (isArray$3(originalArray)) { C = originalArray.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray$3(C.prototype))) C = undefined; else if (isObject$h(C)) { C = C[SPECIES$6]; if (C === null) C = undefined; } } return C === undefined ? Array : C; }; var arraySpeciesConstructor = arraySpeciesConstructor$1; // `ArraySpeciesCreate` abstract operation // https://tc39.es/ecma262/#sec-arrayspeciescreate var arraySpeciesCreate$3 = function (originalArray, length) { return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length); }; var bind$7 = functionBindContext; var IndexedObject$3 = indexedObject; var toObject$d = toObject$g; var toLength$m = toLength$o; var arraySpeciesCreate$2 = arraySpeciesCreate$3; var push = [].push; // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation var createMethod$4 = function (TYPE) { var IS_MAP = TYPE == 1; var IS_FILTER = TYPE == 2; var IS_SOME = TYPE == 3; var IS_EVERY = TYPE == 4; var IS_FIND_INDEX = TYPE == 6; var IS_FILTER_REJECT = TYPE == 7; var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; return function ($this, callbackfn, that, specificCreate) { var O = toObject$d($this); var self = IndexedObject$3(O); var boundFunction = bind$7(callbackfn, that, 3); var length = toLength$m(self.length); var index = 0; var create = specificCreate || arraySpeciesCreate$2; var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined; var value, result; for (;length > index; index++) if (NO_HOLES || index in self) { value = self[index]; result = boundFunction(value, index, O); if (TYPE) { if (IS_MAP) target[index] = result; // map else if (result) switch (TYPE) { case 3: return true; // some case 5: return value; // find case 6: return index; // findIndex case 2: push.call(target, value); // filter } else switch (TYPE) { case 4: return false; // every case 7: push.call(target, value); // filterReject } } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; }; }; var arrayIteration = { // `Array.prototype.forEach` method // https://tc39.es/ecma262/#sec-array.prototype.foreach forEach: createMethod$4(0), // `Array.prototype.map` method // https://tc39.es/ecma262/#sec-array.prototype.map map: createMethod$4(1), // `Array.prototype.filter` method // https://tc39.es/ecma262/#sec-array.prototype.filter filter: createMethod$4(2), // `Array.prototype.some` method // https://tc39.es/ecma262/#sec-array.prototype.some some: createMethod$4(3), // `Array.prototype.every` method // https://tc39.es/ecma262/#sec-array.prototype.every every: createMethod$4(4), // `Array.prototype.find` method // https://tc39.es/ecma262/#sec-array.prototype.find find: createMethod$4(5), // `Array.prototype.findIndex` method // https://tc39.es/ecma262/#sec-array.prototype.findIndex findIndex: createMethod$4(6), // `Array.prototype.filterReject` method // https://github.com/tc39/proposal-array-filtering filterReject: createMethod$4(7) }; var $$u = _export; var global$q = global$D; var getBuiltIn$4 = getBuiltIn$a; var DESCRIPTORS$d = descriptors; var NATIVE_SYMBOL = nativeSymbol$1; var fails$t = fails$B; var has$7 = has$g; var isArray$2 = isArray$4; var isObject$g = isObject$p; var isSymbol$2 = isSymbol$6; var anObject$e = anObject$k; var toObject$c = toObject$g; var toIndexedObject$7 = toIndexedObject$c; var toPropertyKey$2 = toPropertyKey$5; var $toString$3 = toString$d; var createPropertyDescriptor$4 = createPropertyDescriptor$7; var nativeObjectCreate = objectCreate; var objectKeys$2 = objectKeys$4; var getOwnPropertyNamesModule$1 = objectGetOwnPropertyNames; var getOwnPropertyNamesExternal = objectGetOwnPropertyNamesExternal; var getOwnPropertySymbolsModule$1 = objectGetOwnPropertySymbols; var getOwnPropertyDescriptorModule$2 = objectGetOwnPropertyDescriptor; var definePropertyModule$4 = objectDefineProperty; var propertyIsEnumerableModule$1 = objectPropertyIsEnumerable; var createNonEnumerableProperty$8 = createNonEnumerableProperty$c; var redefine$b = redefine$d.exports; var shared$1 = shared$5.exports; var sharedKey$1 = sharedKey$4; var hiddenKeys$1 = hiddenKeys$6; var uid$2 = uid$5; var wellKnownSymbol$n = wellKnownSymbol$s; var wrappedWellKnownSymbolModule = wellKnownSymbolWrapped; var defineWellKnownSymbol$1 = defineWellKnownSymbol$2; var setToStringTag$7 = setToStringTag$9; var InternalStateModule$8 = internalState; var $forEach$2 = arrayIteration.forEach; var HIDDEN = sharedKey$1('hidden'); var SYMBOL = 'Symbol'; var PROTOTYPE$1 = 'prototype'; var TO_PRIMITIVE = wellKnownSymbol$n('toPrimitive'); var setInternalState$8 = InternalStateModule$8.set; var getInternalState$6 = InternalStateModule$8.getterFor(SYMBOL); var ObjectPrototype$3 = Object[PROTOTYPE$1]; var $Symbol$1 = global$q.Symbol; var $stringify$1 = getBuiltIn$4('JSON', 'stringify'); var nativeGetOwnPropertyDescriptor$2 = getOwnPropertyDescriptorModule$2.f; var nativeDefineProperty$1 = definePropertyModule$4.f; var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f; var nativePropertyIsEnumerable = propertyIsEnumerableModule$1.f; var AllSymbols = shared$1('symbols'); var ObjectPrototypeSymbols = shared$1('op-symbols'); var StringToSymbolRegistry = shared$1('string-to-symbol-registry'); var SymbolToStringRegistry = shared$1('symbol-to-string-registry'); var WellKnownSymbolsStore = shared$1('wks'); var QObject = global$q.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDescriptor = DESCRIPTORS$d && fails$t(function () { return nativeObjectCreate(nativeDefineProperty$1({}, 'a', { get: function () { return nativeDefineProperty$1(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (O, P, Attributes) { var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$2(ObjectPrototype$3, P); if (ObjectPrototypeDescriptor) delete ObjectPrototype$3[P]; nativeDefineProperty$1(O, P, Attributes); if (ObjectPrototypeDescriptor && O !== ObjectPrototype$3) { nativeDefineProperty$1(ObjectPrototype$3, P, ObjectPrototypeDescriptor); } } : nativeDefineProperty$1; var wrap$1 = function (tag, description) { var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol$1[PROTOTYPE$1]); setInternalState$8(symbol, { type: SYMBOL, tag: tag, description: description }); if (!DESCRIPTORS$d) symbol.description = description; return symbol; }; var $defineProperty = function defineProperty(O, P, Attributes) { if (O === ObjectPrototype$3) $defineProperty(ObjectPrototypeSymbols, P, Attributes); anObject$e(O); var key = toPropertyKey$2(P); anObject$e(Attributes); if (has$7(AllSymbols, key)) { if (!Attributes.enumerable) { if (!has$7(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor$4(1, {})); O[HIDDEN][key] = true; } else { if (has$7(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false; Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor$4(0, false) }); } return setSymbolDescriptor(O, key, Attributes); } return nativeDefineProperty$1(O, key, Attributes); }; var $defineProperties = function defineProperties(O, Properties) { anObject$e(O); var properties = toIndexedObject$7(Properties); var keys = objectKeys$2(properties).concat($getOwnPropertySymbols(properties)); $forEach$2(keys, function (key) { if (!DESCRIPTORS$d || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]); }); return O; }; var $create = function create(O, Properties) { return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties); }; var $propertyIsEnumerable = function propertyIsEnumerable(V) { var P = toPropertyKey$2(V); var enumerable = nativePropertyIsEnumerable.call(this, P); if (this === ObjectPrototype$3 && has$7(AllSymbols, P) && !has$7(ObjectPrototypeSymbols, P)) return false; return enumerable || !has$7(this, P) || !has$7(AllSymbols, P) || has$7(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) { var it = toIndexedObject$7(O); var key = toPropertyKey$2(P); if (it === ObjectPrototype$3 && has$7(AllSymbols, key) && !has$7(ObjectPrototypeSymbols, key)) return; var descriptor = nativeGetOwnPropertyDescriptor$2(it, key); if (descriptor && has$7(AllSymbols, key) && !(has$7(it, HIDDEN) && it[HIDDEN][key])) { descriptor.enumerable = true; } return descriptor; }; var $getOwnPropertyNames = function getOwnPropertyNames(O) { var names = nativeGetOwnPropertyNames(toIndexedObject$7(O)); var result = []; $forEach$2(names, function (key) { if (!has$7(AllSymbols, key) && !has$7(hiddenKeys$1, key)) result.push(key); }); return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(O) { var IS_OBJECT_PROTOTYPE = O === ObjectPrototype$3; var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject$7(O)); var result = []; $forEach$2(names, function (key) { if (has$7(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has$7(ObjectPrototype$3, key))) { result.push(AllSymbols[key]); } }); return result; }; // `Symbol` constructor // https://tc39.es/ecma262/#sec-symbol-constructor if (!NATIVE_SYMBOL) { $Symbol$1 = function Symbol() { if (this instanceof $Symbol$1) throw TypeError('Symbol is not a constructor'); var description = !arguments.length || arguments[0] === undefined ? undefined : $toString$3(arguments[0]); var tag = uid$2(description); var setter = function (value) { if (this === ObjectPrototype$3) setter.call(ObjectPrototypeSymbols, value); if (has$7(this, HIDDEN) && has$7(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDescriptor(this, tag, createPropertyDescriptor$4(1, value)); }; if (DESCRIPTORS$d && USE_SETTER) setSymbolDescriptor(ObjectPrototype$3, tag, { configurable: true, set: setter }); return wrap$1(tag, description); }; redefine$b($Symbol$1[PROTOTYPE$1], 'toString', function toString() { return getInternalState$6(this).tag; }); redefine$b($Symbol$1, 'withoutSetter', function (description) { return wrap$1(uid$2(description), description); }); propertyIsEnumerableModule$1.f = $propertyIsEnumerable; definePropertyModule$4.f = $defineProperty; getOwnPropertyDescriptorModule$2.f = $getOwnPropertyDescriptor; getOwnPropertyNamesModule$1.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames; getOwnPropertySymbolsModule$1.f = $getOwnPropertySymbols; wrappedWellKnownSymbolModule.f = function (name) { return wrap$1(wellKnownSymbol$n(name), name); }; if (DESCRIPTORS$d) { // https://github.com/tc39/proposal-Symbol-description nativeDefineProperty$1($Symbol$1[PROTOTYPE$1], 'description', { configurable: true, get: function description() { return getInternalState$6(this).description; } }); { redefine$b(ObjectPrototype$3, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true }); } } } $$u({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, { Symbol: $Symbol$1 }); $forEach$2(objectKeys$2(WellKnownSymbolsStore), function (name) { defineWellKnownSymbol$1(name); }); $$u({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, { // `Symbol.for` method // https://tc39.es/ecma262/#sec-symbol.for 'for': function (key) { var string = $toString$3(key); if (has$7(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string]; var symbol = $Symbol$1(string); StringToSymbolRegistry[string] = symbol; SymbolToStringRegistry[symbol] = string; return symbol; }, // `Symbol.keyFor` method // https://tc39.es/ecma262/#sec-symbol.keyfor keyFor: function keyFor(sym) { if (!isSymbol$2(sym)) throw TypeError(sym + ' is not a symbol'); if (has$7(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym]; }, useSetter: function () { USE_SETTER = true; }, useSimple: function () { USE_SETTER = false; } }); $$u({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS$d }, { // `Object.create` method // https://tc39.es/ecma262/#sec-object.create create: $create, // `Object.defineProperty` method // https://tc39.es/ecma262/#sec-object.defineproperty defineProperty: $defineProperty, // `Object.defineProperties` method // https://tc39.es/ecma262/#sec-object.defineproperties defineProperties: $defineProperties, // `Object.getOwnPropertyDescriptor` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptors getOwnPropertyDescriptor: $getOwnPropertyDescriptor }); $$u({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, { // `Object.getOwnPropertyNames` method // https://tc39.es/ecma262/#sec-object.getownpropertynames getOwnPropertyNames: $getOwnPropertyNames, // `Object.getOwnPropertySymbols` method // https://tc39.es/ecma262/#sec-object.getownpropertysymbols getOwnPropertySymbols: $getOwnPropertySymbols }); // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives // https://bugs.chromium.org/p/v8/issues/detail?id=3443 $$u({ target: 'Object', stat: true, forced: fails$t(function () { getOwnPropertySymbolsModule$1.f(1); }) }, { getOwnPropertySymbols: function getOwnPropertySymbols(it) { return getOwnPropertySymbolsModule$1.f(toObject$c(it)); } }); // `JSON.stringify` method behavior with symbols // https://tc39.es/ecma262/#sec-json.stringify if ($stringify$1) { var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails$t(function () { var symbol = $Symbol$1(); // MS Edge converts symbol values to JSON as {} return $stringify$1([symbol]) != '[null]' // WebKit converts symbol values to JSON as null || $stringify$1({ a: symbol }) != '{}' // V8 throws on boxed symbols || $stringify$1(Object(symbol)) != '{}'; }); $$u({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, { // eslint-disable-next-line no-unused-vars -- required for `.length` stringify: function stringify(it, replacer, space) { var args = [it]; var index = 1; var $replacer; while (arguments.length > index) args.push(arguments[index++]); $replacer = replacer; if (!isObject$g(replacer) && it === undefined || isSymbol$2(it)) return; // IE8 returns string on undefined if (!isArray$2(replacer)) replacer = function (key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol$2(value)) return value; }; args[1] = replacer; return $stringify$1.apply(null, args); } }); } // `Symbol.prototype[@@toPrimitive]` method // https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive if (!$Symbol$1[PROTOTYPE$1][TO_PRIMITIVE]) { createNonEnumerableProperty$8($Symbol$1[PROTOTYPE$1], TO_PRIMITIVE, $Symbol$1[PROTOTYPE$1].valueOf); } // `Symbol.prototype[@@toStringTag]` property // https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag setToStringTag$7($Symbol$1, SYMBOL); hiddenKeys$1[HIDDEN] = true; var fails$s = fails$B; var wellKnownSymbol$m = wellKnownSymbol$s; var V8_VERSION$2 = engineV8Version; var SPECIES$5 = wellKnownSymbol$m('species'); var arrayMethodHasSpeciesSupport$5 = function (METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return V8_VERSION$2 >= 51 || !fails$s(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES$5] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; var $$t = _export; var $filter$1 = arrayIteration.filter; var arrayMethodHasSpeciesSupport$4 = arrayMethodHasSpeciesSupport$5; var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport$4('filter'); // `Array.prototype.filter` method // https://tc39.es/ecma262/#sec-array.prototype.filter // with adding support of @@species $$t({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 }, { filter: function filter(callbackfn /* , thisArg */) { return $filter$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); var $$s = _export; var fails$r = fails$B; var toIndexedObject$6 = toIndexedObject$c; var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; var DESCRIPTORS$c = descriptors; var FAILS_ON_PRIMITIVES$1 = fails$r(function () { nativeGetOwnPropertyDescriptor$1(1); }); var FORCED$8 = !DESCRIPTORS$c || FAILS_ON_PRIMITIVES$1; // `Object.getOwnPropertyDescriptor` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor $$s({ target: 'Object', stat: true, forced: FORCED$8, sham: !DESCRIPTORS$c }, { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) { return nativeGetOwnPropertyDescriptor$1(toIndexedObject$6(it), key); } }); var toPropertyKey$1 = toPropertyKey$5; var definePropertyModule$3 = objectDefineProperty; var createPropertyDescriptor$3 = createPropertyDescriptor$7; var createProperty$5 = function (object, key, value) { var propertyKey = toPropertyKey$1(key); if (propertyKey in object) definePropertyModule$3.f(object, propertyKey, createPropertyDescriptor$3(0, value)); else object[propertyKey] = value; }; var $$r = _export; var DESCRIPTORS$b = descriptors; var ownKeys$7 = ownKeys$9; var toIndexedObject$5 = toIndexedObject$c; var getOwnPropertyDescriptorModule$1 = objectGetOwnPropertyDescriptor; var createProperty$4 = createProperty$5; // `Object.getOwnPropertyDescriptors` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptors $$r({ target: 'Object', stat: true, sham: !DESCRIPTORS$b }, { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { var O = toIndexedObject$5(object); var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule$1.f; var keys = ownKeys$7(O); var result = {}; var index = 0; var key, descriptor; while (keys.length > index) { descriptor = getOwnPropertyDescriptor(O, key = keys[index++]); if (descriptor !== undefined) createProperty$4(result, key, descriptor); } return result; } }); 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$1(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); }); }; } function _assertThisInitialized$3(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits$4(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof$3(obj) { "@babel/helpers - typeof"; return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$3(obj); } function _possibleConstructorReturn$4(self, call) { if (call && (_typeof$3(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized$3(self); } function _getPrototypeOf$4(o) { _getPrototypeOf$4 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf$4(o); } function _defineProperty$3(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; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$4(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck$4(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var wellKnownSymbol$l = wellKnownSymbol$s; var TO_STRING_TAG$3 = wellKnownSymbol$l('toStringTag'); var test$1 = {}; test$1[TO_STRING_TAG$3] = 'z'; var toStringTagSupport = String(test$1) === '[object z]'; var TO_STRING_TAG_SUPPORT$2 = toStringTagSupport; var classofRaw = classofRaw$1; var wellKnownSymbol$k = wellKnownSymbol$s; var TO_STRING_TAG$2 = wellKnownSymbol$k('toStringTag'); // ES3 wrong here var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (error) { /* empty */ } }; // getting tag from ES6+ `Object.prototype.toString` var classof$9 = TO_STRING_TAG_SUPPORT$2 ? classofRaw : function (it) { var O, tag, result; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$2)) == 'string' ? tag // builtinTag case : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; }; var TO_STRING_TAG_SUPPORT$1 = toStringTagSupport; var classof$8 = classof$9; // `Object.prototype.toString` method implementation // https://tc39.es/ecma262/#sec-object.prototype.tostring var objectToString = TO_STRING_TAG_SUPPORT$1 ? {}.toString : function toString() { return '[object ' + classof$8(this) + ']'; }; var TO_STRING_TAG_SUPPORT = toStringTagSupport; var redefine$a = redefine$d.exports; var toString$b = objectToString; // `Object.prototype.toString` method // https://tc39.es/ecma262/#sec-object.prototype.tostring if (!TO_STRING_TAG_SUPPORT) { redefine$a(Object.prototype, 'toString', toString$b, { unsafe: true }); } var global$p = global$D; var nativePromiseConstructor = global$p.Promise; var redefine$9 = redefine$d.exports; var redefineAll$4 = function (target, src, options) { for (var key in src) redefine$9(target, key, src[key], options); return target; }; var isObject$f = isObject$p; var aPossiblePrototype$1 = function (it) { if (!isObject$f(it) && it !== null) { throw TypeError("Can't set " + String(it) + ' as a prototype'); } return it; }; /* eslint-disable no-proto -- safe */ var anObject$d = anObject$k; var aPossiblePrototype = aPossiblePrototype$1; // `Object.setPrototypeOf` method // https://tc39.es/ecma262/#sec-object.setprototypeof // Works with __proto__ only. Old v8 can't work with null proto objects. // eslint-disable-next-line es/no-object-setprototypeof -- safe var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () { var CORRECT_SETTER = false; var test = {}; var setter; try { // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; setter.call(test, []); CORRECT_SETTER = test instanceof Array; } catch (error) { /* empty */ } return function setPrototypeOf(O, proto) { anObject$d(O); aPossiblePrototype(proto); if (CORRECT_SETTER) setter.call(O, proto); else O.__proto__ = proto; return O; }; }() : undefined); var getBuiltIn$3 = getBuiltIn$a; var definePropertyModule$2 = objectDefineProperty; var wellKnownSymbol$j = wellKnownSymbol$s; var DESCRIPTORS$a = descriptors; var SPECIES$4 = wellKnownSymbol$j('species'); var setSpecies$4 = function (CONSTRUCTOR_NAME) { var Constructor = getBuiltIn$3(CONSTRUCTOR_NAME); var defineProperty = definePropertyModule$2.f; if (DESCRIPTORS$a && Constructor && !Constructor[SPECIES$4]) { defineProperty(Constructor, SPECIES$4, { configurable: true, get: function () { return this; } }); } }; var anInstance$7 = function (it, Constructor, name) { if (!(it instanceof Constructor)) { throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); } return it; }; var iterators = {}; var wellKnownSymbol$i = wellKnownSymbol$s; var Iterators$4 = iterators; var ITERATOR$8 = wellKnownSymbol$i('iterator'); var ArrayPrototype$1 = Array.prototype; // check on default Array iterator var isArrayIteratorMethod$3 = function (it) { return it !== undefined && (Iterators$4.Array === it || ArrayPrototype$1[ITERATOR$8] === it); }; var classof$7 = classof$9; var Iterators$3 = iterators; var wellKnownSymbol$h = wellKnownSymbol$s; var ITERATOR$7 = wellKnownSymbol$h('iterator'); var getIteratorMethod$5 = function (it) { if (it != undefined) return it[ITERATOR$7] || it['@@iterator'] || Iterators$3[classof$7(it)]; }; var anObject$c = anObject$k; var getIteratorMethod$4 = getIteratorMethod$5; var getIterator$4 = function (it, usingIterator) { var iteratorMethod = arguments.length < 2 ? getIteratorMethod$4(it) : usingIterator; if (typeof iteratorMethod != 'function') { throw TypeError(String(it) + ' is not iterable'); } return anObject$c(iteratorMethod.call(it)); }; var anObject$b = anObject$k; var iteratorClose$2 = function (iterator, kind, value) { var innerResult, innerError; anObject$b(iterator); try { innerResult = iterator['return']; if (innerResult === undefined) { if (kind === 'throw') throw value; return value; } innerResult = innerResult.call(iterator); } catch (error) { innerError = true; innerResult = error; } if (kind === 'throw') throw value; if (innerError) throw innerResult; anObject$b(innerResult); return value; }; var anObject$a = anObject$k; var isArrayIteratorMethod$2 = isArrayIteratorMethod$3; var toLength$l = toLength$o; var bind$6 = functionBindContext; var getIterator$3 = getIterator$4; var getIteratorMethod$3 = getIteratorMethod$5; var iteratorClose$1 = iteratorClose$2; var Result = function (stopped, result) { this.stopped = stopped; this.result = result; }; var iterate$3 = function (iterable, unboundFunction, options) { var that = options && options.that; var AS_ENTRIES = !!(options && options.AS_ENTRIES); var IS_ITERATOR = !!(options && options.IS_ITERATOR); var INTERRUPTED = !!(options && options.INTERRUPTED); var fn = bind$6(unboundFunction, that, 1 + AS_ENTRIES + INTERRUPTED); var iterator, iterFn, index, length, result, next, step; var stop = function (condition) { if (iterator) iteratorClose$1(iterator, 'normal', condition); return new Result(true, condition); }; var callFn = function (value) { if (AS_ENTRIES) { anObject$a(value); return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]); } return INTERRUPTED ? fn(value, stop) : fn(value); }; if (IS_ITERATOR) { iterator = iterable; } else { iterFn = getIteratorMethod$3(iterable); if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); // optimisation for array iterators if (isArrayIteratorMethod$2(iterFn)) { for (index = 0, length = toLength$l(iterable.length); length > index; index++) { result = callFn(iterable[index]); if (result && result instanceof Result) return result; } return new Result(false); } iterator = getIterator$3(iterable, iterFn); } next = iterator.next; while (!(step = next.call(iterator)).done) { try { result = callFn(step.value); } catch (error) { iteratorClose$1(iterator, 'throw', error); } if (typeof result == 'object' && result && result instanceof Result) return result; } return new Result(false); }; var wellKnownSymbol$g = wellKnownSymbol$s; var ITERATOR$6 = wellKnownSymbol$g('iterator'); var SAFE_CLOSING = false; try { var called = 0; var iteratorWithReturn = { next: function () { return { done: !!called++ }; }, 'return': function () { SAFE_CLOSING = true; } }; iteratorWithReturn[ITERATOR$6] = function () { return this; }; // eslint-disable-next-line es/no-array-from, no-throw-literal -- required for testing Array.from(iteratorWithReturn, function () { throw 2; }); } catch (error) { /* empty */ } var checkCorrectnessOfIteration$4 = function (exec, SKIP_CLOSING) { if (!SKIP_CLOSING && !SAFE_CLOSING) return false; var ITERATION_SUPPORT = false; try { var object = {}; object[ITERATOR$6] = function () { return { next: function () { return { done: ITERATION_SUPPORT = true }; } }; }; exec(object); } catch (error) { /* empty */ } return ITERATION_SUPPORT; }; var anObject$9 = anObject$k; var aFunction$5 = aFunction$9; var wellKnownSymbol$f = wellKnownSymbol$s; var SPECIES$3 = wellKnownSymbol$f('species'); // `SpeciesConstructor` abstract operation // https://tc39.es/ecma262/#sec-speciesconstructor var speciesConstructor$3 = function (O, defaultConstructor) { var C = anObject$9(O).constructor; var S; return C === undefined || (S = anObject$9(C)[SPECIES$3]) == undefined ? defaultConstructor : aFunction$5(S); }; var userAgent$4 = engineUserAgent; var engineIsIos = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent$4); var classof$6 = classofRaw$1; var global$o = global$D; var engineIsNode = classof$6(global$o.process) == 'process'; var global$n = global$D; var fails$q = fails$B; var bind$5 = functionBindContext; var html = html$2; var createElement = documentCreateElement$2; var IS_IOS$1 = engineIsIos; var IS_NODE$2 = engineIsNode; var set$1 = global$n.setImmediate; var clear = global$n.clearImmediate; var process$2 = global$n.process; var MessageChannel = global$n.MessageChannel; var Dispatch = global$n.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var location, defer, channel, port; try { // Deno throws a ReferenceError on `location` access without `--location` flag location = global$n.location; } catch (error) { /* empty */ } var run = function (id) { // eslint-disable-next-line no-prototype-builtins -- safe if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var runner = function (id) { return function () { run(id); }; }; var listener = function (event) { run(event.data); }; var post = function (id) { // old engines have not location.origin global$n.postMessage(String(id), location.protocol + '//' + location.host); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!set$1 || !clear) { set$1 = function setImmediate(fn) { var args = []; var argumentsLength = arguments.length; var i = 1; while (argumentsLength > i) args.push(arguments[i++]); queue[++counter] = function () { // eslint-disable-next-line no-new-func -- spec requirement (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args); }; defer(counter); return counter; }; clear = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (IS_NODE$2) { defer = function (id) { process$2.nextTick(runner(id)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(runner(id)); }; // Browsers with MessageChannel, includes WebWorkers // except iOS - https://github.com/zloirock/core-js/issues/624 } else if (MessageChannel && !IS_IOS$1) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = bind$5(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if ( global$n.addEventListener && typeof postMessage == 'function' && !global$n.importScripts && location && location.protocol !== 'file:' && !fails$q(post) ) { defer = post; global$n.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in createElement('script')) { defer = function (id) { html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(runner(id), 0); }; } } var task$1 = { set: set$1, clear: clear }; var userAgent$3 = engineUserAgent; var global$m = global$D; var engineIsIosPebble = /ipad|iphone|ipod/i.test(userAgent$3) && global$m.Pebble !== undefined; var userAgent$2 = engineUserAgent; var engineIsWebosWebkit = /web0s(?!.*chrome)/i.test(userAgent$2); var global$l = global$D; var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f; var macrotask = task$1.set; var IS_IOS = engineIsIos; var IS_IOS_PEBBLE = engineIsIosPebble; var IS_WEBOS_WEBKIT = engineIsWebosWebkit; var IS_NODE$1 = engineIsNode; var MutationObserver = global$l.MutationObserver || global$l.WebKitMutationObserver; var document$2 = global$l.document; var process$1 = global$l.process; var Promise$1 = global$l.Promise; // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` var queueMicrotaskDescriptor = getOwnPropertyDescriptor$2(global$l, 'queueMicrotask'); var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value; var flush, head, last, notify$1, toggle, node, promise, then; // modern engines have queueMicrotask method if (!queueMicrotask) { flush = function () { var parent, fn; if (IS_NODE$1 && (parent = process$1.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (error) { if (head) notify$1(); else last = undefined; throw error; } } last = undefined; if (parent) parent.enter(); }; // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 // also except WebOS Webkit https://github.com/zloirock/core-js/issues/898 if (!IS_IOS && !IS_NODE$1 && !IS_WEBOS_WEBKIT && MutationObserver && document$2) { toggle = true; node = document$2.createTextNode(''); new MutationObserver(flush).observe(node, { characterData: true }); notify$1 = function () { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (!IS_IOS_PEBBLE && Promise$1 && Promise$1.resolve) { // Promise.resolve without an argument throws an error in LG WebOS 2 promise = Promise$1.resolve(undefined); // workaround of WebKit ~ iOS Safari 10.1 bug promise.constructor = Promise$1; then = promise.then; notify$1 = function () { then.call(promise, flush); }; // Node.js without promises } else if (IS_NODE$1) { notify$1 = function () { process$1.nextTick(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify$1 = function () { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global$l, flush); }; } } var microtask$1 = queueMicrotask || function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify$1(); } last = task; }; var newPromiseCapability$2 = {}; var aFunction$4 = aFunction$9; var PromiseCapability = function (C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction$4(resolve); this.reject = aFunction$4(reject); }; // `NewPromiseCapability` abstract operation // https://tc39.es/ecma262/#sec-newpromisecapability newPromiseCapability$2.f = function (C) { return new PromiseCapability(C); }; var anObject$8 = anObject$k; var isObject$e = isObject$p; var newPromiseCapability$1 = newPromiseCapability$2; var promiseResolve$1 = function (C, x) { anObject$8(C); if (isObject$e(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability$1.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; var global$k = global$D; var hostReportErrors$1 = function (a, b) { var console = global$k.console; if (console && console.error) { arguments.length === 1 ? console.error(a) : console.error(a, b); } }; var perform$1 = function (exec) { try { return { error: false, value: exec() }; } catch (error) { return { error: true, value: error }; } }; var engineIsBrowser = typeof window == 'object'; var $$q = _export; var global$j = global$D; var getBuiltIn$2 = getBuiltIn$a; var NativePromise = nativePromiseConstructor; var redefine$8 = redefine$d.exports; var redefineAll$3 = redefineAll$4; var setPrototypeOf$6 = objectSetPrototypeOf; var setToStringTag$6 = setToStringTag$9; var setSpecies$3 = setSpecies$4; var isObject$d = isObject$p; var aFunction$3 = aFunction$9; var anInstance$6 = anInstance$7; var inspectSource = inspectSource$3; var iterate$2 = iterate$3; var checkCorrectnessOfIteration$3 = checkCorrectnessOfIteration$4; var speciesConstructor$2 = speciesConstructor$3; var task = task$1.set; var microtask = microtask$1; var promiseResolve = promiseResolve$1; var hostReportErrors = hostReportErrors$1; var newPromiseCapabilityModule = newPromiseCapability$2; var perform = perform$1; var InternalStateModule$7 = internalState; var isForced$2 = isForced_1; var wellKnownSymbol$e = wellKnownSymbol$s; var IS_BROWSER = engineIsBrowser; var IS_NODE = engineIsNode; var V8_VERSION$1 = engineV8Version; var SPECIES$2 = wellKnownSymbol$e('species'); var PROMISE = 'Promise'; var getInternalState$5 = InternalStateModule$7.get; var setInternalState$7 = InternalStateModule$7.set; var getInternalPromiseState = InternalStateModule$7.getterFor(PROMISE); var NativePromisePrototype = NativePromise && NativePromise.prototype; var PromiseConstructor = NativePromise; var PromiseConstructorPrototype = NativePromisePrototype; var TypeError$1 = global$j.TypeError; var document$1 = global$j.document; var process = global$j.process; var newPromiseCapability = newPromiseCapabilityModule.f; var newGenericPromiseCapability = newPromiseCapability; var DISPATCH_EVENT = !!(document$1 && document$1.createEvent && global$j.dispatchEvent); var NATIVE_REJECTION_EVENT = typeof PromiseRejectionEvent == 'function'; var UNHANDLED_REJECTION = 'unhandledrejection'; var REJECTION_HANDLED = 'rejectionhandled'; var PENDING = 0; var FULFILLED = 1; var REJECTED = 2; var HANDLED = 1; var UNHANDLED = 2; var SUBCLASSING = false; var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen; var FORCED$7 = isForced$2(PROMISE, function () { var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(PromiseConstructor); var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(PromiseConstructor); // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 // We can't detect it synchronously, so just check versions if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION$1 === 66) return true; // We can't use @@species feature detection in V8 since it causes // deoptimization and performance degradation // https://github.com/zloirock/core-js/issues/679 if (V8_VERSION$1 >= 51 && /native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) return false; // Detect correctness of subclassing with @@species support var promise = new PromiseConstructor(function (resolve) { resolve(1); }); var FakePromise = function (exec) { exec(function () { /* empty */ }, function () { /* empty */ }); }; var constructor = promise.constructor = {}; constructor[SPECIES$2] = FakePromise; SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise; if (!SUBCLASSING) return true; // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test return !GLOBAL_CORE_JS_PROMISE && IS_BROWSER && !NATIVE_REJECTION_EVENT; }); var INCORRECT_ITERATION$1 = FORCED$7 || !checkCorrectnessOfIteration$3(function (iterable) { PromiseConstructor.all(iterable)['catch'](function () { /* empty */ }); }); // helpers var isThenable = function (it) { var then; return isObject$d(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function (state, isReject) { if (state.notified) return; state.notified = true; var chain = state.reactions; microtask(function () { var value = state.value; var ok = state.state == FULFILLED; var index = 0; // variable length - can't use forEach while (chain.length > index) { var reaction = chain[index++]; var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then, exited; try { if (handler) { if (!ok) { if (state.rejection === UNHANDLED) onHandleUnhandled(state); state.rejection = HANDLED; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); // can throw if (domain) { domain.exit(); exited = true; } } if (result === reaction.promise) { reject(TypeError$1('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (error) { if (domain && !exited) domain.exit(); reject(error); } } state.reactions = []; state.notified = false; if (isReject && !state.rejection) onUnhandled(state); }); }; var dispatchEvent = function (name, promise, reason) { var event, handler; if (DISPATCH_EVENT) { event = document$1.createEvent('Event'); event.promise = promise; event.reason = reason; event.initEvent(name, false, true); global$j.dispatchEvent(event); } else event = { promise: promise, reason: reason }; if (!NATIVE_REJECTION_EVENT && (handler = global$j['on' + name])) handler(event); else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason); }; var onUnhandled = function (state) { task.call(global$j, function () { var promise = state.facade; var value = state.value; var IS_UNHANDLED = isUnhandled(state); var result; if (IS_UNHANDLED) { result = perform(function () { if (IS_NODE) { process.emit('unhandledRejection', value, promise); } else dispatchEvent(UNHANDLED_REJECTION, promise, value); }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED; if (result.error) throw result.value; } }); }; var isUnhandled = function (state) { return state.rejection !== HANDLED && !state.parent; }; var onHandleUnhandled = function (state) { task.call(global$j, function () { var promise = state.facade; if (IS_NODE) { process.emit('rejectionHandled', promise); } else dispatchEvent(REJECTION_HANDLED, promise, state.value); }); }; var bind$4 = function (fn, state, unwrap) { return function (value) { fn(state, value, unwrap); }; }; var internalReject = function (state, value, unwrap) { if (state.done) return; state.done = true; if (unwrap) state = unwrap; state.value = value; state.state = REJECTED; notify(state, true); }; var internalResolve = function (state, value, unwrap) { if (state.done) return; state.done = true; if (unwrap) state = unwrap; try { if (state.facade === value) throw TypeError$1("Promise can't be resolved itself"); var then = isThenable(value); if (then) { microtask(function () { var wrapper = { done: false }; try { then.call(value, bind$4(internalResolve, wrapper, state), bind$4(internalReject, wrapper, state) ); } catch (error) { internalReject(wrapper, error, state); } }); } else { state.value = value; state.state = FULFILLED; notify(state, false); } } catch (error) { internalReject({ done: false }, error, state); } }; // constructor polyfill if (FORCED$7) { // 25.4.3.1 Promise(executor) PromiseConstructor = function Promise(executor) { anInstance$6(this, PromiseConstructor, PROMISE); aFunction$3(executor); Internal.call(this); var state = getInternalState$5(this); try { executor(bind$4(internalResolve, state), bind$4(internalReject, state)); } catch (error) { internalReject(state, error); } }; PromiseConstructorPrototype = PromiseConstructor.prototype; // eslint-disable-next-line no-unused-vars -- required for `.length` Internal = function Promise(executor) { setInternalState$7(this, { type: PROMISE, done: false, notified: false, parent: false, reactions: [], rejection: false, state: PENDING, value: undefined }); }; Internal.prototype = redefineAll$3(PromiseConstructorPrototype, { // `Promise.prototype.then` method // https://tc39.es/ecma262/#sec-promise.prototype.then then: function then(onFulfilled, onRejected) { var state = getInternalPromiseState(this); var reaction = newPromiseCapability(speciesConstructor$2(this, PromiseConstructor)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = IS_NODE ? process.domain : undefined; state.parent = true; state.reactions.push(reaction); if (state.state != PENDING) notify(state, false); return reaction.promise; }, // `Promise.prototype.catch` method // https://tc39.es/ecma262/#sec-promise.prototype.catch 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); var state = getInternalState$5(promise); this.promise = promise; this.resolve = bind$4(internalResolve, state); this.reject = bind$4(internalReject, state); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === PromiseConstructor || C === PromiseWrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; if (typeof NativePromise == 'function' && NativePromisePrototype !== Object.prototype) { nativeThen = NativePromisePrototype.then; if (!SUBCLASSING) { // make `Promise#then` return a polyfilled `Promise` for native promise-based APIs redefine$8(NativePromisePrototype, 'then', function then(onFulfilled, onRejected) { var that = this; return new PromiseConstructor(function (resolve, reject) { nativeThen.call(that, resolve, reject); }).then(onFulfilled, onRejected); // https://github.com/zloirock/core-js/issues/640 }, { unsafe: true }); // makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then` redefine$8(NativePromisePrototype, 'catch', PromiseConstructorPrototype['catch'], { unsafe: true }); } // make `.constructor === Promise` work for native promise-based APIs try { delete NativePromisePrototype.constructor; } catch (error) { /* empty */ } // make `instanceof Promise` work for native promise-based APIs if (setPrototypeOf$6) { setPrototypeOf$6(NativePromisePrototype, PromiseConstructorPrototype); } } } $$q({ global: true, wrap: true, forced: FORCED$7 }, { Promise: PromiseConstructor }); setToStringTag$6(PromiseConstructor, PROMISE, false); setSpecies$3(PROMISE); PromiseWrapper = getBuiltIn$2(PROMISE); // statics $$q({ target: PROMISE, stat: true, forced: FORCED$7 }, { // `Promise.reject` method // https://tc39.es/ecma262/#sec-promise.reject reject: function reject(r) { var capability = newPromiseCapability(this); capability.reject.call(undefined, r); return capability.promise; } }); $$q({ target: PROMISE, stat: true, forced: FORCED$7 }, { // `Promise.resolve` method // https://tc39.es/ecma262/#sec-promise.resolve resolve: function resolve(x) { return promiseResolve(this, x); } }); $$q({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION$1 }, { // `Promise.all` method // https://tc39.es/ecma262/#sec-promise.all all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var $promiseResolve = aFunction$3(C.resolve); var values = []; var counter = 0; var remaining = 1; iterate$2(iterable, function (promise) { var index = counter++; var alreadyCalled = false; values.push(undefined); remaining++; $promiseResolve.call(C, promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.error) reject(result.value); return capability.promise; }, // `Promise.race` method // https://tc39.es/ecma262/#sec-promise.race race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { var $promiseResolve = aFunction$3(C.resolve); iterate$2(iterable, function (promise) { $promiseResolve.call(C, promise).then(capability.resolve, reject); }); }); if (result.error) reject(result.value); return capability.promise; } }); var $$p = _export; var $map$1 = arrayIteration.map; var arrayMethodHasSpeciesSupport$3 = arrayMethodHasSpeciesSupport$5; var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport$3('map'); // `Array.prototype.map` method // https://tc39.es/ecma262/#sec-array.prototype.map // with adding support of @@species $$p({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 }, { map: function map(callbackfn /* , thisArg */) { return $map$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // iterable DOM collections // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods var domIterables = { CSSRuleList: 0, CSSStyleDeclaration: 0, CSSValueList: 0, ClientRectList: 0, DOMRectList: 0, DOMStringList: 0, DOMTokenList: 1, DataTransferItemList: 0, FileList: 0, HTMLAllCollection: 0, HTMLCollection: 0, HTMLFormElement: 0, HTMLSelectElement: 0, MediaList: 0, MimeTypeArray: 0, NamedNodeMap: 0, NodeList: 1, PaintRequestList: 0, Plugin: 0, PluginArray: 0, SVGLengthList: 0, SVGNumberList: 0, SVGPathSegList: 0, SVGPointList: 0, SVGStringList: 0, SVGTransformList: 0, SourceBufferList: 0, StyleSheetList: 0, TextTrackCueList: 0, TextTrackList: 0, TouchList: 0 }; // in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList` var documentCreateElement = documentCreateElement$2; var classList = documentCreateElement('span').classList; var DOMTokenListPrototype$2 = classList && classList.constructor && classList.constructor.prototype; var domTokenListPrototype = DOMTokenListPrototype$2 === Object.prototype ? undefined : DOMTokenListPrototype$2; var fails$p = fails$B; var arrayMethodIsStrict$4 = function (METHOD_NAME, argument) { var method = [][METHOD_NAME]; return !!method && fails$p(function () { // eslint-disable-next-line no-useless-call,no-throw-literal -- required for testing method.call(null, argument || function () { throw 1; }, 1); }); }; var $forEach$1 = arrayIteration.forEach; var arrayMethodIsStrict$3 = arrayMethodIsStrict$4; var STRICT_METHOD$3 = arrayMethodIsStrict$3('forEach'); // `Array.prototype.forEach` method implementation // https://tc39.es/ecma262/#sec-array.prototype.foreach var arrayForEach = !STRICT_METHOD$3 ? function forEach(callbackfn /* , thisArg */) { return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); // eslint-disable-next-line es/no-array-prototype-foreach -- safe } : [].forEach; var global$i = global$D; var DOMIterables$1 = domIterables; var DOMTokenListPrototype$1 = domTokenListPrototype; var forEach$1 = arrayForEach; var createNonEnumerableProperty$7 = createNonEnumerableProperty$c; var handlePrototype$1 = function (CollectionPrototype) { // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype && CollectionPrototype.forEach !== forEach$1) try { createNonEnumerableProperty$7(CollectionPrototype, 'forEach', forEach$1); } catch (error) { CollectionPrototype.forEach = forEach$1; } }; for (var COLLECTION_NAME$1 in DOMIterables$1) { handlePrototype$1(global$i[COLLECTION_NAME$1] && global$i[COLLECTION_NAME$1].prototype); } handlePrototype$1(DOMTokenListPrototype$1); /** * 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 Op = Object.prototype; var hasOwn$1 = Op.hasOwnProperty; var undefined$1; // 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 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; } // 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$3 = {}; IteratorPrototype$3[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn$1.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype$3 = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype$3); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { prototype[method] = function (arg) { return this._invoke(method, arg); }; }); } function isGeneratorFunction(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; } function mark(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; } // `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. function awrap(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$3(value) === "object" && hasOwn$1.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); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; // 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. function async(innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return 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$1) { // 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$1; 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$1; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function () { return this; }; Gp.toString = function () { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } function keys$2(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$1.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined$1; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } function doneResult() { return { value: undefined$1, done: true }; } Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined$1; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined$1; 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$1.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined$1; } } } }, stop: function stop() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function dispatchException(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$1; } 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$1.call(entry, "catchLoc"); var hasFinally = hasOwn$1.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 abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn$1.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 complete(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 finish(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 _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (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 delegateYield(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$1; } return ContinueSentinel; } }; // Export a default namespace that plays well with Rollup var _regeneratorRuntime$1 = { wrap: wrap, isGeneratorFunction: isGeneratorFunction, AsyncIterator: AsyncIterator, mark: mark, awrap: awrap, async: async, keys: keys$2, values: values }; var regenerator = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': _regeneratorRuntime$1 }); function __decorate$1(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ((typeof Reflect === "undefined" ? "undefined" : _typeof$3(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; } return c > 3 && r && Object.defineProperty(target, key, r), r; } function __metadata$1(metadataKey, metadataValue) { if ((typeof Reflect === "undefined" ? "undefined" : _typeof$3(Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } var $$o = _export; var fails$o = fails$B; var isArray$1 = isArray$4; var isObject$c = isObject$p; var toObject$b = toObject$g; var toLength$k = toLength$o; var createProperty$3 = createProperty$5; var arraySpeciesCreate$1 = arraySpeciesCreate$3; var arrayMethodHasSpeciesSupport$2 = arrayMethodHasSpeciesSupport$5; var wellKnownSymbol$d = wellKnownSymbol$s; var V8_VERSION = engineV8Version; var IS_CONCAT_SPREADABLE = wellKnownSymbol$d('isConcatSpreadable'); var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/679 var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails$o(function () { var array = []; array[IS_CONCAT_SPREADABLE] = false; return array.concat()[0] !== array; }); var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport$2('concat'); var isConcatSpreadable = function (O) { if (!isObject$c(O)) return false; var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray$1(O); }; var FORCED$6 = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method // https://tc39.es/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species $$o({ target: 'Array', proto: true, forced: FORCED$6 }, { // eslint-disable-next-line no-unused-vars -- required for `.length` concat: function concat(arg) { var O = toObject$b(this); var A = arraySpeciesCreate$1(O, 0); var n = 0; var i, k, length, len, E; for (i = -1, length = arguments.length; i < length; i++) { E = i === -1 ? O : arguments[i]; if (isConcatSpreadable(E)) { len = toLength$k(E.length); if (n + len > MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); for (k = 0; k < len; k++, n++) if (k in E) createProperty$3(A, n, E[k]); } else { if (n >= MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); createProperty$3(A, n++, E); } } A.length = n; return A; } }); var anObject$7 = anObject$k; var iteratorClose = iteratorClose$2; // call something on iterator step with safe closing on error var callWithSafeIterationClosing$1 = function (iterator, fn, value, ENTRIES) { try { return ENTRIES ? fn(anObject$7(value)[0], value[1]) : fn(value); } catch (error) { iteratorClose(iterator, 'throw', error); } }; var bind$3 = functionBindContext; var toObject$a = toObject$g; var callWithSafeIterationClosing = callWithSafeIterationClosing$1; var isArrayIteratorMethod$1 = isArrayIteratorMethod$3; var toLength$j = toLength$o; var createProperty$2 = createProperty$5; var getIterator$2 = getIterator$4; var getIteratorMethod$2 = getIteratorMethod$5; // `Array.from` method implementation // https://tc39.es/ecma262/#sec-array.from var arrayFrom$1 = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject$a(arrayLike); var C = typeof this == 'function' ? this : Array; var argumentsLength = arguments.length; var mapfn = argumentsLength > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var iteratorMethod = getIteratorMethod$2(O); var index = 0; var length, result, step, iterator, next, value; if (mapping) mapfn = bind$3(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); // if the target is not iterable or it's an array with the default iterator - use a simple case if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod$1(iteratorMethod))) { iterator = getIterator$2(O, iteratorMethod); next = iterator.next; result = new C(); for (;!(step = next.call(iterator)).done; index++) { value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value; createProperty$2(result, index, value); } } else { length = toLength$j(O.length); result = new C(length); for (;length > index; index++) { value = mapping ? mapfn(O[index], index) : O[index]; createProperty$2(result, index, value); } } result.length = index; return result; }; var $$n = _export; var from = arrayFrom$1; var checkCorrectnessOfIteration$2 = checkCorrectnessOfIteration$4; var INCORRECT_ITERATION = !checkCorrectnessOfIteration$2(function (iterable) { // eslint-disable-next-line es/no-array-from -- required for testing Array.from(iterable); }); // `Array.from` method // https://tc39.es/ecma262/#sec-array.from $$n({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, { from: from }); var toInteger$7 = toInteger$a; var toString$a = toString$d; var requireObjectCoercible$7 = requireObjectCoercible$a; // `String.prototype.codePointAt` methods implementation var createMethod$3 = function (CONVERT_TO_STRING) { return function ($this, pos) { var S = toString$a(requireObjectCoercible$7($this)); var position = toInteger$7(pos); var size = S.length; var first, second; if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; first = S.charCodeAt(position); return first < 0xD800 || first > 0xDBFF || position + 1 === size || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; }; }; var stringMultibyte = { // `String.prototype.codePointAt` method // https://tc39.es/ecma262/#sec-string.prototype.codepointat codeAt: createMethod$3(false), // `String.prototype.at` method // https://github.com/mathiasbynens/String.prototype.at charAt: createMethod$3(true) }; var fails$n = fails$B; var correctPrototypeGetter = !fails$n(function () { function F() { /* empty */ } F.prototype.constructor = null; // eslint-disable-next-line es/no-object-getprototypeof -- required for testing return Object.getPrototypeOf(new F()) !== F.prototype; }); var has$6 = has$g; var toObject$9 = toObject$g; var sharedKey = sharedKey$4; var CORRECT_PROTOTYPE_GETTER = correctPrototypeGetter; var IE_PROTO = sharedKey('IE_PROTO'); var ObjectPrototype$2 = Object.prototype; // `Object.getPrototypeOf` method // https://tc39.es/ecma262/#sec-object.getprototypeof // eslint-disable-next-line es/no-object-getprototypeof -- safe var objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) { O = toObject$9(O); if (has$6(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectPrototype$2 : null; }; var fails$m = fails$B; var getPrototypeOf$4 = objectGetPrototypeOf; var createNonEnumerableProperty$6 = createNonEnumerableProperty$c; var wellKnownSymbol$c = wellKnownSymbol$s; var ITERATOR$5 = wellKnownSymbol$c('iterator'); var BUGGY_SAFARI_ITERATORS$1 = false; // `%IteratorPrototype%` object // https://tc39.es/ecma262/#sec-%iteratorprototype%-object var IteratorPrototype$2, PrototypeOfArrayIteratorPrototype, arrayIterator; /* eslint-disable es/no-array-prototype-keys -- safe */ if ([].keys) { arrayIterator = [].keys(); // Safari 8 has buggy iterators w/o `next` if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS$1 = true; else { PrototypeOfArrayIteratorPrototype = getPrototypeOf$4(getPrototypeOf$4(arrayIterator)); if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype$2 = PrototypeOfArrayIteratorPrototype; } } var NEW_ITERATOR_PROTOTYPE = IteratorPrototype$2 == undefined || fails$m(function () { var test = {}; // FF44- legacy iterators case return IteratorPrototype$2[ITERATOR$5].call(test) !== test; }); if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype$2 = {}; // `%IteratorPrototype%[@@iterator]()` method // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator if (typeof IteratorPrototype$2[ITERATOR$5] !== 'function') { createNonEnumerableProperty$6(IteratorPrototype$2, ITERATOR$5, function () { return this; }); } var iteratorsCore = { IteratorPrototype: IteratorPrototype$2, BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS$1 }; var IteratorPrototype$1 = iteratorsCore.IteratorPrototype; var create$6 = objectCreate; var createPropertyDescriptor$2 = createPropertyDescriptor$7; var setToStringTag$5 = setToStringTag$9; var Iterators$2 = iterators; var returnThis$1 = function () { return this; }; var createIteratorConstructor$2 = function (IteratorConstructor, NAME, next) { var TO_STRING_TAG = NAME + ' Iterator'; IteratorConstructor.prototype = create$6(IteratorPrototype$1, { next: createPropertyDescriptor$2(1, next) }); setToStringTag$5(IteratorConstructor, TO_STRING_TAG, false); Iterators$2[TO_STRING_TAG] = returnThis$1; return IteratorConstructor; }; var $$m = _export; var createIteratorConstructor$1 = createIteratorConstructor$2; var getPrototypeOf$3 = objectGetPrototypeOf; var setPrototypeOf$5 = objectSetPrototypeOf; var setToStringTag$4 = setToStringTag$9; var createNonEnumerableProperty$5 = createNonEnumerableProperty$c; var redefine$7 = redefine$d.exports; var wellKnownSymbol$b = wellKnownSymbol$s; var Iterators$1 = iterators; var IteratorsCore = iteratorsCore; var IteratorPrototype = IteratorsCore.IteratorPrototype; var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; var ITERATOR$4 = wellKnownSymbol$b('iterator'); var KEYS = 'keys'; var VALUES = 'values'; var ENTRIES = 'entries'; var returnThis = function () { return this; }; var defineIterator$3 = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { createIteratorConstructor$1(IteratorConstructor, NAME, next); var getIterationMethod = function (KIND) { if (KIND === DEFAULT && defaultIterator) return defaultIterator; if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND]; switch (KIND) { case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; } return function () { return new IteratorConstructor(this); }; }; var TO_STRING_TAG = NAME + ' Iterator'; var INCORRECT_VALUES_NAME = false; var IterablePrototype = Iterable.prototype; var nativeIterator = IterablePrototype[ITERATOR$4] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT]; var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; var CurrentIteratorPrototype, methods, KEY; // fix native if (anyNativeIterator) { CurrentIteratorPrototype = getPrototypeOf$3(anyNativeIterator.call(new Iterable())); if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { if (getPrototypeOf$3(CurrentIteratorPrototype) !== IteratorPrototype) { if (setPrototypeOf$5) { setPrototypeOf$5(CurrentIteratorPrototype, IteratorPrototype); } else if (typeof CurrentIteratorPrototype[ITERATOR$4] != 'function') { createNonEnumerableProperty$5(CurrentIteratorPrototype, ITERATOR$4, returnThis); } } // Set @@toStringTag to native iterators setToStringTag$4(CurrentIteratorPrototype, TO_STRING_TAG, true); } } // fix Array.prototype.{ values, @@iterator }.name in V8 / FF if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { INCORRECT_VALUES_NAME = true; defaultIterator = function values() { return nativeIterator.call(this); }; } // define iterator if (IterablePrototype[ITERATOR$4] !== defaultIterator) { createNonEnumerableProperty$5(IterablePrototype, ITERATOR$4, defaultIterator); } Iterators$1[NAME] = defaultIterator; // export additional methods if (DEFAULT) { methods = { values: getIterationMethod(VALUES), keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), entries: getIterationMethod(ENTRIES) }; if (FORCED) for (KEY in methods) { if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { redefine$7(IterablePrototype, KEY, methods[KEY]); } } else $$m({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods); } return methods; }; var charAt$1 = stringMultibyte.charAt; var toString$9 = toString$d; var InternalStateModule$6 = internalState; var defineIterator$2 = defineIterator$3; var STRING_ITERATOR = 'String Iterator'; var setInternalState$6 = InternalStateModule$6.set; var getInternalState$4 = InternalStateModule$6.getterFor(STRING_ITERATOR); // `String.prototype[@@iterator]` method // https://tc39.es/ecma262/#sec-string.prototype-@@iterator defineIterator$2(String, 'String', function (iterated) { setInternalState$6(this, { type: STRING_ITERATOR, string: toString$9(iterated), index: 0 }); // `%StringIteratorPrototype%.next` method // https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next }, function next() { var state = getInternalState$4(this); var string = state.string; var index = state.index; var point; if (index >= string.length) return { value: undefined, done: true }; point = charAt$1(string, index); state.index += point.length; return { value: point, done: false }; }); var loglevel = {exports: {}}; (function (module) { (function (root, definition) { if (module.exports) { module.exports = definition(); } else { root.log = definition(); } })(commonjsGlobal, function () { var noop = function noop() {}; var undefinedType = "undefined"; var isIE = (typeof window === "undefined" ? "undefined" : _typeof$3(window)) !== undefinedType && _typeof$3(window.navigator) !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent); var logMethods = ["trace", "debug", "info", "warn", "error"]; // Cross-browser bind equivalent that works at least back to IE6 function bindMethod(obj, methodName) { var method = obj[methodName]; if (typeof method.bind === 'function') { return method.bind(obj); } else { try { return Function.prototype.bind.call(method, obj); } catch (e) { // Missing bind shim or IE8 + Modernizr, fallback to wrapping return function () { return Function.prototype.apply.apply(method, [obj, arguments]); }; } } } // Trace() doesn't print the message in IE, so for that case we need to wrap it function traceForIE() { if (console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { // In old IE, native console methods themselves don't have apply(). Function.prototype.apply.apply(console.log, [console, arguments]); } } if (console.trace) console.trace(); } // Build the best logging method possible for this env // Wherever possible we want to bind, not wrap, to preserve stack traces function realMethod(methodName) { if (methodName === 'debug') { methodName = 'log'; } if ((typeof console === "undefined" ? "undefined" : _typeof$3(console)) === undefinedType) { return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives } else if (methodName === 'trace' && isIE) { return traceForIE; } else if (console[methodName] !== undefined) { return bindMethod(console, methodName); } else if (console.log !== undefined) { return bindMethod(console, 'log'); } else { return noop; } } // These private functions always need `this` to be set properly function replaceLoggingMethods(level, loggerName) { /*jshint validthis:true */ for (var i = 0; i < logMethods.length; i++) { var methodName = logMethods[i]; this[methodName] = i < level ? noop : this.methodFactory(methodName, level, loggerName); } // Define log.log as an alias for log.debug this.log = this.debug; } // In old IE versions, the console isn't present until you first open it. // We build realMethod() replacements here that regenerate logging methods function enableLoggingWhenConsoleArrives(methodName, level, loggerName) { return function () { if ((typeof console === "undefined" ? "undefined" : _typeof$3(console)) !== undefinedType) { replaceLoggingMethods.call(this, level, loggerName); this[methodName].apply(this, arguments); } }; } // By default, we use closely bound real methods wherever possible, and // otherwise we wait for a console to appear, and then try again. function defaultMethodFactory(methodName, level, loggerName) { /*jshint validthis:true */ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments); } function Logger(name, defaultLevel, factory) { var self = this; var currentLevel; defaultLevel = defaultLevel == null ? "WARN" : defaultLevel; var storageKey = "loglevel"; if (typeof name === "string") { storageKey += ":" + name; } else if (_typeof$3(name) === "symbol") { storageKey = undefined; } function persistLevelIfPossible(levelNum) { var levelName = (logMethods[levelNum] || 'silent').toUpperCase(); if ((typeof window === "undefined" ? "undefined" : _typeof$3(window)) === undefinedType || !storageKey) return; // Use localStorage if available try { window.localStorage[storageKey] = levelName; return; } catch (ignore) {} // Use session cookie as fallback try { window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";"; } catch (ignore) {} } function getPersistedLevel() { var storedLevel; if ((typeof window === "undefined" ? "undefined" : _typeof$3(window)) === undefinedType || !storageKey) return; try { storedLevel = window.localStorage[storageKey]; } catch (ignore) {} // Fallback to cookies if local storage gives us nothing if (_typeof$3(storedLevel) === undefinedType) { try { var cookie = window.document.cookie; var location = cookie.indexOf(encodeURIComponent(storageKey) + "="); if (location !== -1) { storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1]; } } catch (ignore) {} } // If the stored level is not valid, treat it as if nothing was stored. if (self.levels[storedLevel] === undefined) { storedLevel = undefined; } return storedLevel; } function clearPersistedLevel() { if ((typeof window === "undefined" ? "undefined" : _typeof$3(window)) === undefinedType || !storageKey) return; // Use localStorage if available try { window.localStorage.removeItem(storageKey); return; } catch (ignore) {} // Use session cookie as fallback try { window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; } catch (ignore) {} } /* * * Public logger API - see https://github.com/pimterry/loglevel for details * */ self.name = name; self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, "ERROR": 4, "SILENT": 5 }; self.methodFactory = factory || defaultMethodFactory; self.getLevel = function () { return currentLevel; }; self.setLevel = function (level, persist) { if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) { level = self.levels[level.toUpperCase()]; } if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) { currentLevel = level; if (persist !== false) { // defaults to true persistLevelIfPossible(level); } replaceLoggingMethods.call(self, level, name); if ((typeof console === "undefined" ? "undefined" : _typeof$3(console)) === undefinedType && level < self.levels.SILENT) { return "No console available for logging"; } } else { throw "log.setLevel() called with invalid level: " + level; } }; self.setDefaultLevel = function (level) { defaultLevel = level; if (!getPersistedLevel()) { self.setLevel(level, false); } }; self.resetLevel = function () { self.setLevel(defaultLevel, false); clearPersistedLevel(); }; self.enableAll = function (persist) { self.setLevel(self.levels.TRACE, persist); }; self.disableAll = function (persist) { self.setLevel(self.levels.SILENT, persist); }; // Initialize with the right level var initialLevel = getPersistedLevel(); if (initialLevel == null) { initialLevel = defaultLevel; } self.setLevel(initialLevel, false); } /* * * Top-level API * */ var defaultLogger = new Logger(); var _loggersByName = {}; defaultLogger.getLogger = function getLogger(name) { if (_typeof$3(name) !== "symbol" && typeof name !== "string" || name === "") { throw new TypeError("You must supply a name when creating a logger."); } var logger = _loggersByName[name]; if (!logger) { logger = _loggersByName[name] = new Logger(name, defaultLogger.getLevel(), defaultLogger.methodFactory); } return logger; }; // Grab the current global log variable in case of overwrite var _log = (typeof window === "undefined" ? "undefined" : _typeof$3(window)) !== undefinedType ? window.log : undefined; defaultLogger.noConflict = function () { if ((typeof window === "undefined" ? "undefined" : _typeof$3(window)) !== undefinedType && window.log === defaultLogger) { window.log = _log; } return defaultLogger; }; defaultLogger.getLoggers = function getLoggers() { return _loggersByName; }; // ES6 default export, for compatibility defaultLogger['default'] = defaultLogger; return defaultLogger; }); })(loglevel); function prepareLine$1(prefix, args) { return ["".concat(new Date().toISOString(), " Conversations ").concat(prefix, ":")].concat(Array.from(args)); } var log$a = loglevel.exports.getLogger("twilio-conversations"); // twilio-conversations is used by Flex SDK. Please DO NOT change var Logger = /*#__PURE__*/function () { function Logger(prefix) { _classCallCheck$4(this, Logger); _defineProperty$3(this, "prefix", ""); this.prefix = prefix !== null && prefix !== undefined && prefix.length > 0 ? prefix + " " : ""; } _createClass$4(Logger, [{ key: "setLevel", value: function setLevel(level) { log$a.setLevel(level); } }, { key: "trace", value: function trace() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log$a.trace.apply(null, prepareLine$1(this.prefix + "T", args)); } }, { key: "debug", value: function debug() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } log$a.debug.apply(null, prepareLine$1(this.prefix + "D", args)); } }, { key: "info", value: function info() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } log$a.info.apply(null, prepareLine$1(this.prefix + "I", args)); } }, { key: "warn", value: function warn() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } log$a.warn.apply(null, prepareLine$1(this.prefix + "W", args)); } }, { key: "error", value: function error() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } log$a.error.apply(null, prepareLine$1(this.prefix + "E", args)); } }], [{ key: "scope", value: function scope(prefix) { return new Logger(prefix); } }, { key: "setLevel", value: function setLevel(level) { log$a.setLevel(level); } }, { key: "trace", value: function trace() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } log$a.trace.apply(null, prepareLine$1("T", args)); } }, { key: "debug", value: function debug() { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } log$a.debug.apply(null, prepareLine$1("D", args)); } }, { key: "info", value: function info() { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } log$a.info.apply(null, prepareLine$1("I", args)); } }, { key: "warn", value: function warn() { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { args[_key9] = arguments[_key9]; } log$a.warn.apply(null, prepareLine$1("W", args)); } }, { key: "error", value: function error() { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { args[_key10] = arguments[_key10]; } log$a.error.apply(null, prepareLine$1("E", args)); } }]); return Logger; }(); var lib = {}; var toSeconds_1; var parse_1; Object.defineProperty(lib, "__esModule", { value: true }); /** * @description A module for parsing ISO8601 durations */ /** * The pattern used for parsing ISO8601 duration (PnYnMnDTnHnMnS). * This does not cover the week format PnW. */ // PnYnMnDTnHnMnS var numbers = '\\d+(?:[\\.,]\\d+)?'; var weekPattern = '(' + numbers + 'W)'; var datePattern = '(' + numbers + 'Y)?(' + numbers + 'M)?(' + numbers + 'D)?'; var timePattern = 'T(' + numbers + 'H)?(' + numbers + 'M)?(' + numbers + 'S)?'; var iso8601 = 'P(?:' + weekPattern + '|' + datePattern + '(?:' + timePattern + ')?)'; var objMap = ['weeks', 'years', 'months', 'days', 'hours', 'minutes', 'seconds']; /** * The ISO8601 regex for matching / testing durations */ var pattern = lib.pattern = new RegExp(iso8601); /** Parse PnYnMnDTnHnMnS format to object * @param {string} durationString - PnYnMnDTnHnMnS formatted string * @return {Object} - With a property for each part of the pattern */ var parse = parse_1 = lib.parse = function parse(durationString) { // Slice away first entry in match-array return durationString.match(pattern).slice(1).reduce(function (prev, next, idx) { prev[objMap[idx]] = parseFloat(next) || 0; return prev; }, {}); }; /** * Convert ISO8601 duration object to an end Date. * * @param {Object} duration - The duration object * @param {Date} startDate - The starting Date for calculating the duration * @return {Date} - The resulting end Date */ var end = lib.end = function end(duration, startDate) { // Create two equal timestamps, add duration to 'then' and return time difference var timestamp = startDate ? startDate.getTime() : Date.now(); var then = new Date(timestamp); then.setFullYear(then.getFullYear() + duration.years); then.setMonth(then.getMonth() + duration.months); then.setDate(then.getDate() + duration.days); then.setHours(then.getHours() + duration.hours); then.setMinutes(then.getMinutes() + duration.minutes); // Then.setSeconds(then.getSeconds() + duration.seconds); then.setMilliseconds(then.getMilliseconds() + duration.seconds * 1000); // Special case weeks then.setDate(then.getDate() + duration.weeks * 7); return then; }; /** * Convert ISO8601 duration object to seconds * * @param {Object} duration - The duration object * @param {Date} startDate - The starting point for calculating the duration * @return {Number} */ var toSeconds = toSeconds_1 = lib.toSeconds = function toSeconds(duration, startDate) { var timestamp = startDate ? startDate.getTime() : Date.now(); var now = new Date(timestamp); var then = end(duration, now); var seconds = (then.getTime() - now.getTime()) / 1000; return seconds; }; lib.default = { end: end, toSeconds: toSeconds, pattern: pattern, parse: parse }; function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$6(Object(source), !0).forEach(function (key) { _defineProperty$3(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var TYPING_TIMEOUT = 5; var HTTP_CACHE_LIFETIME = "PT5S"; var CONSUMPTION_HORIZON_SENDING_INTERVAL = "PT5S"; var USER_INFOS_TO_SUBSCRIBE = 100; var MINIMUM_RETRY_DELAY$1 = 1000; var MAXIMUM_RETRY_DELAY$1 = 4000; var MAXIMUM_ATTEMPTS_COUNT = 3; var RETRY_WHEN_THROTTLED = true; var Configuration$1 = /*#__PURE__*/_createClass$4(function Configuration() { var _ref, _constructorOptions$u, _ref2, _constructorOptions$h, _ref3, _constructorOptions$c; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var configurationResponse = arguments.length > 1 ? arguments[1] : undefined; var logger = arguments.length > 2 ? arguments[2] : undefined; _classCallCheck$4(this, Configuration); _defineProperty$3(this, "typingIndicatorTimeoutDefault", TYPING_TIMEOUT * 1000); var constructorOptions = options.Chat || options.IPMessaging || options || {}; this.productId = constructorOptions.productId; this.links = { myConversations: configurationResponse.links.my_conversations, conversations: configurationResponse.links.conversations, users: configurationResponse.links.users, currentUser: configurationResponse.links.current_user, typing: configurationResponse.links.typing, mediaService: configurationResponse.links.media_service, mediaSetService: configurationResponse.links.media_set_service, messagesReceipts: configurationResponse.links.messages_receipts }; this.limits = { mediaAttachmentsCountLimit: configurationResponse.options.media_attachments_count_limit, mediaAttachmentSizeLimitInMb: configurationResponse.options.media_attachment_size_limit_in_mb, mediaAttachmentsTotalSizeLimitInMb: configurationResponse.options.media_attachments_total_size_limit_in_mb, emailHistoriesAllowedContentTypes: configurationResponse.options.email_histories_allowed_mime_types, emailBodiesAllowedContentTypes: configurationResponse.options.email_bodies_allowed_mime_types }; this.typingIndicatorTimeoutOverride = constructorOptions.typingIndicatorTimeoutOverride; this.backoffConfiguration = _objectSpread$6({ min: MINIMUM_RETRY_DELAY$1, max: MAXIMUM_RETRY_DELAY$1, maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT }, constructorOptions.backoffConfigOverride); this.retryWhenThrottled = constructorOptions.retryWhenThrottledOverride !== undefined ? constructorOptions.retryWhenThrottledOverride : RETRY_WHEN_THROTTLED; this.userInfosToSubscribe = (_ref = (_constructorOptions$u = constructorOptions.userInfosToSubscribeOverride) !== null && _constructorOptions$u !== void 0 ? _constructorOptions$u : configurationResponse.options.user_infos_to_subscribe) !== null && _ref !== void 0 ? _ref : USER_INFOS_TO_SUBSCRIBE; this.reachabilityEnabled = configurationResponse.options.reachability_enabled; this.userIdentity = configurationResponse.identity; this.userInfo = configurationResponse.sync_objects.my_user_info; this.myConversations = configurationResponse.sync_objects.my_conversations; var httpCacheInterval = (_ref2 = (_constructorOptions$h = constructorOptions.httpCacheIntervalOverride) !== null && _constructorOptions$h !== void 0 ? _constructorOptions$h : configurationResponse.options.http_cache_interval) !== null && _ref2 !== void 0 ? _ref2 : HTTP_CACHE_LIFETIME; try { this.httpCacheInterval = toSeconds_1(parse_1(httpCacheInterval)); } catch (_unused) { logger.error("Failed to parse http cache interval ".concat(httpCacheInterval, ", using default value ").concat(HTTP_CACHE_LIFETIME)); this.httpCacheInterval = toSeconds_1(parse_1(HTTP_CACHE_LIFETIME)); } var consumptionReportInterval = (_ref3 = (_constructorOptions$c = constructorOptions.consumptionReportIntervalOverride) !== null && _constructorOptions$c !== void 0 ? _constructorOptions$c : configurationResponse.options.consumption_report_interval) !== null && _ref3 !== void 0 ? _ref3 : CONSUMPTION_HORIZON_SENDING_INTERVAL; try { this.consumptionReportInterval = toSeconds_1(parse_1(consumptionReportInterval)); } catch (_unused2) { logger.error("Failed to parse consumption report interval ".concat(consumptionReportInterval, ", using default value ").concat(CONSUMPTION_HORIZON_SENDING_INTERVAL)); this.consumptionReportInterval = toSeconds_1(parse_1(CONSUMPTION_HORIZON_SENDING_INTERVAL)); } }); var wellKnownSymbol$a = wellKnownSymbol$s; var create$5 = objectCreate; var definePropertyModule$1 = objectDefineProperty; var UNSCOPABLES = wellKnownSymbol$a('unscopables'); var ArrayPrototype = Array.prototype; // Array.prototype[@@unscopables] // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables if (ArrayPrototype[UNSCOPABLES] == undefined) { definePropertyModule$1.f(ArrayPrototype, UNSCOPABLES, { configurable: true, value: create$5(null) }); } // add a key to Array.prototype[@@unscopables] var addToUnscopables$3 = function (key) { ArrayPrototype[UNSCOPABLES][key] = true; }; var toIndexedObject$4 = toIndexedObject$c; var addToUnscopables$2 = addToUnscopables$3; var Iterators = iterators; var InternalStateModule$5 = internalState; var defineIterator$1 = defineIterator$3; var ARRAY_ITERATOR = 'Array Iterator'; var setInternalState$5 = InternalStateModule$5.set; var getInternalState$3 = InternalStateModule$5.getterFor(ARRAY_ITERATOR); // `Array.prototype.entries` method // https://tc39.es/ecma262/#sec-array.prototype.entries // `Array.prototype.keys` method // https://tc39.es/ecma262/#sec-array.prototype.keys // `Array.prototype.values` method // https://tc39.es/ecma262/#sec-array.prototype.values // `Array.prototype[@@iterator]` method // https://tc39.es/ecma262/#sec-array.prototype-@@iterator // `CreateArrayIterator` internal method // https://tc39.es/ecma262/#sec-createarrayiterator var es_array_iterator = defineIterator$1(Array, 'Array', function (iterated, kind) { setInternalState$5(this, { type: ARRAY_ITERATOR, target: toIndexedObject$4(iterated), // target index: 0, // next index kind: kind // kind }); // `%ArrayIteratorPrototype%.next` method // https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next }, function () { var state = getInternalState$3(this); var target = state.target; var kind = state.kind; var index = state.index++; if (!target || index >= target.length) { state.target = undefined; return { value: undefined, done: true }; } if (kind == 'keys') return { value: index, done: false }; if (kind == 'values') return { value: target[index], done: false }; return { value: [index, target[index]], done: false }; }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% // https://tc39.es/ecma262/#sec-createunmappedargumentsobject // https://tc39.es/ecma262/#sec-createmappedargumentsobject Iterators.Arguments = Iterators.Array; // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables addToUnscopables$2('keys'); addToUnscopables$2('values'); addToUnscopables$2('entries'); var global$h = global$D; var DOMIterables = domIterables; var DOMTokenListPrototype = domTokenListPrototype; var ArrayIteratorMethods = es_array_iterator; var createNonEnumerableProperty$4 = createNonEnumerableProperty$c; var wellKnownSymbol$9 = wellKnownSymbol$s; var ITERATOR$3 = wellKnownSymbol$9('iterator'); var TO_STRING_TAG$1 = wellKnownSymbol$9('toStringTag'); var ArrayValues = ArrayIteratorMethods.values; var handlePrototype = function (CollectionPrototype, COLLECTION_NAME) { if (CollectionPrototype) { // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype[ITERATOR$3] !== ArrayValues) try { createNonEnumerableProperty$4(CollectionPrototype, ITERATOR$3, ArrayValues); } catch (error) { CollectionPrototype[ITERATOR$3] = ArrayValues; } if (!CollectionPrototype[TO_STRING_TAG$1]) { createNonEnumerableProperty$4(CollectionPrototype, TO_STRING_TAG$1, COLLECTION_NAME); } if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) { // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try { createNonEnumerableProperty$4(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]); } catch (error) { CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME]; } } } }; for (var COLLECTION_NAME in DOMIterables) { handlePrototype(global$h[COLLECTION_NAME] && global$h[COLLECTION_NAME].prototype, COLLECTION_NAME); } handlePrototype(DOMTokenListPrototype, 'DOMTokenList'); var $$l = _export; var getBuiltIn$1 = getBuiltIn$a; var fails$l = fails$B; var $stringify = getBuiltIn$1('JSON', 'stringify'); var re = /[\uD800-\uDFFF]/g; var low = /^[\uD800-\uDBFF]$/; var hi = /^[\uDC00-\uDFFF]$/; var fix = function (match, offset, string) { var prev = string.charAt(offset - 1); var next = string.charAt(offset + 1); if ((low.test(match) && !hi.test(next)) || (hi.test(match) && !low.test(prev))) { return '\\u' + match.charCodeAt(0).toString(16); } return match; }; var FORCED$5 = fails$l(function () { return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"' || $stringify('\uDEAD') !== '"\\udead"'; }); if ($stringify) { // `JSON.stringify` method // https://tc39.es/ecma262/#sec-json.stringify // https://github.com/tc39/proposal-well-formed-stringify $$l({ target: 'JSON', stat: true, forced: FORCED$5 }, { // eslint-disable-next-line no-unused-vars -- required for `.length` stringify: function stringify(it, replacer, space) { var result = $stringify.apply(null, arguments); return typeof result == 'string' ? result.replace(re, fix) : result; } }); } var isObject$b = isObject$p; var setPrototypeOf$4 = objectSetPrototypeOf; // makes subclassing work correct for wrapped built-ins var inheritIfRequired$3 = function ($this, dummy, Wrapper) { var NewTarget, NewTargetPrototype; if ( // it can work only with native `setPrototypeOf` setPrototypeOf$4 && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this typeof (NewTarget = dummy.constructor) == 'function' && NewTarget !== Wrapper && isObject$b(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype ) setPrototypeOf$4($this, NewTargetPrototype); return $this; }; // a string of all valid unicode whitespaces var whitespaces$1 = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' + '\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; var requireObjectCoercible$6 = requireObjectCoercible$a; var toString$8 = toString$d; var whitespaces = whitespaces$1; var whitespace = '[' + whitespaces + ']'; var ltrim = RegExp('^' + whitespace + whitespace + '*'); var rtrim = RegExp(whitespace + whitespace + '*$'); // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation var createMethod$2 = function (TYPE) { return function ($this) { var string = toString$8(requireObjectCoercible$6($this)); if (TYPE & 1) string = string.replace(ltrim, ''); if (TYPE & 2) string = string.replace(rtrim, ''); return string; }; }; var stringTrim = { // `String.prototype.{ trimLeft, trimStart }` methods // https://tc39.es/ecma262/#sec-string.prototype.trimstart start: createMethod$2(1), // `String.prototype.{ trimRight, trimEnd }` methods // https://tc39.es/ecma262/#sec-string.prototype.trimend end: createMethod$2(2), // `String.prototype.trim` method // https://tc39.es/ecma262/#sec-string.prototype.trim trim: createMethod$2(3) }; var DESCRIPTORS$9 = descriptors; var global$g = global$D; var isForced$1 = isForced_1; var redefine$6 = redefine$d.exports; var has$5 = has$g; var classof$5 = classofRaw$1; var inheritIfRequired$2 = inheritIfRequired$3; var isSymbol$1 = isSymbol$6; var toPrimitive = toPrimitive$2; var fails$k = fails$B; var create$4 = objectCreate; var getOwnPropertyNames$2 = objectGetOwnPropertyNames.f; var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; var defineProperty$8 = objectDefineProperty.f; var trim = stringTrim.trim; var NUMBER = 'Number'; var NativeNumber = global$g[NUMBER]; var NumberPrototype = NativeNumber.prototype; // Opera ~12 has broken Object#toString var BROKEN_CLASSOF = classof$5(create$4(NumberPrototype)) == NUMBER; // `ToNumber` abstract operation // https://tc39.es/ecma262/#sec-tonumber var toNumber = function (argument) { if (isSymbol$1(argument)) throw TypeError('Cannot convert a Symbol value to a number'); var it = toPrimitive(argument, 'number'); var first, third, radix, maxCode, digits, length, index, code; if (typeof it == 'string' && it.length > 2) { it = trim(it); first = it.charCodeAt(0); if (first === 43 || first === 45) { third = it.charCodeAt(2); if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix } else if (first === 48) { switch (it.charCodeAt(1)) { case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i default: return +it; } digits = it.slice(2); length = digits.length; for (index = 0; index < length; index++) { code = digits.charCodeAt(index); // parseInt parses a string to a first unavailable symbol // but ToNumber should return NaN if a string contains unavailable symbols if (code < 48 || code > maxCode) return NaN; } return parseInt(digits, radix); } } return +it; }; // `Number` constructor // https://tc39.es/ecma262/#sec-number-constructor if (isForced$1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { var NumberWrapper = function Number(value) { var it = arguments.length < 1 ? 0 : value; var dummy = this; return dummy instanceof NumberWrapper // check on 1..constructor(foo) case && (BROKEN_CLASSOF ? fails$k(function () { NumberPrototype.valueOf.call(dummy); }) : classof$5(dummy) != NUMBER) ? inheritIfRequired$2(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); }; for (var keys$1 = DESCRIPTORS$9 ? getOwnPropertyNames$2(NativeNumber) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES2015 (in case, if modules with ES2015 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,' + // ESNext 'fromString,range' ).split(','), j$1 = 0, key$1; keys$1.length > j$1; j$1++) { if (has$5(NativeNumber, key$1 = keys$1[j$1]) && !has$5(NumberWrapper, key$1)) { defineProperty$8(NumberWrapper, key$1, getOwnPropertyDescriptor$1(NativeNumber, key$1)); } } NumberWrapper.prototype = NumberPrototype; NumberPrototype.constructor = NumberWrapper; redefine$6(global$g, NUMBER, NumberWrapper); } var anObject$6 = anObject$k; // `RegExp.prototype.flags` getter implementation // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags var regexpFlags$1 = function () { var that = anObject$6(this); var result = ''; if (that.global) result += 'g'; if (that.ignoreCase) result += 'i'; if (that.multiline) result += 'm'; if (that.dotAll) result += 's'; if (that.unicode) result += 'u'; if (that.sticky) result += 'y'; return result; }; var regexpStickyHelpers = {}; var fails$j = fails$B; var global$f = global$D; // babel-minify and Closure Compiler transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError var $RegExp$2 = global$f.RegExp; regexpStickyHelpers.UNSUPPORTED_Y = fails$j(function () { var re = $RegExp$2('a', 'y'); re.lastIndex = 2; return re.exec('abcd') != null; }); regexpStickyHelpers.BROKEN_CARET = fails$j(function () { // https://bugzilla.mozilla.org/show_bug.cgi?id=773687 var re = $RegExp$2('^r', 'gy'); re.lastIndex = 2; return re.exec('str') != null; }); var fails$i = fails$B; var global$e = global$D; // babel-minify and Closure Compiler transpiles RegExp('.', 's') -> /./s and it causes SyntaxError var $RegExp$1 = global$e.RegExp; var regexpUnsupportedDotAll = fails$i(function () { var re = $RegExp$1('.', 's'); return !(re.dotAll && re.exec('\n') && re.flags === 's'); }); var fails$h = fails$B; var global$d = global$D; // babel-minify and Closure Compiler transpiles RegExp('(?b)', 'g') -> /(?b)/g and it causes SyntaxError var $RegExp = global$d.RegExp; var regexpUnsupportedNcg = fails$h(function () { var re = $RegExp('(?b)', 'g'); return re.exec('b').groups.a !== 'b' || 'b'.replace(re, '$c') !== 'bc'; }); /* eslint-disable regexp/no-empty-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */ /* eslint-disable regexp/no-useless-quantifier -- testing */ var toString$7 = toString$d; var regexpFlags = regexpFlags$1; var stickyHelpers$1 = regexpStickyHelpers; var shared = shared$5.exports; var create$3 = objectCreate; var getInternalState$2 = internalState.get; var UNSUPPORTED_DOT_ALL = regexpUnsupportedDotAll; var UNSUPPORTED_NCG = regexpUnsupportedNcg; var nativeExec = RegExp.prototype.exec; var nativeReplace = shared('native-string-replace', String.prototype.replace); var patchedExec = nativeExec; var UPDATES_LAST_INDEX_WRONG = (function () { var re1 = /a/; var re2 = /b*/g; nativeExec.call(re1, 'a'); nativeExec.call(re2, 'a'); return re1.lastIndex !== 0 || re2.lastIndex !== 0; })(); var UNSUPPORTED_Y$1 = stickyHelpers$1.UNSUPPORTED_Y || stickyHelpers$1.BROKEN_CARET; // nonparticipating capturing group, copied from es5-shim's String#split patch. var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$1 || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG; if (PATCH) { // eslint-disable-next-line max-statements -- TODO patchedExec = function exec(string) { var re = this; var state = getInternalState$2(re); var str = toString$7(string); var raw = state.raw; var result, reCopy, lastIndex, match, i, object, group; if (raw) { raw.lastIndex = re.lastIndex; result = patchedExec.call(raw, str); re.lastIndex = raw.lastIndex; return result; } var groups = state.groups; var sticky = UNSUPPORTED_Y$1 && re.sticky; var flags = regexpFlags.call(re); var source = re.source; var charsAdded = 0; var strCopy = str; if (sticky) { flags = flags.replace('y', ''); if (flags.indexOf('g') === -1) { flags += 'g'; } strCopy = str.slice(re.lastIndex); // Support anchored sticky behavior. if (re.lastIndex > 0 && (!re.multiline || re.multiline && str.charAt(re.lastIndex - 1) !== '\n')) { source = '(?: ' + source + ')'; strCopy = ' ' + strCopy; charsAdded++; } // ^(? + rx + ) is needed, in combination with some str slicing, to // simulate the 'y' flag. reCopy = new RegExp('^(?:' + source + ')', flags); } if (NPCG_INCLUDED) { reCopy = new RegExp('^' + source + '$(?!\\s)', flags); } if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; match = nativeExec.call(sticky ? reCopy : re, strCopy); if (sticky) { if (match) { match.input = match.input.slice(charsAdded); match[0] = match[0].slice(charsAdded); match.index = re.lastIndex; re.lastIndex += match[0].length; } else re.lastIndex = 0; } else if (UPDATES_LAST_INDEX_WRONG && match) { re.lastIndex = re.global ? match.index + match[0].length : lastIndex; } if (NPCG_INCLUDED && match && match.length > 1) { // Fix browsers whose `exec` methods don't consistently return `undefined` // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ nativeReplace.call(match[0], reCopy, function () { for (i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undefined) match[i] = undefined; } }); } if (match && groups) { match.groups = object = create$3(null); for (i = 0; i < groups.length; i++) { group = groups[i]; object[group[0]] = match[group[1]]; } } return match; }; } var regexpExec$3 = patchedExec; var $$k = _export; var exec = regexpExec$3; // `RegExp.prototype.exec` method // https://tc39.es/ecma262/#sec-regexp.prototype.exec $$k({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, { exec: exec }); // TODO: Remove from `core-js@4` since it's moved to entry points var redefine$5 = redefine$d.exports; var regexpExec$2 = regexpExec$3; var fails$g = fails$B; var wellKnownSymbol$8 = wellKnownSymbol$s; var createNonEnumerableProperty$3 = createNonEnumerableProperty$c; var SPECIES$1 = wellKnownSymbol$8('species'); var RegExpPrototype$1 = RegExp.prototype; var fixRegexpWellKnownSymbolLogic = function (KEY, exec, FORCED, SHAM) { var SYMBOL = wellKnownSymbol$8(KEY); var DELEGATES_TO_SYMBOL = !fails$g(function () { // String methods call symbol-named RegEp methods var O = {}; O[SYMBOL] = function () { return 7; }; return ''[KEY](O) != 7; }); var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails$g(function () { // Symbol-named RegExp methods call .exec var execCalled = false; var re = /a/; if (KEY === 'split') { // We can't use real regex here since it causes deoptimization // and serious performance degradation in V8 // https://github.com/zloirock/core-js/issues/306 re = {}; // RegExp[@@split] doesn't call the regex's exec method, but first creates // a new one. We need to return the patched regex when creating the new one. re.constructor = {}; re.constructor[SPECIES$1] = function () { return re; }; re.flags = ''; re[SYMBOL] = /./[SYMBOL]; } re.exec = function () { execCalled = true; return null; }; re[SYMBOL](''); return !execCalled; }); if ( !DELEGATES_TO_SYMBOL || !DELEGATES_TO_EXEC || FORCED ) { var nativeRegExpMethod = /./[SYMBOL]; var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { var $exec = regexp.exec; if ($exec === regexpExec$2 || $exec === RegExpPrototype$1.exec) { if (DELEGATES_TO_SYMBOL && !forceStringMethod) { // The native String method already delegates to @@method (this // polyfilled function), leasing to infinite recursion. // We avoid it by directly calling the native @@method method. return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) }; } return { done: true, value: nativeMethod.call(str, regexp, arg2) }; } return { done: false }; }); redefine$5(String.prototype, KEY, methods[0]); redefine$5(RegExpPrototype$1, SYMBOL, methods[1]); } if (SHAM) createNonEnumerableProperty$3(RegExpPrototype$1[SYMBOL], 'sham', true); }; var charAt = stringMultibyte.charAt; // `AdvanceStringIndex` abstract operation // https://tc39.es/ecma262/#sec-advancestringindex var advanceStringIndex$3 = function (S, index, unicode) { return index + (unicode ? charAt(S, index).length : 1); }; var toObject$8 = toObject$g; var floor$6 = Math.floor; var replace$1 = ''.replace; var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g; var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g; // `GetSubstitution` abstract operation // https://tc39.es/ecma262/#sec-getsubstitution var getSubstitution$1 = function (matched, str, position, captures, namedCaptures, replacement) { var tailPos = position + matched.length; var m = captures.length; var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; if (namedCaptures !== undefined) { namedCaptures = toObject$8(namedCaptures); symbols = SUBSTITUTION_SYMBOLS; } return replace$1.call(replacement, symbols, function (match, ch) { var capture; switch (ch.charAt(0)) { case '$': return '$'; case '&': return matched; case '`': return str.slice(0, position); case "'": return str.slice(tailPos); case '<': capture = namedCaptures[ch.slice(1, -1)]; break; default: // \d\d? var n = +ch; if (n === 0) return match; if (n > m) { var f = floor$6(n / 10); if (f === 0) return match; if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); return match; } capture = captures[n - 1]; } return capture === undefined ? '' : capture; }); }; var classof$4 = classofRaw$1; var regexpExec$1 = regexpExec$3; // `RegExpExec` abstract operation // https://tc39.es/ecma262/#sec-regexpexec var regexpExecAbstract = function (R, S) { var exec = R.exec; if (typeof exec === 'function') { var result = exec.call(R, S); if (typeof result !== 'object') { throw TypeError('RegExp exec method returned something other than an Object or null'); } return result; } if (classof$4(R) !== 'RegExp') { throw TypeError('RegExp#exec called on incompatible receiver'); } return regexpExec$1.call(R, S); }; var fixRegExpWellKnownSymbolLogic$3 = fixRegexpWellKnownSymbolLogic; var fails$f = fails$B; var anObject$5 = anObject$k; var toInteger$6 = toInteger$a; var toLength$i = toLength$o; var toString$6 = toString$d; var requireObjectCoercible$5 = requireObjectCoercible$a; var advanceStringIndex$2 = advanceStringIndex$3; var getSubstitution = getSubstitution$1; var regExpExec$2 = regexpExecAbstract; var wellKnownSymbol$7 = wellKnownSymbol$s; var REPLACE = wellKnownSymbol$7('replace'); var max$2 = Math.max; var min$5 = Math.min; var maybeToString = function (it) { return it === undefined ? it : String(it); }; // IE <= 11 replaces $0 with the whole match, as if it was $& // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0 var REPLACE_KEEPS_$0 = (function () { // eslint-disable-next-line regexp/prefer-escape-replacement-dollar-char -- required for testing return 'a'.replace(/./, '$0') === '$0'; })(); // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () { if (/./[REPLACE]) { return /./[REPLACE]('a', '$0') === ''; } return false; })(); var REPLACE_SUPPORTS_NAMED_GROUPS = !fails$f(function () { var re = /./; re.exec = function () { var result = []; result.groups = { a: '7' }; return result; }; // eslint-disable-next-line regexp/no-useless-dollar-replacements -- false positive return ''.replace(re, '$') !== '7'; }); // @@replace logic fixRegExpWellKnownSymbolLogic$3('replace', function (_, nativeReplace, maybeCallNative) { var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; return [ // `String.prototype.replace` method // https://tc39.es/ecma262/#sec-string.prototype.replace function replace(searchValue, replaceValue) { var O = requireObjectCoercible$5(this); var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(toString$6(O), searchValue, replaceValue); }, // `RegExp.prototype[@@replace]` method // https://tc39.es/ecma262/#sec-regexp.prototype-@@replace function (string, replaceValue) { var rx = anObject$5(this); var S = toString$6(string); if ( typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1 && replaceValue.indexOf('$<') === -1 ) { var res = maybeCallNative(nativeReplace, rx, S, replaceValue); if (res.done) return res.value; } var functionalReplace = typeof replaceValue === 'function'; if (!functionalReplace) replaceValue = toString$6(replaceValue); var global = rx.global; if (global) { var fullUnicode = rx.unicode; rx.lastIndex = 0; } var results = []; while (true) { var result = regExpExec$2(rx, S); if (result === null) break; results.push(result); if (!global) break; var matchStr = toString$6(result[0]); if (matchStr === '') rx.lastIndex = advanceStringIndex$2(S, toLength$i(rx.lastIndex), fullUnicode); } var accumulatedResult = ''; var nextSourcePosition = 0; for (var i = 0; i < results.length; i++) { result = results[i]; var matched = toString$6(result[0]); var position = max$2(min$5(toInteger$6(result.index), S.length), 0); var captures = []; // NOTE: This is equivalent to // captures = result.slice(1).map(maybeToString) // but for some reason `nativeSlice.call(result, 1, result.length)` (called in // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); var namedCaptures = result.groups; if (functionalReplace) { var replacerArgs = [matched].concat(captures, position, S); if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); var replacement = toString$6(replaceValue.apply(undefined, replacerArgs)); } else { replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); } if (position >= nextSourcePosition) { accumulatedResult += S.slice(nextSourcePosition, position) + replacement; nextSourcePosition = position + matched.length; } } return accumulatedResult + S.slice(nextSourcePosition); } ]; }, !REPLACE_SUPPORTS_NAMED_GROUPS || !REPLACE_KEEPS_$0 || REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE); var $$j = _export; var IndexedObject$2 = indexedObject; var toIndexedObject$3 = toIndexedObject$c; var arrayMethodIsStrict$2 = arrayMethodIsStrict$4; var nativeJoin = [].join; var ES3_STRINGS = IndexedObject$2 != Object; var STRICT_METHOD$2 = arrayMethodIsStrict$2('join', ','); // `Array.prototype.join` method // https://tc39.es/ecma262/#sec-array.prototype.join $$j({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$2 }, { join: function join(separator) { return nativeJoin.call(toIndexedObject$3(this), separator === undefined ? ',' : separator); } }); /** * Deep-clone an object. Note that this does not work on object containing * functions. * @param {object} obj - the object to deep-clone * @returns {object} */ function deepClone$1(obj) { return JSON.parse(JSON.stringify(obj)); } function parseToNumber(value) { if (typeof value !== "undefined" && !isNaN(Number(value))) { return Number(value); } return null; } // timeString cannot be typed `string` because in member.ts // call to parseTime(data.lastReadTimestamp) uses number not a string for timestamp. function parseTime(timeString) { try { return new Date(timeString); } catch (e) { return null; } } function parseAttributes(rawAttributes, warningMessage, log) { var attributes = {}; if (rawAttributes) { try { attributes = JSON.parse(rawAttributes); } catch (e) { log.warn(warningMessage, e); } } return attributes; } /** * Construct URI with query parameters */ var UriBuilder$1 = /*#__PURE__*/function () { function UriBuilder(base) { _classCallCheck$4(this, UriBuilder); this.base = base.replace(/\/$/, ""); this.args = []; this.paths = []; } _createClass$4(UriBuilder, [{ key: "arg", value: function arg(name, value) { if (typeof value !== "undefined") { this.args.push(encodeURIComponent(name) + "=" + encodeURIComponent(value)); } return this; } }, { key: "path", value: function path(name) { this.paths.push(encodeURIComponent(name)); return this; } }, { key: "build", value: function build() { var result = this.base; if (this.paths.length) { result += "/" + this.paths.join("/"); } if (this.args.length) { result += "?" + this.args.join("&"); } return result; } }]); return UriBuilder; }(); var browser$7 = {}; var $$i = _export; var isObject$a = isObject$p; var isArray = isArray$4; var toAbsoluteIndex$4 = toAbsoluteIndex$6; var toLength$h = toLength$o; var toIndexedObject$2 = toIndexedObject$c; var createProperty$1 = createProperty$5; var wellKnownSymbol$6 = wellKnownSymbol$s; var arrayMethodHasSpeciesSupport$1 = arrayMethodHasSpeciesSupport$5; var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport$1('slice'); var SPECIES = wellKnownSymbol$6('species'); var nativeSlice = [].slice; var max$1 = Math.max; // `Array.prototype.slice` method // https://tc39.es/ecma262/#sec-array.prototype.slice // fallback for not array-like ES3 strings and DOM objects $$i({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 }, { slice: function slice(start, end) { var O = toIndexedObject$2(this); var length = toLength$h(O.length); var k = toAbsoluteIndex$4(start, length); var fin = toAbsoluteIndex$4(end === undefined ? length : end, length); // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible var Constructor, result, n; if (isArray(O)) { Constructor = O.constructor; // cross-realm fallback if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) { Constructor = undefined; } else if (isObject$a(Constructor)) { Constructor = Constructor[SPECIES]; if (Constructor === null) Constructor = undefined; } if (Constructor === Array || Constructor === undefined) { return nativeSlice.call(O, k, fin); } } result = new (Constructor === undefined ? Array : Constructor)(max$1(fin - k, 0)); for (n = 0; k < fin; k++, n++) if (k in O) createProperty$1(result, n, O[k]); result.length = n; return result; } }); // TODO: Remove from `core-js@4` since it's moved to entry points var $$h = _export; var isObject$9 = isObject$p; var DELEGATES_TO_EXEC = function () { var execCalled = false; var re = /[ac]/; re.exec = function () { execCalled = true; return /./.exec.apply(this, arguments); }; return re.test('abc') === true && execCalled; }(); var nativeTest = /./.test; // `RegExp.prototype.test` method // https://tc39.es/ecma262/#sec-regexp.prototype.test $$h({ target: 'RegExp', proto: true, forced: !DELEGATES_TO_EXEC }, { test: function (str) { if (typeof this.exec !== 'function') { return nativeTest.call(this, str); } var result = this.exec(str); if (result !== null && !isObject$9(result)) { throw new Error('RegExp exec method returned something other than an Object or null'); } return !!result; } }); var $$g = _export; var DESCRIPTORS$8 = descriptors; var global$c = global$D; var has$4 = has$g; var isObject$8 = isObject$p; var defineProperty$7 = objectDefineProperty.f; var copyConstructorProperties = copyConstructorProperties$2; var NativeSymbol = global$c.Symbol; if (DESCRIPTORS$8 && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || // Safari 12 bug NativeSymbol().description !== undefined )) { var EmptyStringDescriptionStore = {}; // wrap Symbol constructor for correct work with undefined description var SymbolWrapper = function Symbol() { var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]); var result = this instanceof SymbolWrapper ? new NativeSymbol(description) // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)' : description === undefined ? NativeSymbol() : NativeSymbol(description); if (description === '') EmptyStringDescriptionStore[result] = true; return result; }; copyConstructorProperties(SymbolWrapper, NativeSymbol); var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype; symbolPrototype.constructor = SymbolWrapper; var symbolToString = symbolPrototype.toString; var nativeSymbol = String(NativeSymbol('test')) == 'Symbol(test)'; var regexp = /^Symbol\((.*)\)[^)]+$/; defineProperty$7(symbolPrototype, 'description', { configurable: true, get: function description() { var symbol = isObject$8(this) ? this.valueOf() : this; var string = symbolToString.call(symbol); if (has$4(EmptyStringDescriptionStore, symbol)) return ''; var desc = nativeSymbol ? string.slice(7, -1) : string.replace(regexp, '$1'); return desc === '' ? undefined : desc; } }); $$g({ global: true, forced: true }, { Symbol: SymbolWrapper }); } var defineWellKnownSymbol = defineWellKnownSymbol$2; // `Symbol.iterator` well-known symbol // https://tc39.es/ecma262/#sec-symbol.iterator defineWellKnownSymbol('iterator'); var _typeof$2 = {exports: {}}; (function (module) { function _typeof(obj) { "@babel/helpers - typeof"; return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj); } module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; })(_typeof$2); var DESCRIPTORS$7 = descriptors; var defineProperty$6 = objectDefineProperty.f; var FunctionPrototype = Function.prototype; var FunctionPrototypeToString = FunctionPrototype.toString; var nameRE = /^\s*function ([^ (]*)/; var NAME$1 = 'name'; // Function instances `.name` property // https://tc39.es/ecma262/#sec-function-instances-name if (DESCRIPTORS$7 && !(NAME$1 in FunctionPrototype)) { defineProperty$6(FunctionPrototype, NAME$1, { configurable: true, get: function () { try { return FunctionPrototypeToString.call(this).match(nameRE)[1]; } catch (error) { return ''; } } }); } var slicedToArray = {exports: {}}; var arrayWithHoles = {exports: {}}; (function (module) { function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; })(arrayWithHoles); var iterableToArrayLimit = {exports: {}}; (function (module) { function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports; })(iterableToArrayLimit); var unsupportedIterableToArray = {exports: {}}; var arrayLikeToArray = {exports: {}}; (function (module) { function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; })(arrayLikeToArray); (function (module) { var arrayLikeToArray$1 = arrayLikeToArray.exports; function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray$1(o, minLen); } module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; })(unsupportedIterableToArray); var nonIterableRest = {exports: {}}; (function (module) { function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports; })(nonIterableRest); (function (module) { var arrayWithHoles$1 = arrayWithHoles.exports; var iterableToArrayLimit$1 = iterableToArrayLimit.exports; var unsupportedIterableToArray$1 = unsupportedIterableToArray.exports; var nonIterableRest$1 = nonIterableRest.exports; function _slicedToArray(arr, i) { return arrayWithHoles$1(arr) || iterableToArrayLimit$1(arr, i) || unsupportedIterableToArray$1(arr, i) || nonIterableRest$1(); } module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; })(slicedToArray); var toConsumableArray = {exports: {}}; var arrayWithoutHoles = {exports: {}}; (function (module) { var arrayLikeToArray$1 = arrayLikeToArray.exports; function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return arrayLikeToArray$1(arr); } module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; })(arrayWithoutHoles); var iterableToArray = {exports: {}}; (function (module) { function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; })(iterableToArray); var nonIterableSpread = {exports: {}}; (function (module) { function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports; })(nonIterableSpread); (function (module) { var arrayWithoutHoles$1 = arrayWithoutHoles.exports; var iterableToArray$1 = iterableToArray.exports; var unsupportedIterableToArray$1 = unsupportedIterableToArray.exports; var nonIterableSpread$1 = nonIterableSpread.exports; function _toConsumableArray(arr) { return arrayWithoutHoles$1(arr) || iterableToArray$1(arr) || unsupportedIterableToArray$1(arr) || nonIterableSpread$1(); } module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports; })(toConsumableArray); var createClass = {exports: {}}; (function (module) { function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; })(createClass); var classCallCheck = {exports: {}}; (function (module) { function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports; })(classCallCheck); var inherits = {exports: {}}; var setPrototypeOf$3 = {exports: {}}; (function (module) { function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }, module.exports.__esModule = true, module.exports["default"] = module.exports; return _setPrototypeOf(o, p); } module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; })(setPrototypeOf$3); (function (module) { var setPrototypeOf = setPrototypeOf$3.exports; function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) setPrototypeOf(subClass, superClass); } module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports; })(inherits); var possibleConstructorReturn = {exports: {}}; var assertThisInitialized = {exports: {}}; (function (module) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports; })(assertThisInitialized); (function (module) { var _typeof = _typeof$2.exports["default"]; var assertThisInitialized$1 = assertThisInitialized.exports; function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return assertThisInitialized$1(self); } module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports; })(possibleConstructorReturn); var getPrototypeOf$2 = {exports: {}}; (function (module) { function _getPrototypeOf(o) { module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }, module.exports.__esModule = true, module.exports["default"] = module.exports; return _getPrototypeOf(o); } module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; })(getPrototypeOf$2); var $$f = _export; var $includes$1 = arrayIncludes.includes; var addToUnscopables$1 = addToUnscopables$3; // `Array.prototype.includes` method // https://tc39.es/ecma262/#sec-array.prototype.includes $$f({ target: 'Array', proto: true }, { includes: function includes(el /* , fromIndex = 0 */) { return $includes$1(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables addToUnscopables$1('includes'); var isObject$7 = isObject$p; var floor$5 = Math.floor; // `Number.isInteger` method implementation // https://tc39.es/ecma262/#sec-number.isinteger var isInteger$3 = function isInteger(it) { return !isObject$7(it) && isFinite(it) && floor$5(it) === it; }; var $$e = _export; var isInteger$2 = isInteger$3; // `Number.isInteger` method // https://tc39.es/ecma262/#sec-number.isinteger $$e({ target: 'Number', stat: true }, { isInteger: isInteger$2 }); var DESCRIPTORS$6 = descriptors; var objectKeys$1 = objectKeys$4; var toIndexedObject$1 = toIndexedObject$c; var propertyIsEnumerable = objectPropertyIsEnumerable.f; // `Object.{ entries, values }` methods implementation var createMethod$1 = function (TO_ENTRIES) { return function (it) { var O = toIndexedObject$1(it); var keys = objectKeys$1(O); var length = keys.length; var i = 0; var result = []; var key; while (length > i) { key = keys[i++]; if (!DESCRIPTORS$6 || propertyIsEnumerable.call(O, key)) { result.push(TO_ENTRIES ? [key, O[key]] : O[key]); } } return result; }; }; var objectToArray = { // `Object.entries` method // https://tc39.es/ecma262/#sec-object.entries entries: createMethod$1(true), // `Object.values` method // https://tc39.es/ecma262/#sec-object.values values: createMethod$1(false) }; var $$d = _export; var $entries = objectToArray.entries; // `Object.entries` method // https://tc39.es/ecma262/#sec-object.entries $$d({ target: 'Object', stat: true }, { entries: function entries(O) { return $entries(O); } }); Object.defineProperty(browser$7, '__esModule', { value: true }); var _typeof$1 = _typeof$2.exports; var _slicedToArray$2 = slicedToArray.exports; var _toConsumableArray$2 = toConsumableArray.exports; var _createClass$3 = createClass.exports; var _classCallCheck$3 = classCallCheck.exports; var _inherits$3 = inherits.exports; var _possibleConstructorReturn$3 = possibleConstructorReturn.exports; var _getPrototypeOf$3 = getPrototypeOf$2.exports; function _interopDefaultLegacy$5(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } var _typeof__default$1 = /*#__PURE__*/_interopDefaultLegacy$5(_typeof$1); var _slicedToArray__default$1 = /*#__PURE__*/_interopDefaultLegacy$5(_slicedToArray$2); var _toConsumableArray__default$1 = /*#__PURE__*/_interopDefaultLegacy$5(_toConsumableArray$2); var _createClass__default$3 = /*#__PURE__*/_interopDefaultLegacy$5(_createClass$3); var _classCallCheck__default$3 = /*#__PURE__*/_interopDefaultLegacy$5(_classCallCheck$3); var _inherits__default$3 = /*#__PURE__*/_interopDefaultLegacy$5(_inherits$3); var _possibleConstructorReturn__default$3 = /*#__PURE__*/_interopDefaultLegacy$5(_possibleConstructorReturn$3); var _getPrototypeOf__default$3 = /*#__PURE__*/_interopDefaultLegacy$5(_getPrototypeOf$3); var custom = function custom() { for (var _len = arguments.length, checks = new Array(_len), _key = 0; _key < _len; _key++) { checks[_key] = arguments[_key]; } return { checks: checks }; }; function _createForOfIteratorHelper$4$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$4$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$4$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4$1(o, minLen); } function _arrayLikeToArray$4$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var type = function type() { for (var _len = arguments.length, checks = new Array(_len), _key = 0; _key < _len; _key++) { checks[_key] = arguments[_key]; } return custom(function (value) { var isValid = false; var expectedTypes = []; var _iterator = _createForOfIteratorHelper$4$1(checks), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _type = _step.value; if (typeof _type === "string") { isValid = isValid || _typeof__default$1["default"](value) === _type; expectedTypes.push("of type ".concat(_type)); continue; } isValid = isValid || value instanceof _type; expectedTypes.push("an instance of ".concat(_type.name)); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return [isValid, expectedTypes]; }); }; function _createForOfIteratorHelper$3$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$3$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$3$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3$1(o, minLen); } function _arrayLikeToArray$3$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var literal = function literal() { for (var _len = arguments.length, checks = new Array(_len), _key = 0; _key < _len; _key++) { checks[_key] = arguments[_key]; } return custom(function (value) { var isValid = false; var expectedTypes = []; var _iterator = _createForOfIteratorHelper$3$1(checks), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var type = _step.value; isValid = isValid || value === type; expectedTypes.push(typeof type === "string" ? "\"".concat(type, "\"") : "".concat(type)); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return [isValid, expectedTypes]; }); }; function _createSuper$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function _createSuperInternal() { var Super = _getPrototypeOf__default$3["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default$3["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default$3["default"](this, result); }; } function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _createForOfIteratorHelper$2$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$2$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2$2(o, minLen); } function _arrayLikeToArray$2$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var runtimeTypeValidation = function runtimeTypeValidation(rules, values) { if (values.length > rules.length) { throw new Error("Expected at most ".concat(rules.length, " argument(s), but got ").concat(values.length)); } while (values.length < rules.length) { values.push(undefined); } var _iterator = _createForOfIteratorHelper$2$2(values.entries()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _step$value = _slicedToArray__default$1["default"](_step.value, 2), index = _step$value[0], value = _step$value[1]; var _validateValue = validateValue(rules[index], value), _validateValue2 = _slicedToArray__default$1["default"](_validateValue, 4), isValid = _validateValue2[0], received = _validateValue2[1], expected = _validateValue2[2], delimeter = _validateValue2[3]; if (isValid) { continue; } var argumentIndex = index + 1; throw new Error("Argument ".concat(argumentIndex, " is expected to be ").concat(expected).concat(delimeter, " but got ").concat(received)); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } }; var stringifyReceivedType = function stringifyReceivedType(value) { var _value$constructor; var receivedType; var types = ["undefined", "boolean", "number", "bigint", "string"]; if (types.includes(_typeof__default$1["default"](value))) { receivedType = typeof value === "string" ? "\"".concat(value, "\"") : "".concat(value); } if (_typeof__default$1["default"](value) === "object" && (value === null || value === void 0 ? void 0 : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) !== "Object") { var _value$constructor2; receivedType = value === null ? "null" : "instance of ".concat(value === null || value === void 0 ? void 0 : (_value$constructor2 = value.constructor) === null || _value$constructor2 === void 0 ? void 0 : _value$constructor2.name); } if (!receivedType) { receivedType = _typeof__default$1["default"](value); } return receivedType; }; /* eslint-disable @typescript-eslint/no-explicit-any */ var validateConstructorTypes = function validateConstructorTypes() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var finalRuleSet = convertRuleArguments(args); return function (ctor) { return /*#__PURE__*/function (_ctor) { _inherits__default$3["default"](_class, _ctor); var _super = _createSuper$c(_class); function _class() { _classCallCheck__default$3["default"](this, _class); for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } runtimeTypeValidation(finalRuleSet, args); return _super.call.apply(_super, [this].concat(args)); } return _createClass__default$3["default"](_class); }(ctor); }; }; /* eslint-enable @typescript-eslint/no-explicit-any */ var validateTypes = function validateTypes() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } var finalRuleSet = convertRuleArguments(args); return function (target, propertyKey, descriptor) { if (typeof descriptor.value !== "function") { throw new Error("The validateTypes decorator can only be applied to methods"); } var originalMethod = descriptor.value; descriptor.value = function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } runtimeTypeValidation(finalRuleSet, args); return originalMethod.apply(this, args); }; }; }; var validateTypesAsync = function validateTypesAsync() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } var finalRuleSet = convertRuleArguments(args); return function (target, propertyKey, descriptor) { if (typeof descriptor.value !== "function") { throw new Error("The validateTypesAsync decorator can only be applied to methods"); } var originalMethod = descriptor.value; descriptor.value = function () { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } try { runtimeTypeValidation(finalRuleSet, args); } catch (e) { return Promise.reject(e); } return originalMethod.apply(this, args); }; }; }; var convertRuleArguments = function convertRuleArguments(args) { var finalRuleDefinitionSet = []; var _iterator2 = _createForOfIteratorHelper$2$2(args), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var arg = _step2.value; finalRuleDefinitionSet.push(convertRuleArgument(arg)); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return finalRuleDefinitionSet; }; var convertRuleArgument = function convertRuleArgument(arg) { var finalArgumentRuleDefinitions = []; var declaredRules = Array.isArray(arg) ? arg : [arg]; var _iterator3 = _createForOfIteratorHelper$2$2(declaredRules), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var rule = _step3.value; if (typeof rule === "string" || typeof rule === "function") { finalArgumentRuleDefinitions.push(type(rule)); continue; } finalArgumentRuleDefinitions.push(rule); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return finalArgumentRuleDefinitions; }; var validateValue = function validateValue(ruleDefinitions, value) { var expectedTypes = []; var customReceivedType; var isValid = false; var _iterator4 = _createForOfIteratorHelper$2$2(ruleDefinitions), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var definition = _step4.value; var _iterator5 = _createForOfIteratorHelper$2$2(definition.checks), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var check = _step5.value; var _check = check(value), _check2 = _slicedToArray__default$1["default"](_check, 3), checkPassed = _check2[0], typeDescription = _check2[1], _receivedType = _check2[2]; isValid = isValid || checkPassed; if (!customReceivedType && _receivedType) { customReceivedType = _receivedType; } if (typeDescription) { expectedTypes = typeof typeDescription === "string" ? [].concat(_toConsumableArray__default$1["default"](expectedTypes), [typeDescription]) : [].concat(_toConsumableArray__default$1["default"](expectedTypes), _toConsumableArray__default$1["default"](typeDescription)); } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } if (isValid) { return [true]; } var receivedType = customReceivedType || stringifyReceivedType(value); var lastIndex = expectedTypes.length - 1; var expectedTypesString = lastIndex > 0 ? "".concat(expectedTypes.slice(0, lastIndex).join(", "), " or ").concat(expectedTypes[lastIndex]) : expectedTypes.join(", "); return [false, receivedType, expectedTypesString, lastIndex > 1 ? ";" : ","]; }; function _createForOfIteratorHelper$1$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$1$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1$2(o, minLen); } function _arrayLikeToArray$1$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var nonEmptyArray = function nonEmptyArray(name, rules) { return custom(function (value) { if (!Array.isArray(value) || value.length < 1) { return [false, "a non-empty array of ".concat(name)]; } var _iterator = _createForOfIteratorHelper$1$2(value.entries()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _step$value = _slicedToArray__default$1["default"](_step.value, 2), key = _step$value[0], valueOfKey = _step$value[1]; var _validateValue = validateValue(convertRuleArgument(rules), valueOfKey), _validateValue2 = _slicedToArray__default$1["default"](_validateValue, 3), isValid = _validateValue2[0], received = _validateValue2[1], expected = _validateValue2[2]; if (!isValid) { return [false, "a valid non-empty array of ".concat(name, " (index ").concat(key, " should be ").concat(expected, ")"), "malformed array of ".concat(name, " (index ").concat(key, " is ").concat(received, ")")]; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return [true]; }); }; var nonEmptyString = custom(function (value) { return [typeof value === "string" && value.length > 0, "a non-empty string"]; }); var nonNegativeInteger = custom(function (value) { return [typeof value === "number" && Number.isInteger(value) && value >= 0, "a non-negative integer"]; }); var pureObject = custom(function (value) { return [_typeof__default$1["default"](value) === "object" && value !== null && !Array.isArray(value), "a pure object (non-null and non-array)"]; }); var objectSchema = function objectSchema(name, schema) { return custom(function (object) { if (_typeof__default$1["default"](object) !== "object" || object === null || Array.isArray(object)) { return [false, "valid ".concat(name, " (should be a pure object)")]; } for (var _i = 0, _Object$entries = Object.entries(schema); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray__default$1["default"](_Object$entries[_i], 2), key = _Object$entries$_i[0], rules = _Object$entries$_i[1]; var _validateValue = validateValue(convertRuleArgument(rules), object[key]), _validateValue2 = _slicedToArray__default$1["default"](_validateValue, 3), isValid = _validateValue2[0], received = _validateValue2[1], expected = _validateValue2[2]; if (!isValid) { return [false, "valid ".concat(name, " (key \"").concat(key, "\" should be ").concat(expected, ")"), "malformed ".concat(name, " (key \"").concat(key, "\" is ").concat(received, ")")]; } } return [true]; }); }; function _createForOfIteratorHelper$6(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$7(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$7(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$7(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$7(o, minLen); } function _arrayLikeToArray$7(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var array = function array(name, rules) { return custom(function (value) { if (!Array.isArray(value)) { return [false, "an array of ".concat(name)]; } var _iterator = _createForOfIteratorHelper$6(value.entries()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _step$value = _slicedToArray__default$1["default"](_step.value, 2), key = _step$value[0], valueOfKey = _step$value[1]; var _validateValue = validateValue(convertRuleArgument(rules), valueOfKey), _validateValue2 = _slicedToArray__default$1["default"](_validateValue, 3), isValid = _validateValue2[0], received = _validateValue2[1], expected = _validateValue2[2]; if (!isValid) { return [false, "a valid array of ".concat(name, " (index ").concat(key, " should be ").concat(expected, ")"), "malformed array of ".concat(name, " (index ").concat(key, " is ").concat(received, ")")]; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return [true]; }); }; var array_1 = browser$7.array = array; var custom_1 = browser$7.custom = custom; var literal_1 = browser$7.literal = literal; var nonEmptyArray_1 = browser$7.nonEmptyArray = nonEmptyArray; var nonEmptyString_1 = browser$7.nonEmptyString = nonEmptyString; var nonNegativeInteger_1 = browser$7.nonNegativeInteger = nonNegativeInteger; var objectSchema_1 = browser$7.objectSchema = objectSchema; var pureObject_1 = browser$7.pureObject = pureObject; browser$7.runtimeTypeValidation = runtimeTypeValidation; browser$7.stringifyReceivedType = stringifyReceivedType; browser$7.type = type; var validateConstructorTypes_1 = browser$7.validateConstructorTypes = validateConstructorTypes; var validateTypes_1 = browser$7.validateTypes = validateTypes; var validateTypesAsync_1 = browser$7.validateTypesAsync = validateTypesAsync; function _arrayLikeToArray$6(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$6(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$6(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$6(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$6(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray$1(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$6(arr) || _nonIterableSpread(); } var json = custom_1(function (value) { return [["string", "number", "boolean", "object"].includes(_typeof$3(value)), "a JSON type"]; }); var optionalJson = custom_1(function (value) { return [["undefined", "string", "number", "boolean", "object"].includes(_typeof$3(value)), "an optional JSON type"]; }); var sendMediaOptions = objectSchema_1("send media options", { contentType: [literal_1(null), "string"], filename: ["string", "undefined"], media: [literal_1("null"), "string"].concat(_toConsumableArray$1(typeof Buffer === "function" ? [Buffer] : []), _toConsumableArray$1(typeof Blob === "function" ? [Blob] : [])) }); var browser$6 = {}; var get$1 = {exports: {}}; var superPropBase = {exports: {}}; (function (module) { var getPrototypeOf = getPrototypeOf$2.exports; function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = getPrototypeOf(object); if (object === null) break; } return object; } module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports; })(superPropBase); (function (module) { var superPropBase$1 = superPropBase.exports; function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { module.exports = _get = Reflect.get, module.exports.__esModule = true, module.exports["default"] = module.exports; } else { module.exports = _get = function _get(target, property, receiver) { var base = superPropBase$1(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }, module.exports.__esModule = true, module.exports["default"] = module.exports; } return _get.apply(this, arguments); } module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports; })(get$1); var defineProperty$5 = {exports: {}}; (function (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; })(defineProperty$5); Object.defineProperty(browser$6, '__esModule', { value: true }); var _toConsumableArray = toConsumableArray.exports; var _classCallCheck$2 = classCallCheck.exports; var _createClass$2 = createClass.exports; var _assertThisInitialized$2 = assertThisInitialized.exports; var _get$1 = get$1.exports; var _inherits$2 = inherits.exports; var _possibleConstructorReturn$2 = possibleConstructorReturn.exports; var _getPrototypeOf$2 = getPrototypeOf$2.exports; var _defineProperty$2 = defineProperty$5.exports; function _interopDefaultLegacy$4(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy$4(_toConsumableArray); var _classCallCheck__default$2 = /*#__PURE__*/_interopDefaultLegacy$4(_classCallCheck$2); var _createClass__default$2 = /*#__PURE__*/_interopDefaultLegacy$4(_createClass$2); var _assertThisInitialized__default$2 = /*#__PURE__*/_interopDefaultLegacy$4(_assertThisInitialized$2); var _get__default$1 = /*#__PURE__*/_interopDefaultLegacy$4(_get$1); var _inherits__default$2 = /*#__PURE__*/_interopDefaultLegacy$4(_inherits$2); var _possibleConstructorReturn__default$2 = /*#__PURE__*/_interopDefaultLegacy$4(_possibleConstructorReturn$2); var _getPrototypeOf__default$2 = /*#__PURE__*/_interopDefaultLegacy$4(_getPrototypeOf$2); var _defineProperty__default$2 = /*#__PURE__*/_interopDefaultLegacy$4(_defineProperty$2); var domain$2; // This constructor is used to store event handlers. Instantiating this is // faster than explicitly calling `Object.create(null)` to get a "clean" empty // object (tested with v8 v4.9). function EventHandlers$2() {} EventHandlers$2.prototype = Object.create(null); function EventEmitter$2() { EventEmitter$2.init.call(this); } // nodejs oddity // require('events') === require('events').EventEmitter EventEmitter$2.EventEmitter = EventEmitter$2; EventEmitter$2.usingDomains = false; EventEmitter$2.prototype.domain = undefined; EventEmitter$2.prototype._events = undefined; EventEmitter$2.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter$2.defaultMaxListeners = 10; EventEmitter$2.init = function () { this.domain = null; if (EventEmitter$2.usingDomains) { // if there is an active domain, then attach to it. if (domain$2.active) ; } if (!this._events || this._events === Object.getPrototypeOf(this)._events) { this._events = new EventHandlers$2(); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter$2.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners$2(that) { if (that._maxListeners === undefined) return EventEmitter$2.defaultMaxListeners; return that._maxListeners; } EventEmitter$2.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners$2(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone$2(handler, isFn, self) { if (isFn) handler.call(self);else { var len = handler.length; var listeners = arrayClone$2(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self); } } } function emitOne$2(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1);else { var len = handler.length; var listeners = arrayClone$2(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1); } } } function emitTwo$2(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2);else { var len = handler.length; var listeners = arrayClone$2(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2); } } } function emitThree$2(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3);else { var len = handler.length; var listeners = arrayClone$2(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2, arg3); } } } function emitMany$2(handler, isFn, self, args) { if (isFn) handler.apply(self, args);else { var len = handler.length; var listeners = arrayClone$2(handler, len); for (var i = 0; i < len; ++i) { listeners[i].apply(self, args); } } } EventEmitter$2.prototype.emit = function emit(type) { var er, handler, len, args, i, events, domain; var doError = type === 'error'; events = this._events; if (events) doError = doError && events.error == null;else if (!doError) return false; domain = this.domain; // If there is no 'error' event listener then throw. if (doError) { er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); er.domainEmitter = this; er.domain = domain; er.domainThrown = false; domain.emit('error', er); } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone$2(handler, isFn, this); break; case 2: emitOne$2(handler, isFn, this, arguments[1]); break; case 3: emitTwo$2(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree$2(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) { args[i - 1] = arguments[i]; } emitMany$2(handler, isFn, this, args); } return true; }; function _addListener$2(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = new EventHandlers$2(); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners$2(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; emitWarning$2(w); } } } return target; } function emitWarning$2(e) { typeof console.warn === 'function' ? console.warn(e) : console.log(e); } EventEmitter$2.prototype.addListener = function addListener(type, listener) { return _addListener$2(this, type, listener, false); }; EventEmitter$2.prototype.on = EventEmitter$2.prototype.addListener; EventEmitter$2.prototype.prependListener = function prependListener(type, listener) { return _addListener$2(this, type, listener, true); }; function _onceWrap$2(target, type, listener) { var fired = false; function g() { target.removeListener(type, g); if (!fired) { fired = true; listener.apply(target, arguments); } } g.listener = listener; return g; } EventEmitter$2.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap$2(this, type, listener)); return this; }; EventEmitter$2.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap$2(this, type, listener)); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter$2.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener && list.listener === listener) { if (--this._eventsCount === 0) this._events = new EventHandlers$2();else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (list.length === 1) { list[0] = undefined; if (--this._eventsCount === 0) { this._events = new EventHandlers$2(); return this; } else { delete events[type]; } } else { spliceOne$2(list, position); } if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; // Alias for removeListener added in NodeJS 10.0 // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener EventEmitter$2.prototype.off = function (type, listener) { return this.removeListener(type, listener); }; EventEmitter$2.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = new EventHandlers$2(); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = new EventHandlers$2();else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); for (var i = 0, key; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = new EventHandlers$2(); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order do { this.removeListener(type, listeners[listeners.length - 1]); } while (listeners[0]); } return this; }; EventEmitter$2.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = [];else { evlistener = events[type]; if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners$2(evlistener); } return ret; }; EventEmitter$2.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount$2.call(emitter, type); } }; EventEmitter$2.prototype.listenerCount = listenerCount$2; function listenerCount$2(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter$2.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne$2(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; } list.pop(); } function arrayClone$2(arr, i) { var copy = new Array(i); while (i--) { copy[i] = arr[i]; } return copy; } function unwrapListeners$2(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf__default$2["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default$2["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default$2["default"](this, result); }; } function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ReplayEventEmitter = /*#__PURE__*/function (_EventEmitter) { _inherits__default$2["default"](ReplayEventEmitter, _EventEmitter); var _super = _createSuper$b(ReplayEventEmitter); function ReplayEventEmitter() { var _this; _classCallCheck__default$2["default"](this, ReplayEventEmitter); _this = _super.call(this); _defineProperty__default$2["default"](_assertThisInitialized__default$2["default"](_this), "eventHistory", new Map()); return _this; } _createClass__default$2["default"](ReplayEventEmitter, [{ key: "on", value: function on(event, listener) { return _get__default$1["default"](_getPrototypeOf__default$2["default"](ReplayEventEmitter.prototype), "on", this).call(this, event, listener); } }, { key: "once", value: function once(event, listener) { return _get__default$1["default"](_getPrototypeOf__default$2["default"](ReplayEventEmitter.prototype), "once", this).call(this, event, listener); } }, { key: "off", value: function off(event, listener) { return _get__default$1["default"](_getPrototypeOf__default$2["default"](ReplayEventEmitter.prototype), "off", this).call(this, event, listener); } }, { key: "emit", value: function emit(event) { var _get2; for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } this.eventHistory.set(event, args); return (_get2 = _get__default$1["default"](_getPrototypeOf__default$2["default"](ReplayEventEmitter.prototype), "emit", this)).call.apply(_get2, [this, event].concat(args)); } }, { key: "addListener", value: function addListener(event, listener) { return _get__default$1["default"](_getPrototypeOf__default$2["default"](ReplayEventEmitter.prototype), "addListener", this).call(this, event, listener); } }, { key: "removeListener", value: function removeListener(event, listener) { return _get__default$1["default"](_getPrototypeOf__default$2["default"](ReplayEventEmitter.prototype), "removeListener", this).call(this, event, listener); } }, { key: "addListenerWithReplay", value: function addListenerWithReplay(event, listener) { var historyEntry = this.eventHistory.get(event); if (historyEntry !== undefined) { listener.apply(void 0, _toConsumableArray__default["default"](historyEntry)); } return this.addListener(event, listener); } }, { key: "onWithReplay", value: function onWithReplay(event, listener) { return this.addListenerWithReplay(event, listener); } }, { key: "onceWithReplay", value: function onceWithReplay(event, listener) { var historyEntry = this.eventHistory.get(event); if (historyEntry !== undefined) { listener.apply(void 0, _toConsumableArray__default["default"](historyEntry)); return this; } return _get__default$1["default"](_getPrototypeOf__default$2["default"](ReplayEventEmitter.prototype), "once", this).call(this, event, listener); } }]); return ReplayEventEmitter; }(EventEmitter$2); var ReplayEventEmitter_1 = browser$6.ReplayEventEmitter = ReplayEventEmitter; var lodash_isequal = {exports: {}}; (function (module, exports) { /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `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 to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = _typeof$3(commonjsGlobal) == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; /** Detect free variable `self`. */ var freeSelf = (typeof self === "undefined" ? "undefined" : _typeof$3(self)) == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = function () { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }(); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * 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; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.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; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.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); }; } /** * 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); } /** * 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]; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function (value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function (arg) { return func(transform(arg)); }; } /** * 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; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect methods masquerading as native. */ var maskSrcKey = function () { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? 'Symbol(src)_1.' + uid : ''; }(); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, _Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash(), 'map': new (Map || ListCache)(), 'string': new Hash() }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache(); while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache(); this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties. isIndex(key, length)))) { result.push(key); } } return result; } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack()); return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack()); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack()); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * 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; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function (othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == other + ''; case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } 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; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function (object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function (symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { getTag = function getTag(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * 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) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length; } /** * 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$3(value); return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == 'function' && Ctor.prototype || objectProto; return value === proto; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return func + ''; } catch (e) {} } return ''; } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || value !== value && other !== other; } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function () { return arguments; }()) ? baseIsArguments : function (value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * 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); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = _typeof$3(value); return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && _typeof$3(value) == 'object'; } /** * 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; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = isEqual; })(lodash_isequal, lodash_isequal.exports); var isEqual = lodash_isequal.exports; function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var log$9 = Logger.scope("User"); /** * Extended user information. * Note that `isOnline` and `isNotifiable` properties are eligible * for use only if the reachability function is enabled. * You may check if it is enabled by reading the value of {@link Client.reachabilityEnabled}. */ var User = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(User, _ReplayEventEmitter); var _super = _createSuper$a(User); /** * @internal */ function User(identity, entityName, configuration, services) { var _this; _classCallCheck$4(this, User); _this = _super.call(this); _defineProperty$3(_assertThisInitialized$3(_this), "promiseToFetch", null); _defineProperty$3(_assertThisInitialized$3(_this), "updated", "updated"); _defineProperty$3(_assertThisInitialized$3(_this), "userSubscribed", "userSubscribed"); _defineProperty$3(_assertThisInitialized$3(_this), "userUnsubscribed", "userUnsubscribed"); _this.services = services; _this.subscribed = "initializing"; _this.setMaxListeners(0); _this.state = { identity: identity, entityName: entityName, friendlyName: null, attributes: {}, online: null, notifiable: null }; _this._initializationPromise = new Promise(function (resolve) { _this._resolveInitializationPromise = resolve; }); if (configuration !== null) { _this._resolveInitialization(configuration, identity, entityName, false); } return _this; } /** * Fired when the properties or the reachability status of the message has been updated. * * Parameters: * 1. object `data` - info object provided with the event. It has the following properties: * * {@link User} `user` - the user in question * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update * @event */ _createClass$4(User, [{ key: "identity", get: /** * User identity. */ function get() { return this.state.identity; }, set: function set(identity) { this.state.identity = identity; } }, { key: "entityName", set: function set(name) { this.state.entityName = name; } /** * Custom attributes of the user. */ }, { key: "attributes", get: function get() { return this.state.attributes; } /** * Friendly name of the user, null if not set. */ }, { key: "friendlyName", get: function get() { return this.state.friendlyName; } /** * Status of the real-time conversation connection of the user. */ }, { key: "isOnline", get: function get() { return this.state.online; } /** * User push notification registration status. */ }, { key: "isNotifiable", get: function get() { return this.state.notifiable; } /** * True if this user is receiving real-time status updates. */ }, { key: "isSubscribed", get: function get() { return this.subscribed == "subscribed"; } // Handles service updates }, { key: "_update", value: function () { var _update2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(key, value) { var updateReasons, updateAttributes; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this._initializationPromise; case 2: updateReasons = []; log$9.debug("User for", this.state.identity, "updated:", key, value); _context.t0 = key; _context.next = _context.t0 === "friendlyName" ? 7 : _context.t0 === "attributes" ? 9 : _context.t0 === "reachability" ? 12 : 15; break; case 7: if (this.state.friendlyName !== value.value) { updateReasons.push("friendlyName"); this.state.friendlyName = value.value; } return _context.abrupt("break", 16); case 9: updateAttributes = parseAttributes(value.value, "Retrieved malformed attributes from the server for user: ".concat(this.state.identity), log$9); if (!isEqual(this.state.attributes, updateAttributes)) { this.state.attributes = updateAttributes; updateReasons.push("attributes"); } return _context.abrupt("break", 16); case 12: if (this.state.online !== value.online) { this.state.online = value.online; updateReasons.push("reachabilityOnline"); } if (this.state.notifiable !== value.notifiable) { this.state.notifiable = value.notifiable; updateReasons.push("reachabilityNotifiable"); } return _context.abrupt("break", 16); case 15: return _context.abrupt("return"); case 16: if (updateReasons.length > 0) { this.emit("updated", { user: this, updateReasons: updateReasons }); } case 17: case "end": return _context.stop(); } } }, _callee, this); })); function _update(_x, _x2) { return _update2.apply(this, arguments); } return _update; }() // Fetch reachability info }, { key: "_updateReachabilityInfo", value: function () { var _updateReachabilityInfo2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2(map, update) { var _this2 = this; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this._initializationPromise; case 2: if (this.configuration.reachabilityEnabled) { _context2.next = 4; break; } return _context2.abrupt("return", Promise.resolve()); case 4: return _context2.abrupt("return", map.get("reachability").then(update).catch(function (err) { log$9.warn("Failed to get reachability info for ", _this2.state.identity, err); })); case 5: case "end": return _context2.stop(); } } }, _callee2, this); })); function _updateReachabilityInfo(_x3, _x4) { return _updateReachabilityInfo2.apply(this, arguments); } return _updateReachabilityInfo; }() // Fetch user }, { key: "_fetch", value: function () { var _fetch2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3() { var _this3 = this; return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this._initializationPromise; case 2: if (this.state.entityName) { _context3.next = 4; break; } return _context3.abrupt("return", this); case 4: this.promiseToFetch = this.services.syncClient.map({ id: this.state.entityName, mode: "open_existing", includeItems: true }).then(function (map) { _this3.entity = map; map.on("itemUpdated", function (args) { log$9.debug(_this3.state.entityName + " (" + _this3.state.identity + ") itemUpdated: " + args.item.key); return _this3._update(args.item.key, args.item.data); }); return Promise.all([map.get("friendlyName").then(function (item) { return _this3._update(item.key, item.data); }), map.get("attributes").then(function (item) { return _this3._update(item.key, item.data); }), _this3._updateReachabilityInfo(map, function (item) { return _this3._update(item.key, item.data); })]); }).then(function () { log$9.debug("Fetched for", _this3.identity); _this3.subscribed = "subscribed"; _this3.emit("userSubscribed", _this3); return _this3; }).catch(function (err) { _this3.promiseToFetch = null; throw err; }); return _context3.abrupt("return", this.promiseToFetch); case 6: case "end": return _context3.stop(); } } }, _callee3, this); })); function _fetch() { return _fetch2.apply(this, arguments); } return _fetch; }() }, { key: "_ensureFetched", value: function () { var _ensureFetched2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee4() { return _regeneratorRuntime$1.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._initializationPromise; case 2: return _context4.abrupt("return", this.promiseToFetch || this._fetch()); case 3: case "end": return _context4.stop(); } } }, _callee4, this); })); function _ensureFetched() { return _ensureFetched2.apply(this, arguments); } return _ensureFetched; }() /** * Edit user attributes. * @param attributes New attributes. */ }, { key: "updateAttributes", value: function () { var _updateAttributes = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee5(attributes) { return _regeneratorRuntime$1.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this._initializationPromise; case 2: if (!(this.subscribed == "unsubscribed")) { _context5.next = 4; break; } throw new Error("Can't modify unsubscribed object"); case 4: _context5.next = 6; return this.services.commandExecutor.mutateResource("post", this.links.self, { attributes: JSON.stringify(attributes) }); case 6: return _context5.abrupt("return", this); case 7: case "end": return _context5.stop(); } } }, _callee5, this); })); function updateAttributes(_x5) { return _updateAttributes.apply(this, arguments); } return updateAttributes; }() /** * Update the friendly name of the user. * @param friendlyName New friendly name. */ }, { key: "updateFriendlyName", value: function () { var _updateFriendlyName = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee6(friendlyName) { return _regeneratorRuntime$1.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return this._initializationPromise; case 2: if (!(this.subscribed == "unsubscribed")) { _context6.next = 4; break; } throw new Error("Can't modify unsubscribed object"); case 4: _context6.next = 6; return this.services.commandExecutor.mutateResource("post", this.links.self, { friendly_name: friendlyName }); case 6: return _context6.abrupt("return", this); case 7: case "end": return _context6.stop(); } } }, _callee6, this); })); function updateFriendlyName(_x6) { return _updateFriendlyName.apply(this, arguments); } return updateFriendlyName; }() /** * Remove the user from the subscription list. * @return A promise of completion. */ }, { key: "unsubscribe", value: function () { var _unsubscribe = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee7() { return _regeneratorRuntime$1.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return this._initializationPromise; case 2: if (!this.promiseToFetch) { _context7.next = 9; break; } _context7.next = 5; return this.promiseToFetch; case 5: this.entity.close(); this.promiseToFetch = null; this.subscribed = "unsubscribed"; this.emit("userUnsubscribed", this); case 9: case "end": return _context7.stop(); } } }, _callee7, this); })); function unsubscribe() { return _unsubscribe.apply(this, arguments); } return unsubscribe; }() }, { key: "_resolveInitialization", value: function _resolveInitialization(configuration, identity, entityName, emitUpdated) { this.configuration = configuration; this.identity = identity; this.entityName = entityName; this.links = { self: "".concat(this.configuration.links.users, "/").concat(encodeURIComponent(this.identity)) }; this._resolveInitializationPromise(); if (emitUpdated) { this.emit("updated", { user: this, updateReasons: ["friendlyName", "attributes", "reachabilityOnline", "reachabilityNotifiable"] }); } } }]); return User; }(ReplayEventEmitter_1); __decorate$1([validateTypesAsync_1(json), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Promise)], User.prototype, "updateAttributes", null); __decorate$1([validateTypesAsync_1(["string"]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], User.prototype, "updateFriendlyName", null); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray$1(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$6(arr, i) || _nonIterableRest(); } var internalMetadata = {exports: {}}; var fails$e = fails$B; var freezing = !fails$e(function () { // eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- required for testing return Object.isExtensible(Object.preventExtensions({})); }); var $$c = _export; var hiddenKeys = hiddenKeys$6; var isObject$6 = isObject$p; var has$3 = has$g; var defineProperty$4 = objectDefineProperty.f; var getOwnPropertyNamesModule = objectGetOwnPropertyNames; var getOwnPropertyNamesExternalModule = objectGetOwnPropertyNamesExternal; var uid$1 = uid$5; var FREEZING$1 = freezing; var REQUIRED = false; var METADATA = uid$1('meta'); var id = 0; // eslint-disable-next-line es/no-object-isextensible -- safe var isExtensible = Object.isExtensible || function () { return true; }; var setMetadata = function (it) { defineProperty$4(it, METADATA, { value: { objectID: 'O' + id++, // object ID weakData: {} // weak collections IDs } }); }; var fastKey$1 = function (it, create) { // return a primitive with prefix if (!isObject$6(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has$3(it, METADATA)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMetadata(it); // return object ID } return it[METADATA].objectID; }; var getWeakData = function (it, create) { if (!has$3(it, METADATA)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMetadata(it); // return the store of weak collections IDs } return it[METADATA].weakData; }; // add metadata on freeze-family methods calling var onFreeze$1 = function (it) { if (FREEZING$1 && REQUIRED && isExtensible(it) && !has$3(it, METADATA)) setMetadata(it); return it; }; var enable = function () { meta.enable = function () { /* empty */ }; REQUIRED = true; var getOwnPropertyNames = getOwnPropertyNamesModule.f; var splice = [].splice; var test = {}; test[METADATA] = 1; // prevent exposing of metadata key if (getOwnPropertyNames(test).length) { getOwnPropertyNamesModule.f = function (it) { var result = getOwnPropertyNames(it); for (var i = 0, length = result.length; i < length; i++) { if (result[i] === METADATA) { splice.call(result, i, 1); break; } } return result; }; $$c({ target: 'Object', stat: true, forced: true }, { getOwnPropertyNames: getOwnPropertyNamesExternalModule.f }); } }; var meta = internalMetadata.exports = { enable: enable, fastKey: fastKey$1, getWeakData: getWeakData, onFreeze: onFreeze$1 }; hiddenKeys[METADATA] = true; var $$b = _export; var global$b = global$D; var isForced = isForced_1; var redefine$4 = redefine$d.exports; var InternalMetadataModule = internalMetadata.exports; var iterate$1 = iterate$3; var anInstance$5 = anInstance$7; var isObject$5 = isObject$p; var fails$d = fails$B; var checkCorrectnessOfIteration$1 = checkCorrectnessOfIteration$4; var setToStringTag$3 = setToStringTag$9; var inheritIfRequired$1 = inheritIfRequired$3; var collection$2 = function (CONSTRUCTOR_NAME, wrapper, common) { var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1; var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1; var ADDER = IS_MAP ? 'set' : 'add'; var NativeConstructor = global$b[CONSTRUCTOR_NAME]; var NativePrototype = NativeConstructor && NativeConstructor.prototype; var Constructor = NativeConstructor; var exported = {}; var fixMethod = function (KEY) { var nativeMethod = NativePrototype[KEY]; redefine$4(NativePrototype, KEY, KEY == 'add' ? function add(value) { nativeMethod.call(this, value === 0 ? 0 : value); return this; } : KEY == 'delete' ? function (key) { return IS_WEAK && !isObject$5(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); } : KEY == 'get' ? function get(key) { return IS_WEAK && !isObject$5(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key); } : KEY == 'has' ? function has(key) { return IS_WEAK && !isObject$5(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); } : function set(key, value) { nativeMethod.call(this, key === 0 ? 0 : key, value); return this; } ); }; var REPLACE = isForced( CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails$d(function () { new NativeConstructor().entries().next(); })) ); if (REPLACE) { // create collection constructor Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); InternalMetadataModule.enable(); } else if (isForced(CONSTRUCTOR_NAME, true)) { var instance = new Constructor(); // early implementations not supports chaining var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false var THROWS_ON_PRIMITIVES = fails$d(function () { instance.has(1); }); // most early implementations doesn't supports iterables, most modern - not close it correctly // eslint-disable-next-line no-new -- required for testing var ACCEPT_ITERABLES = checkCorrectnessOfIteration$1(function (iterable) { new NativeConstructor(iterable); }); // for early implementations -0 and +0 not the same var BUGGY_ZERO = !IS_WEAK && fails$d(function () { // V8 ~ Chromium 42- fails only with 5+ elements var $instance = new NativeConstructor(); var index = 5; while (index--) $instance[ADDER](index, index); return !$instance.has(-0); }); if (!ACCEPT_ITERABLES) { Constructor = wrapper(function (dummy, iterable) { anInstance$5(dummy, Constructor, CONSTRUCTOR_NAME); var that = inheritIfRequired$1(new NativeConstructor(), dummy, Constructor); if (iterable != undefined) iterate$1(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); return that; }); Constructor.prototype = NativePrototype; NativePrototype.constructor = Constructor; } if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); // weak collections should not contains .clear method if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; } exported[CONSTRUCTOR_NAME] = Constructor; $$b({ global: true, forced: Constructor != NativeConstructor }, exported); setToStringTag$3(Constructor, CONSTRUCTOR_NAME); if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); return Constructor; }; var defineProperty$3 = objectDefineProperty.f; var create$2 = objectCreate; var redefineAll$2 = redefineAll$4; var bind$2 = functionBindContext; var anInstance$4 = anInstance$7; var iterate = iterate$3; var defineIterator = defineIterator$3; var setSpecies$2 = setSpecies$4; var DESCRIPTORS$5 = descriptors; var fastKey = internalMetadata.exports.fastKey; var InternalStateModule$4 = internalState; var setInternalState$4 = InternalStateModule$4.set; var internalStateGetterFor = InternalStateModule$4.getterFor; var collectionStrong$2 = { getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { var C = wrapper(function (that, iterable) { anInstance$4(that, C, CONSTRUCTOR_NAME); setInternalState$4(that, { type: CONSTRUCTOR_NAME, index: create$2(null), first: undefined, last: undefined, size: 0 }); if (!DESCRIPTORS$5) that.size = 0; if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); }); var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); var define = function (that, key, value) { var state = getInternalState(that); var entry = getEntry(that, key); var previous, index; // change existing entry if (entry) { entry.value = value; // create new entry } else { state.last = entry = { index: index = fastKey(key, true), key: key, value: value, previous: previous = state.last, next: undefined, removed: false }; if (!state.first) state.first = entry; if (previous) previous.next = entry; if (DESCRIPTORS$5) state.size++; else that.size++; // add to index if (index !== 'F') state.index[index] = entry; } return that; }; var getEntry = function (that, key) { var state = getInternalState(that); // fast case var index = fastKey(key); var entry; if (index !== 'F') return state.index[index]; // frozen object case for (entry = state.first; entry; entry = entry.next) { if (entry.key == key) return entry; } }; redefineAll$2(C.prototype, { // `{ Map, Set }.prototype.clear()` methods // https://tc39.es/ecma262/#sec-map.prototype.clear // https://tc39.es/ecma262/#sec-set.prototype.clear clear: function clear() { var that = this; var state = getInternalState(that); var data = state.index; var entry = state.first; while (entry) { entry.removed = true; if (entry.previous) entry.previous = entry.previous.next = undefined; delete data[entry.index]; entry = entry.next; } state.first = state.last = undefined; if (DESCRIPTORS$5) state.size = 0; else that.size = 0; }, // `{ Map, Set }.prototype.delete(key)` methods // https://tc39.es/ecma262/#sec-map.prototype.delete // https://tc39.es/ecma262/#sec-set.prototype.delete 'delete': function (key) { var that = this; var state = getInternalState(that); var entry = getEntry(that, key); if (entry) { var next = entry.next; var prev = entry.previous; delete state.index[entry.index]; entry.removed = true; if (prev) prev.next = next; if (next) next.previous = prev; if (state.first == entry) state.first = next; if (state.last == entry) state.last = prev; if (DESCRIPTORS$5) state.size--; else that.size--; } return !!entry; }, // `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods // https://tc39.es/ecma262/#sec-map.prototype.foreach // https://tc39.es/ecma262/#sec-set.prototype.foreach forEach: function forEach(callbackfn /* , that = undefined */) { var state = getInternalState(this); var boundFunction = bind$2(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); var entry; while (entry = entry ? entry.next : state.first) { boundFunction(entry.value, entry.key, this); // revert to the last existing entry while (entry && entry.removed) entry = entry.previous; } }, // `{ Map, Set}.prototype.has(key)` methods // https://tc39.es/ecma262/#sec-map.prototype.has // https://tc39.es/ecma262/#sec-set.prototype.has has: function has(key) { return !!getEntry(this, key); } }); redefineAll$2(C.prototype, IS_MAP ? { // `Map.prototype.get(key)` method // https://tc39.es/ecma262/#sec-map.prototype.get get: function get(key) { var entry = getEntry(this, key); return entry && entry.value; }, // `Map.prototype.set(key, value)` method // https://tc39.es/ecma262/#sec-map.prototype.set set: function set(key, value) { return define(this, key === 0 ? 0 : key, value); } } : { // `Set.prototype.add(value)` method // https://tc39.es/ecma262/#sec-set.prototype.add add: function add(value) { return define(this, value = value === 0 ? 0 : value, value); } }); if (DESCRIPTORS$5) defineProperty$3(C.prototype, 'size', { get: function () { return getInternalState(this).size; } }); return C; }, setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) { var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); // `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods // https://tc39.es/ecma262/#sec-map.prototype.entries // https://tc39.es/ecma262/#sec-map.prototype.keys // https://tc39.es/ecma262/#sec-map.prototype.values // https://tc39.es/ecma262/#sec-map.prototype-@@iterator // https://tc39.es/ecma262/#sec-set.prototype.entries // https://tc39.es/ecma262/#sec-set.prototype.keys // https://tc39.es/ecma262/#sec-set.prototype.values // https://tc39.es/ecma262/#sec-set.prototype-@@iterator defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) { setInternalState$4(this, { type: ITERATOR_NAME, target: iterated, state: getInternalCollectionState(iterated), kind: kind, last: undefined }); }, function () { var state = getInternalIteratorState(this); var kind = state.kind; var entry = state.last; // revert to the last existing entry while (entry && entry.removed) entry = entry.previous; // get next entry if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { // or finish the iteration state.target = undefined; return { value: undefined, done: true }; } // return step by kind if (kind == 'keys') return { value: entry.key, done: false }; if (kind == 'values') return { value: entry.value, done: false }; return { value: [entry.key, entry.value], done: false }; }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); // `{ Map, Set }.prototype[@@species]` accessors // https://tc39.es/ecma262/#sec-get-map-@@species // https://tc39.es/ecma262/#sec-get-set-@@species setSpecies$2(CONSTRUCTOR_NAME); } }; var collection$1 = collection$2; var collectionStrong$1 = collectionStrong$2; // `Map` constructor // https://tc39.es/ecma262/#sec-map-objects collection$1('Map', function (init) { return function Map() { return init(this, arguments.length ? arguments[0] : undefined); }; }, collectionStrong$1); var browser$5 = {}; Object.defineProperty(browser$5, '__esModule', { value: true }); var _classCallCheck$1 = classCallCheck.exports; var _createClass$1 = createClass.exports; var _assertThisInitialized$1 = assertThisInitialized.exports; var _inherits$1 = inherits.exports; var _possibleConstructorReturn$1 = possibleConstructorReturn.exports; var _getPrototypeOf$1 = getPrototypeOf$2.exports; var _defineProperty$1 = defineProperty$5.exports; function _interopDefaultLegacy$3(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } var _classCallCheck__default$1 = /*#__PURE__*/_interopDefaultLegacy$3(_classCallCheck$1); var _createClass__default$1 = /*#__PURE__*/_interopDefaultLegacy$3(_createClass$1); var _assertThisInitialized__default$1 = /*#__PURE__*/_interopDefaultLegacy$3(_assertThisInitialized$1); var _inherits__default$1 = /*#__PURE__*/_interopDefaultLegacy$3(_inherits$1); var _possibleConstructorReturn__default$1 = /*#__PURE__*/_interopDefaultLegacy$3(_possibleConstructorReturn$1); var _getPrototypeOf__default$1 = /*#__PURE__*/_interopDefaultLegacy$3(_getPrototypeOf$1); var _defineProperty__default$1 = /*#__PURE__*/_interopDefaultLegacy$3(_defineProperty$1); var domain$1; // This constructor is used to store event handlers. Instantiating this is // faster than explicitly calling `Object.create(null)` to get a "clean" empty // object (tested with v8 v4.9). function EventHandlers$1() {} EventHandlers$1.prototype = Object.create(null); function EventEmitter$1() { EventEmitter$1.init.call(this); } // nodejs oddity // require('events') === require('events').EventEmitter EventEmitter$1.EventEmitter = EventEmitter$1; EventEmitter$1.usingDomains = false; EventEmitter$1.prototype.domain = undefined; EventEmitter$1.prototype._events = undefined; EventEmitter$1.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter$1.defaultMaxListeners = 10; EventEmitter$1.init = function () { this.domain = null; if (EventEmitter$1.usingDomains) { // if there is an active domain, then attach to it. if (domain$1.active) ; } if (!this._events || this._events === Object.getPrototypeOf(this)._events) { this._events = new EventHandlers$1(); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter$1.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners$1(that) { if (that._maxListeners === undefined) return EventEmitter$1.defaultMaxListeners; return that._maxListeners; } EventEmitter$1.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners$1(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone$1(handler, isFn, self) { if (isFn) handler.call(self);else { var len = handler.length; var listeners = arrayClone$1(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self); } } } function emitOne$1(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1);else { var len = handler.length; var listeners = arrayClone$1(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1); } } } function emitTwo$1(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2);else { var len = handler.length; var listeners = arrayClone$1(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2); } } } function emitThree$1(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3);else { var len = handler.length; var listeners = arrayClone$1(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2, arg3); } } } function emitMany$1(handler, isFn, self, args) { if (isFn) handler.apply(self, args);else { var len = handler.length; var listeners = arrayClone$1(handler, len); for (var i = 0; i < len; ++i) { listeners[i].apply(self, args); } } } EventEmitter$1.prototype.emit = function emit(type) { var er, handler, len, args, i, events, domain; var doError = type === 'error'; events = this._events; if (events) doError = doError && events.error == null;else if (!doError) return false; domain = this.domain; // If there is no 'error' event listener then throw. if (doError) { er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); er.domainEmitter = this; er.domain = domain; er.domainThrown = false; domain.emit('error', er); } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone$1(handler, isFn, this); break; case 2: emitOne$1(handler, isFn, this, arguments[1]); break; case 3: emitTwo$1(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree$1(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) { args[i - 1] = arguments[i]; } emitMany$1(handler, isFn, this, args); } return true; }; function _addListener$1(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = new EventHandlers$1(); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners$1(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; emitWarning$1(w); } } } return target; } function emitWarning$1(e) { typeof console.warn === 'function' ? console.warn(e) : console.log(e); } EventEmitter$1.prototype.addListener = function addListener(type, listener) { return _addListener$1(this, type, listener, false); }; EventEmitter$1.prototype.on = EventEmitter$1.prototype.addListener; EventEmitter$1.prototype.prependListener = function prependListener(type, listener) { return _addListener$1(this, type, listener, true); }; function _onceWrap$1(target, type, listener) { var fired = false; function g() { target.removeListener(type, g); if (!fired) { fired = true; listener.apply(target, arguments); } } g.listener = listener; return g; } EventEmitter$1.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap$1(this, type, listener)); return this; }; EventEmitter$1.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap$1(this, type, listener)); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter$1.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener && list.listener === listener) { if (--this._eventsCount === 0) this._events = new EventHandlers$1();else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (list.length === 1) { list[0] = undefined; if (--this._eventsCount === 0) { this._events = new EventHandlers$1(); return this; } else { delete events[type]; } } else { spliceOne$1(list, position); } if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; // Alias for removeListener added in NodeJS 10.0 // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener EventEmitter$1.prototype.off = function (type, listener) { return this.removeListener(type, listener); }; EventEmitter$1.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = new EventHandlers$1(); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = new EventHandlers$1();else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); for (var i = 0, key; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = new EventHandlers$1(); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order do { this.removeListener(type, listeners[listeners.length - 1]); } while (listeners[0]); } return this; }; EventEmitter$1.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = [];else { evlistener = events[type]; if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners$1(evlistener); } return ret; }; EventEmitter$1.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount$1.call(emitter, type); } }; EventEmitter$1.prototype.listenerCount = listenerCount$1; function listenerCount$1(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter$1.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne$1(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; } list.pop(); } function arrayClone$1(arr, i) { var copy = new Array(i); while (i--) { copy[i] = arr[i]; } return copy; } function unwrapListeners$1(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function _createSuper$1$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default$1["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default$1["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default$1["default"](this, result); }; } function _isNativeReflectConstruct$1$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * Provides retrier service */ var Retrier = /*#__PURE__*/function (_EventEmitter) { _inherits__default$1["default"](Retrier, _EventEmitter); var _super = _createSuper$1$2(Retrier); // fibonacci strategy /** * Creates a new Retrier instance */ function Retrier(options) { var _this; _classCallCheck__default$1["default"](this, Retrier); _this = _super.call(this); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this), "timeout", null); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this), "startTimestamp", -1); _this.minDelay = options.min; _this.maxDelay = options.max; _this.initialDelay = options.initial || 0; _this.maxAttemptsCount = options.maxAttemptsCount || 0; _this.maxAttemptsTime = options.maxAttemptsTime || 0; _this.randomness = options.randomness || 0; _this.inProgress = false; _this.attemptNum = 0; _this.prevDelay = 0; _this.currDelay = 0; return _this; } _createClass__default$1["default"](Retrier, [{ key: "attempt", value: function attempt() { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.attemptNum++; this.emit("attempt", this); } }, { key: "nextDelay", value: function nextDelay(delayOverride) { if (typeof delayOverride === "number") { this.prevDelay = 0; this.currDelay = delayOverride; return delayOverride; } if (this.attemptNum == 0) { return this.initialDelay; } if (this.attemptNum == 1) { this.currDelay = this.minDelay; return this.currDelay; } this.prevDelay = this.currDelay; var delay = this.currDelay + this.prevDelay; if (this.maxDelay && delay > this.maxDelay) { this.currDelay = this.maxDelay; delay = this.maxDelay; } this.currDelay = delay; return delay; } }, { key: "randomize", value: function randomize(delay) { var area = delay * this.randomness; var corr = Math.round(Math.random() * area * 2 - area); return Math.max(0, delay + corr); } }, { key: "scheduleAttempt", value: function scheduleAttempt(delayOverride) { var _this2 = this; if (this.maxAttemptsCount && this.attemptNum >= this.maxAttemptsCount) { this.cleanup(); this.emit("failed", new Error("Maximum attempt count limit reached")); return; } var delay = this.nextDelay(delayOverride); delay = this.randomize(delay); if (this.maxAttemptsTime && this.startTimestamp + this.maxAttemptsTime < Date.now() + delay) { this.cleanup(); this.emit("failed", new Error("Maximum attempt time limit reached")); return; } this.timeout = setTimeout(function () { return _this2.attempt(); }, delay); } }, { key: "cleanup", value: function cleanup() { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.inProgress = false; this.attemptNum = 0; this.prevDelay = 0; this.currDelay = 0; } }, { key: "start", value: function start() { if (this.inProgress) { throw new Error("Retrier is already in progress"); } this.inProgress = true; this.startTimestamp = Date.now(); this.scheduleAttempt(this.initialDelay); } }, { key: "cancel", value: function cancel() { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; this.inProgress = false; this.emit("cancelled"); } } // @todo Must be a T here, so the entire Retrier must be typed on this value type. // eslint-disable-next-line }, { key: "succeeded", value: function succeeded(arg) { this.emit("succeeded", arg); } }, { key: "failed", value: function failed(err, nextAttemptDelayOverride) { if (this.timeout) { throw new Error("Retrier attempt is already in progress"); } this.scheduleAttempt(nextAttemptDelayOverride); } }]); return Retrier; }(EventEmitter$1); /** * Run retrier as an async function with possibility to await for it. * Example: * ``` * const result = AsyncRetrier.run(async () => somePromise); * ``` */ var AsyncRetrier = /*#__PURE__*/function (_EventEmitter2) { _inherits__default$1["default"](AsyncRetrier, _EventEmitter2); var _super2 = _createSuper$1$2(AsyncRetrier); // This any must be T typed directly on the AsyncRetrier // eslint-disable-next-line function AsyncRetrier(options) { var _this3; _classCallCheck__default$1["default"](this, AsyncRetrier); _this3 = _super2.call(this); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this3), "resolve", function () { return void 0; }); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this3), "reject", function () { return void 0; }); _this3.retrier = new Retrier(options); return _this3; } _createClass__default$1["default"](AsyncRetrier, [{ key: "run", value: function run(handler) { var _this4 = this; this.retrier.on("attempt", function () { handler().then(function (v) { return _this4.retrier.succeeded(v); }).catch(function (e) { return _this4.retrier.failed(e); }); }); this.retrier.on("succeeded", function (arg) { return _this4.resolve(arg); }); this.retrier.on("cancelled", function () { return _this4.reject(new Error("Cancelled")); }); this.retrier.on("failed", function (err) { return _this4.reject(err); }); return new Promise(function (resolve, reject) { _this4.resolve = resolve; _this4.reject = reject; _this4.retrier.start(); }); } }, { key: "cancel", value: function cancel() { this.retrier.cancel(); } }]); return AsyncRetrier; }(EventEmitter$1); function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = _getPrototypeOf__default$1["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default$1["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default$1["default"](this, result); }; } function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function isDef(value) { return value !== undefined && value !== null; } var Backoff = /*#__PURE__*/function (_EventEmitter) { _inherits__default$1["default"](Backoff, _EventEmitter); var _super = _createSuper$9(Backoff); function Backoff(options) { var _this; _classCallCheck__default$1["default"](this, Backoff); _this = _super.call(this); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this), "backoffDelay", 0); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this), "nextBackoffDelay", 0); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this), "backoffNumber", 0); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this), "timeoutID", null); _defineProperty__default$1["default"](_assertThisInitialized__default$1["default"](_this), "maxNumberOfRetry", -1); options = options || {}; var _options = options, initialDelay = _options.initialDelay, maxDelay = _options.maxDelay, randomisationFactor = _options.randomisationFactor, factor = _options.factor; if (isDef(initialDelay) && initialDelay < 1) { throw new Error("The initial timeout must be equal to or greater than 1."); } if (isDef(maxDelay) && maxDelay <= 1) { throw new Error("The maximal timeout must be greater than 1."); } if (isDef(randomisationFactor) && (randomisationFactor < 0 || randomisationFactor > 1)) { throw new Error("The randomisation factor must be between 0 and 1."); } if (isDef(factor) && factor <= 1) { throw new Error("Exponential factor should be greater than 1."); } _this.initialDelay = initialDelay || 100; _this.maxDelay = maxDelay || 10000; if (_this.maxDelay <= _this.initialDelay) { throw new Error("The maximal backoff delay must be greater than the initial backoff delay."); } _this.randomisationFactor = randomisationFactor || 0; _this.factor = factor || 2; _this.reset(); return _this; } _createClass__default$1["default"](Backoff, [{ key: "backoff", value: function backoff(err) { if (this.timeoutID == null) { if (this.backoffNumber === this.maxNumberOfRetry) { this.emit("fail", err); this.reset(); } else { this.backoffDelay = this.next(); this.timeoutID = setTimeout(this.onBackoff.bind(this), this.backoffDelay); this.emit("backoff", this.backoffNumber, this.backoffDelay, err); } } } }, { key: "reset", value: function reset() { this.backoffDelay = 0; this.nextBackoffDelay = this.initialDelay; this.backoffNumber = 0; if (this.timeoutID) { clearTimeout(this.timeoutID); } this.timeoutID = null; } }, { key: "failAfter", value: function failAfter(maxNumberOfRetry) { if (maxNumberOfRetry <= 0) { throw new Error("Expected a maximum number of retry greater than 0 but got ".concat(maxNumberOfRetry)); } this.maxNumberOfRetry = maxNumberOfRetry; } }, { key: "next", value: function next() { this.backoffDelay = Math.min(this.nextBackoffDelay, this.maxDelay); this.nextBackoffDelay = this.backoffDelay * this.factor; var randomisationMultiple = 1 + Math.random() * this.randomisationFactor; return Math.min(this.maxDelay, Math.round(this.backoffDelay * randomisationMultiple)); } }, { key: "onBackoff", value: function onBackoff() { this.timeoutID = null; this.emit("ready", this.backoffNumber, this.backoffDelay); this.backoffNumber++; } }], [{ key: "exponential", value: function exponential(options) { return new Backoff(options); } }]); return Backoff; }(EventEmitter$1); var AsyncRetrier_1 = browser$5.AsyncRetrier = AsyncRetrier; browser$5.Backoff = Backoff; var Retrier_1 = browser$5.Retrier = Retrier; function _createForOfIteratorHelper$5(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$5(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$5(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$5(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$5(o, minLen); } function _arrayLikeToArray$5(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var Network = /*#__PURE__*/function () { function Network(configuration, services) { _classCallCheck$4(this, Network); this.configuration = configuration; this.services = services; this.cache = new Map(); this.cacheLifetime = this.configuration.httpCacheInterval * 100; this.cleanupCache(); } _createClass$4(Network, [{ key: "isExpired", value: function isExpired(timestamp) { return !this.cacheLifetime || Date.now() - timestamp > this.cacheLifetime; } }, { key: "cleanupCache", value: function cleanupCache() { var _iterator = _createForOfIteratorHelper$5(this.cache), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _step$value = _slicedToArray$1(_step.value, 2), k = _step$value[0], v = _step$value[1]; if (this.isExpired(v.timestamp)) { this.cache.delete(k); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (this.cache.size === 0) { clearInterval(this.timer); } } }, { key: "pokeTimer", value: function pokeTimer() { var _this = this; this.timer = this.timer || setInterval(function () { return _this.cleanupCache(); }, this.cacheLifetime * 2); } }, { key: "executeWithRetry", value: function executeWithRetry(request) { var _this2 = this; var retryWhenThrottled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return new Promise(function (resolve, reject) { var codesToRetryOn = [502, 503, 504]; if (retryWhenThrottled) { codesToRetryOn.push(429); } var retrier = new Retrier_1(_this2.configuration.backoffConfiguration); retrier.on("attempt", function () { request().then(function (result) { return retrier.succeeded(result); }).catch(function (err) { if (codesToRetryOn.indexOf(err.status) > -1) { retrier.failed(err); } else if (err.message === "Twilsock disconnected") { // Ugly hack. We must make a proper exceptions for twilsock retrier.failed(err); } else { // Fatal error retrier.removeAllListeners(); retrier.cancel(); reject(err); } }); }); retrier.on("succeeded", function (result) { resolve(result); }); retrier.on("cancelled", function (err) { return reject(err); }); retrier.on("failed", function (err) { return reject(err); }); retrier.start(); }); } }, { key: "get", value: function () { var _get = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(url) { var _this3 = this; var cacheEntry, headers, response; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: cacheEntry = this.cache.get(url); if (!(cacheEntry && !this.isExpired(cacheEntry.timestamp))) { _context.next = 3; break; } return _context.abrupt("return", cacheEntry.response); case 3: headers = {}; _context.next = 6; return this.executeWithRetry(function () { return _this3.services.transport.get(url, headers, _this3.configuration.productId); }, this.configuration.retryWhenThrottled); case 6: response = _context.sent; this.cache.set(url, { response: response, timestamp: Date.now() }); this.pokeTimer(); return _context.abrupt("return", response); case 10: case "end": return _context.stop(); } } }, _callee, this); })); function get(_x) { return _get.apply(this, arguments); } return get; }() }]); return Network; }(); var NotificationTypes = /*#__PURE__*/_createClass$4(function NotificationTypes() { _classCallCheck$4(this, NotificationTypes); }); _defineProperty$3(NotificationTypes, "TYPING_INDICATOR", "twilio.ipmsg.typing_indicator"); _defineProperty$3(NotificationTypes, "NEW_MESSAGE", "twilio.conversations.new_message"); _defineProperty$3(NotificationTypes, "ADDED_TO_CONVERSATION", "twilio.conversations.added_to_conversation"); _defineProperty$3(NotificationTypes, "REMOVED_FROM_CONVERSATION", "twilio.conversations.removed_from_conversation"); _defineProperty$3(NotificationTypes, "CONSUMPTION_UPDATE", "twilio.channel.consumption_update"); var browser$4 = {}; var asyncToGenerator = {exports: {}}; (function (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; })(asyncToGenerator); var require$$8 = /*@__PURE__*/getAugmentedNamespace(regenerator); var redefine$3 = redefine$d.exports; var anObject$4 = anObject$k; var $toString$2 = toString$d; var fails$c = fails$B; var flags = regexpFlags$1; var TO_STRING = 'toString'; var RegExpPrototype = RegExp.prototype; var nativeToString = RegExpPrototype[TO_STRING]; var NOT_GENERIC = fails$c(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; }); // FF44- RegExp#toString has a wrong name var INCORRECT_NAME = nativeToString.name != TO_STRING; // `RegExp.prototype.toString` method // https://tc39.es/ecma262/#sec-regexp.prototype.tostring if (NOT_GENERIC || INCORRECT_NAME) { redefine$3(RegExp.prototype, TO_STRING, function toString() { var R = anObject$4(this); var p = $toString$2(R.source); var rf = R.flags; var f = $toString$2(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf); return '/' + p + '/' + f; }, { unsafe: true }); } var collection = collection$2; var collectionStrong = collectionStrong$2; // `Set` constructor // https://tc39.es/ecma262/#sec-set-objects collection('Set', function (init) { return function Set() { return init(this, arguments.length ? arguments[0] : undefined); }; }, collectionStrong); var stateMachine = {exports: {}}; (function (module, exports) { (function webpackUniversalModuleDefinition(root, factory) { module.exports = factory(); })(commonjsGlobal, function () { return ( /******/ function (modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function (value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function (exports, name, getter) { /******/ if (!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function (module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 5); /******/ } /************************************************************************/ /******/ ([ /* 0 */ /***/ function (module, exports, __webpack_require__) { module.exports = function (target, sources) { var n, source, key; for (n = 1; n < arguments.length; n++) { source = arguments[n]; for (key in source) { if (source.hasOwnProperty(key)) target[key] = source[key]; } } return target; }; /***/ }, /* 1 */ /***/ function (module, exports, __webpack_require__) { var mixin = __webpack_require__(0); //------------------------------------------------------------------------------------------------- module.exports = { build: function build(target, config) { var n, max, plugin, plugins = config.plugins; for (n = 0, max = plugins.length; n < max; n++) { plugin = plugins[n]; if (plugin.methods) mixin(target, plugin.methods); if (plugin.properties) Object.defineProperties(target, plugin.properties); } }, hook: function hook(fsm, name, additional) { var n, max, method, plugin, plugins = fsm.config.plugins, args = [fsm.context]; if (additional) args = args.concat(additional); for (n = 0, max = plugins.length; n < max; n++) { plugin = plugins[n]; method = plugins[n][name]; if (method) method.apply(plugin, args); } } }; //------------------------------------------------------------------------------------------------- /***/ }, /* 2 */ /***/ function (module, exports, __webpack_require__) { function camelize(label) { if (label.length === 0) return label; var n, result, words = label.split(/[_-]/); // single word with first character already lowercase, return untouched if (words.length === 1 && words[0][0].toLowerCase() === words[0][0]) return label; result = words[0].toLowerCase(); for (n = 1; n < words.length; n++) { result = result + words[n].charAt(0).toUpperCase() + words[n].substring(1).toLowerCase(); } return result; } //------------------------------------------------------------------------------------------------- camelize.prepended = function (prepend, label) { label = camelize(label); return prepend + label[0].toUpperCase() + label.substring(1); }; //------------------------------------------------------------------------------------------------- module.exports = camelize; /***/ }, /* 3 */ /***/ function (module, exports, __webpack_require__) { var mixin = __webpack_require__(0), camelize = __webpack_require__(2); //------------------------------------------------------------------------------------------------- function Config(options, StateMachine) { options = options || {}; this.options = options; // preserving original options can be useful (e.g visualize plugin) this.defaults = StateMachine.defaults; this.states = []; this.transitions = []; this.map = {}; this.lifecycle = this.configureLifecycle(); this.init = this.configureInitTransition(options.init); this.data = this.configureData(options.data); this.methods = this.configureMethods(options.methods); this.map[this.defaults.wildcard] = {}; this.configureTransitions(options.transitions || []); this.plugins = this.configurePlugins(options.plugins, StateMachine.plugin); } //------------------------------------------------------------------------------------------------- mixin(Config.prototype, { addState: function addState(name) { if (!this.map[name]) { this.states.push(name); this.addStateLifecycleNames(name); this.map[name] = {}; } }, addStateLifecycleNames: function addStateLifecycleNames(name) { this.lifecycle.onEnter[name] = camelize.prepended('onEnter', name); this.lifecycle.onLeave[name] = camelize.prepended('onLeave', name); this.lifecycle.on[name] = camelize.prepended('on', name); }, addTransition: function addTransition(name) { if (this.transitions.indexOf(name) < 0) { this.transitions.push(name); this.addTransitionLifecycleNames(name); } }, addTransitionLifecycleNames: function addTransitionLifecycleNames(name) { this.lifecycle.onBefore[name] = camelize.prepended('onBefore', name); this.lifecycle.onAfter[name] = camelize.prepended('onAfter', name); this.lifecycle.on[name] = camelize.prepended('on', name); }, mapTransition: function mapTransition(transition) { var name = transition.name, from = transition.from, to = transition.to; this.addState(from); if (typeof to !== 'function') this.addState(to); this.addTransition(name); this.map[from][name] = transition; return transition; }, configureLifecycle: function configureLifecycle() { return { onBefore: { transition: 'onBeforeTransition' }, onAfter: { transition: 'onAfterTransition' }, onEnter: { state: 'onEnterState' }, onLeave: { state: 'onLeaveState' }, on: { transition: 'onTransition' } }; }, configureInitTransition: function configureInitTransition(init) { if (typeof init === 'string') { return this.mapTransition(mixin({}, this.defaults.init, { to: init, active: true })); } else if (_typeof$3(init) === 'object') { return this.mapTransition(mixin({}, this.defaults.init, init, { active: true })); } else { this.addState(this.defaults.init.from); return this.defaults.init; } }, configureData: function configureData(data) { if (typeof data === 'function') return data;else if (_typeof$3(data) === 'object') return function () { return data; };else return function () { return {}; }; }, configureMethods: function configureMethods(methods) { return methods || {}; }, configurePlugins: function configurePlugins(plugins, builtin) { plugins = plugins || []; var n, max, plugin; for (n = 0, max = plugins.length; n < max; n++) { plugin = plugins[n]; if (typeof plugin === 'function') plugins[n] = plugin = plugin(); if (plugin.configure) plugin.configure(this); } return plugins; }, configureTransitions: function configureTransitions(transitions) { var i, n, transition, from, to, wildcard = this.defaults.wildcard; for (n = 0; n < transitions.length; n++) { transition = transitions[n]; from = Array.isArray(transition.from) ? transition.from : [transition.from || wildcard]; to = transition.to || wildcard; for (i = 0; i < from.length; i++) { this.mapTransition({ name: transition.name, from: from[i], to: to }); } } }, transitionFor: function transitionFor(state, transition) { var wildcard = this.defaults.wildcard; return this.map[state][transition] || this.map[wildcard][transition]; }, transitionsFor: function transitionsFor(state) { var wildcard = this.defaults.wildcard; return Object.keys(this.map[state]).concat(Object.keys(this.map[wildcard])); }, allStates: function allStates() { return this.states; }, allTransitions: function allTransitions() { return this.transitions; } }); //------------------------------------------------------------------------------------------------- module.exports = Config; //------------------------------------------------------------------------------------------------- /***/ }, /* 4 */ /***/ function (module, exports, __webpack_require__) { var mixin = __webpack_require__(0), Exception = __webpack_require__(6), plugin = __webpack_require__(1), UNOBSERVED = [null, []]; //------------------------------------------------------------------------------------------------- function JSM(context, config) { this.context = context; this.config = config; this.state = config.init.from; this.observers = [context]; } //------------------------------------------------------------------------------------------------- mixin(JSM.prototype, { init: function init(args) { mixin(this.context, this.config.data.apply(this.context, args)); plugin.hook(this, 'init'); if (this.config.init.active) return this.fire(this.config.init.name, []); }, is: function is(state) { return Array.isArray(state) ? state.indexOf(this.state) >= 0 : this.state === state; }, isPending: function isPending() { return this.pending; }, can: function can(transition) { return !this.isPending() && !!this.seek(transition); }, cannot: function cannot(transition) { return !this.can(transition); }, allStates: function allStates() { return this.config.allStates(); }, allTransitions: function allTransitions() { return this.config.allTransitions(); }, transitions: function transitions() { return this.config.transitionsFor(this.state); }, seek: function seek(transition, args) { var wildcard = this.config.defaults.wildcard, entry = this.config.transitionFor(this.state, transition), to = entry && entry.to; if (typeof to === 'function') return to.apply(this.context, args);else if (to === wildcard) return this.state;else return to; }, fire: function fire(transition, args) { return this.transit(transition, this.state, this.seek(transition, args), args); }, transit: function transit(transition, from, to, args) { var lifecycle = this.config.lifecycle, changed = this.config.options.observeUnchangedState || from !== to; if (!to) return this.context.onInvalidTransition(transition, from, to); if (this.isPending()) return this.context.onPendingTransition(transition, from, to); this.config.addState(to); // might need to add this state if it's unknown (e.g. conditional transition or goto) this.beginTransit(); args.unshift({ // this context will be passed to each lifecycle event observer transition: transition, from: from, to: to, fsm: this.context }); return this.observeEvents([this.observersForEvent(lifecycle.onBefore.transition), this.observersForEvent(lifecycle.onBefore[transition]), changed ? this.observersForEvent(lifecycle.onLeave.state) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onLeave[from]) : UNOBSERVED, this.observersForEvent(lifecycle.on.transition), changed ? ['doTransit', [this]] : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onEnter.state) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onEnter[to]) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.on[to]) : UNOBSERVED, this.observersForEvent(lifecycle.onAfter.transition), this.observersForEvent(lifecycle.onAfter[transition]), this.observersForEvent(lifecycle.on[transition])], args); }, beginTransit: function beginTransit() { this.pending = true; }, endTransit: function endTransit(result) { this.pending = false; return result; }, failTransit: function failTransit(result) { this.pending = false; throw result; }, doTransit: function doTransit(lifecycle) { this.state = lifecycle.to; }, observe: function observe(args) { if (args.length === 2) { var observer = {}; observer[args[0]] = args[1]; this.observers.push(observer); } else { this.observers.push(args[0]); } }, observersForEvent: function observersForEvent(event) { // TODO: this could be cached var n = 0, max = this.observers.length, observer, result = []; for (; n < max; n++) { observer = this.observers[n]; if (observer[event]) result.push(observer); } return [event, result, true]; }, observeEvents: function observeEvents(events, args, previousEvent, previousResult) { if (events.length === 0) { return this.endTransit(previousResult === undefined ? true : previousResult); } var event = events[0][0], observers = events[0][1], pluggable = events[0][2]; args[0].event = event; if (event && pluggable && event !== previousEvent) plugin.hook(this, 'lifecycle', args); if (observers.length === 0) { events.shift(); return this.observeEvents(events, args, event, previousResult); } else { var observer = observers.shift(), result = observer[event].apply(observer, args); if (result && typeof result.then === 'function') { return result.then(this.observeEvents.bind(this, events, args, event)).catch(this.failTransit.bind(this)); } else if (result === false) { return this.endTransit(false); } else { return this.observeEvents(events, args, event, result); } } }, onInvalidTransition: function onInvalidTransition(transition, from, to) { throw new Exception("transition is invalid in current state", transition, from, to, this.state); }, onPendingTransition: function onPendingTransition(transition, from, to) { throw new Exception("transition is invalid while previous transition is still in progress", transition, from, to, this.state); } }); //------------------------------------------------------------------------------------------------- module.exports = JSM; //------------------------------------------------------------------------------------------------- /***/ }, /* 5 */ /***/ function (module, exports, __webpack_require__) { var mixin = __webpack_require__(0), camelize = __webpack_require__(2), plugin = __webpack_require__(1), Config = __webpack_require__(3), JSM = __webpack_require__(4); //----------------------------------------------------------------------------------------------- var PublicMethods = { is: function is(state) { return this._fsm.is(state); }, can: function can(transition) { return this._fsm.can(transition); }, cannot: function cannot(transition) { return this._fsm.cannot(transition); }, observe: function observe() { return this._fsm.observe(arguments); }, transitions: function transitions() { return this._fsm.transitions(); }, allTransitions: function allTransitions() { return this._fsm.allTransitions(); }, allStates: function allStates() { return this._fsm.allStates(); }, onInvalidTransition: function onInvalidTransition(t, from, to) { return this._fsm.onInvalidTransition(t, from, to); }, onPendingTransition: function onPendingTransition(t, from, to) { return this._fsm.onPendingTransition(t, from, to); } }; var PublicProperties = { state: { configurable: false, enumerable: true, get: function get() { return this._fsm.state; }, set: function set(state) { throw Error('use transitions to change state'); } } }; //----------------------------------------------------------------------------------------------- function StateMachine(options) { return apply(this || {}, options); } function factory() { var cstor, options; if (typeof arguments[0] === 'function') { cstor = arguments[0]; options = arguments[1] || {}; } else { cstor = function cstor() { this._fsm.apply(this, arguments); }; options = arguments[0] || {}; } var config = new Config(options, StateMachine); build(cstor.prototype, config); cstor.prototype._fsm.config = config; // convenience access to shared config without needing an instance return cstor; } //------------------------------------------------------------------------------------------------- function apply(instance, options) { var config = new Config(options, StateMachine); build(instance, config); instance._fsm(); return instance; } function build(target, config) { if (_typeof$3(target) !== 'object' || Array.isArray(target)) throw Error('StateMachine can only be applied to objects'); plugin.build(target, config); Object.defineProperties(target, PublicProperties); mixin(target, PublicMethods); mixin(target, config.methods); config.allTransitions().forEach(function (transition) { target[camelize(transition)] = function () { return this._fsm.fire(transition, [].slice.call(arguments)); }; }); target._fsm = function () { this._fsm = new JSM(this, config); this._fsm.init(arguments); }; } //----------------------------------------------------------------------------------------------- StateMachine.version = '3.0.1'; StateMachine.factory = factory; StateMachine.apply = apply; StateMachine.defaults = { wildcard: '*', init: { name: 'init', from: 'none' } }; //=============================================================================================== module.exports = StateMachine; /***/ }, /* 6 */ /***/ function (module, exports, __webpack_require__) { module.exports = function (message, transition, from, to, current) { this.message = message; this.transition = transition; this.from = from; this.to = to; this.current = current; }; /***/ } /******/ ]) ); }); })(stateMachine); var rngBrowser = {exports: {}}; // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection // getRandomValues needs to be invoked in a context where "this" is a Crypto // implementation. Also, find the complete implementation of crypto on IE11. var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto); if (getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef rngBrowser.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; } else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); rngBrowser.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid$2(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join(''); } var bytesToUuid_1 = bytesToUuid$2; var rng$1 = rngBrowser.exports; var bytesToUuid$1 = bytesToUuid_1; // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1$1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { var seedBytes = rng$1(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid$1(b); } var v1_1 = v1$1; var rng = rngBrowser.exports; var bytesToUuid = bytesToUuid_1; function v4$1(options, buf, offset) { var i = buf && offset || 0; if (typeof options == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } var v4_1 = v4$1; var v1 = v1_1; var v4 = v4_1; var uuid$1 = v4; uuid$1.v1 = v1; uuid$1.v4 = v4; var uuid_1 = uuid$1; var typedArrayConstructor = {exports: {}}; // eslint-disable-next-line es/no-typed-arrays -- safe var arrayBufferNative = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined'; var NATIVE_ARRAY_BUFFER$1 = arrayBufferNative; var DESCRIPTORS$4 = descriptors; var global$a = global$D; var isObject$4 = isObject$p; var has$2 = has$g; var classof$3 = classof$9; var createNonEnumerableProperty$2 = createNonEnumerableProperty$c; var redefine$2 = redefine$d.exports; var defineProperty$2 = objectDefineProperty.f; var getPrototypeOf$1 = objectGetPrototypeOf; var setPrototypeOf$2 = objectSetPrototypeOf; var wellKnownSymbol$5 = wellKnownSymbol$s; var uid = uid$5; var Int8Array$3 = global$a.Int8Array; var Int8ArrayPrototype = Int8Array$3 && Int8Array$3.prototype; var Uint8ClampedArray = global$a.Uint8ClampedArray; var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; var TypedArray$1 = Int8Array$3 && getPrototypeOf$1(Int8Array$3); var TypedArrayPrototype$1 = Int8ArrayPrototype && getPrototypeOf$1(Int8ArrayPrototype); var ObjectPrototype$1 = Object.prototype; var isPrototypeOf = ObjectPrototype$1.isPrototypeOf; var TO_STRING_TAG = wellKnownSymbol$5('toStringTag'); var TYPED_ARRAY_TAG$1 = uid('TYPED_ARRAY_TAG'); var TYPED_ARRAY_CONSTRUCTOR$2 = uid('TYPED_ARRAY_CONSTRUCTOR'); // Fixing native typed arrays in Opera Presto crashes the browser, see #595 var NATIVE_ARRAY_BUFFER_VIEWS$2 = NATIVE_ARRAY_BUFFER$1 && !!setPrototypeOf$2 && classof$3(global$a.opera) !== 'Opera'; var TYPED_ARRAY_TAG_REQIRED = false; var NAME, Constructor, Prototype; var TypedArrayConstructorsList = { Int8Array: 1, Uint8Array: 1, Uint8ClampedArray: 1, Int16Array: 2, Uint16Array: 2, Int32Array: 4, Uint32Array: 4, Float32Array: 4, Float64Array: 8 }; var BigIntArrayConstructorsList = { BigInt64Array: 8, BigUint64Array: 8 }; var isView = function isView(it) { if (!isObject$4(it)) return false; var klass = classof$3(it); return klass === 'DataView' || has$2(TypedArrayConstructorsList, klass) || has$2(BigIntArrayConstructorsList, klass); }; var isTypedArray$1 = function (it) { if (!isObject$4(it)) return false; var klass = classof$3(it); return has$2(TypedArrayConstructorsList, klass) || has$2(BigIntArrayConstructorsList, klass); }; var aTypedArray$n = function (it) { if (isTypedArray$1(it)) return it; throw TypeError('Target is not a typed array'); }; var aTypedArrayConstructor$3 = function (C) { if (setPrototypeOf$2 && !isPrototypeOf.call(TypedArray$1, C)) { throw TypeError('Target is not a typed array constructor'); } return C; }; var exportTypedArrayMethod$o = function (KEY, property, forced) { if (!DESCRIPTORS$4) return; if (forced) for (var ARRAY in TypedArrayConstructorsList) { var TypedArrayConstructor = global$a[ARRAY]; if (TypedArrayConstructor && has$2(TypedArrayConstructor.prototype, KEY)) try { delete TypedArrayConstructor.prototype[KEY]; } catch (error) { /* empty */ } } if (!TypedArrayPrototype$1[KEY] || forced) { redefine$2(TypedArrayPrototype$1, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS$2 && Int8ArrayPrototype[KEY] || property); } }; var exportTypedArrayStaticMethod = function (KEY, property, forced) { var ARRAY, TypedArrayConstructor; if (!DESCRIPTORS$4) return; if (setPrototypeOf$2) { if (forced) for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global$a[ARRAY]; if (TypedArrayConstructor && has$2(TypedArrayConstructor, KEY)) try { delete TypedArrayConstructor[KEY]; } catch (error) { /* empty */ } } if (!TypedArray$1[KEY] || forced) { // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable try { return redefine$2(TypedArray$1, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS$2 && TypedArray$1[KEY] || property); } catch (error) { /* empty */ } } else return; } for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global$a[ARRAY]; if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { redefine$2(TypedArrayConstructor, KEY, property); } } }; for (NAME in TypedArrayConstructorsList) { Constructor = global$a[NAME]; Prototype = Constructor && Constructor.prototype; if (Prototype) createNonEnumerableProperty$2(Prototype, TYPED_ARRAY_CONSTRUCTOR$2, Constructor); else NATIVE_ARRAY_BUFFER_VIEWS$2 = false; } for (NAME in BigIntArrayConstructorsList) { Constructor = global$a[NAME]; Prototype = Constructor && Constructor.prototype; if (Prototype) createNonEnumerableProperty$2(Prototype, TYPED_ARRAY_CONSTRUCTOR$2, Constructor); } // WebKit bug - typed arrays constructors prototype is Object.prototype if (!NATIVE_ARRAY_BUFFER_VIEWS$2 || typeof TypedArray$1 != 'function' || TypedArray$1 === Function.prototype) { // eslint-disable-next-line no-shadow -- safe TypedArray$1 = function TypedArray() { throw TypeError('Incorrect invocation'); }; if (NATIVE_ARRAY_BUFFER_VIEWS$2) for (NAME in TypedArrayConstructorsList) { if (global$a[NAME]) setPrototypeOf$2(global$a[NAME], TypedArray$1); } } if (!NATIVE_ARRAY_BUFFER_VIEWS$2 || !TypedArrayPrototype$1 || TypedArrayPrototype$1 === ObjectPrototype$1) { TypedArrayPrototype$1 = TypedArray$1.prototype; if (NATIVE_ARRAY_BUFFER_VIEWS$2) for (NAME in TypedArrayConstructorsList) { if (global$a[NAME]) setPrototypeOf$2(global$a[NAME].prototype, TypedArrayPrototype$1); } } // WebKit bug - one more object in Uint8ClampedArray prototype chain if (NATIVE_ARRAY_BUFFER_VIEWS$2 && getPrototypeOf$1(Uint8ClampedArrayPrototype) !== TypedArrayPrototype$1) { setPrototypeOf$2(Uint8ClampedArrayPrototype, TypedArrayPrototype$1); } if (DESCRIPTORS$4 && !has$2(TypedArrayPrototype$1, TO_STRING_TAG)) { TYPED_ARRAY_TAG_REQIRED = true; defineProperty$2(TypedArrayPrototype$1, TO_STRING_TAG, { get: function () { return isObject$4(this) ? this[TYPED_ARRAY_TAG$1] : undefined; } }); for (NAME in TypedArrayConstructorsList) if (global$a[NAME]) { createNonEnumerableProperty$2(global$a[NAME], TYPED_ARRAY_TAG$1, NAME); } } var arrayBufferViewCore = { NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS$2, TYPED_ARRAY_CONSTRUCTOR: TYPED_ARRAY_CONSTRUCTOR$2, TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG$1, aTypedArray: aTypedArray$n, aTypedArrayConstructor: aTypedArrayConstructor$3, exportTypedArrayMethod: exportTypedArrayMethod$o, exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, isView: isView, isTypedArray: isTypedArray$1, TypedArray: TypedArray$1, TypedArrayPrototype: TypedArrayPrototype$1 }; /* eslint-disable no-new -- required for testing */ var global$9 = global$D; var fails$b = fails$B; var checkCorrectnessOfIteration = checkCorrectnessOfIteration$4; var NATIVE_ARRAY_BUFFER_VIEWS$1 = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; var ArrayBuffer$3 = global$9.ArrayBuffer; var Int8Array$2 = global$9.Int8Array; var typedArrayConstructorsRequireWrappers = !NATIVE_ARRAY_BUFFER_VIEWS$1 || !fails$b(function () { Int8Array$2(1); }) || !fails$b(function () { new Int8Array$2(-1); }) || !checkCorrectnessOfIteration(function (iterable) { new Int8Array$2(); new Int8Array$2(null); new Int8Array$2(1.5); new Int8Array$2(iterable); }, true) || fails$b(function () { // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill return new Int8Array$2(new ArrayBuffer$3(2), 1, undefined).length !== 1; }); var toInteger$5 = toInteger$a; var toLength$g = toLength$o; // `ToIndex` abstract operation // https://tc39.es/ecma262/#sec-toindex var toIndex$2 = function (it) { if (it === undefined) return 0; var number = toInteger$5(it); var length = toLength$g(number); if (number !== length) throw RangeError('Wrong length or index'); return length; }; // IEEE754 conversions based on https://github.com/feross/ieee754 var abs = Math.abs; var pow$1 = Math.pow; var floor$4 = Math.floor; var log$8 = Math.log; var LN2 = Math.LN2; var pack = function (number, mantissaLength, bytes) { var buffer = new Array(bytes); var exponentLength = bytes * 8 - mantissaLength - 1; var eMax = (1 << exponentLength) - 1; var eBias = eMax >> 1; var rt = mantissaLength === 23 ? pow$1(2, -24) - pow$1(2, -77) : 0; var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0; var index = 0; var exponent, mantissa, c; number = abs(number); // eslint-disable-next-line no-self-compare -- NaN check if (number != number || number === Infinity) { // eslint-disable-next-line no-self-compare -- NaN check mantissa = number != number ? 1 : 0; exponent = eMax; } else { exponent = floor$4(log$8(number) / LN2); if (number * (c = pow$1(2, -exponent)) < 1) { exponent--; c *= 2; } if (exponent + eBias >= 1) { number += rt / c; } else { number += rt * pow$1(2, 1 - eBias); } if (number * c >= 2) { exponent++; c /= 2; } if (exponent + eBias >= eMax) { mantissa = 0; exponent = eMax; } else if (exponent + eBias >= 1) { mantissa = (number * c - 1) * pow$1(2, mantissaLength); exponent = exponent + eBias; } else { mantissa = number * pow$1(2, eBias - 1) * pow$1(2, mantissaLength); exponent = 0; } } for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8); exponent = exponent << mantissaLength | mantissa; exponentLength += mantissaLength; for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8); buffer[--index] |= sign * 128; return buffer; }; var unpack = function (buffer, mantissaLength) { var bytes = buffer.length; var exponentLength = bytes * 8 - mantissaLength - 1; var eMax = (1 << exponentLength) - 1; var eBias = eMax >> 1; var nBits = exponentLength - 7; var index = bytes - 1; var sign = buffer[index--]; var exponent = sign & 127; var mantissa; sign >>= 7; for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8); mantissa = exponent & (1 << -nBits) - 1; exponent >>= -nBits; nBits += mantissaLength; for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8); if (exponent === 0) { exponent = 1 - eBias; } else if (exponent === eMax) { return mantissa ? NaN : sign ? -Infinity : Infinity; } else { mantissa = mantissa + pow$1(2, mantissaLength); exponent = exponent - eBias; } return (sign ? -1 : 1) * mantissa * pow$1(2, exponent - mantissaLength); }; var ieee754 = { pack: pack, unpack: unpack }; var toObject$7 = toObject$g; var toAbsoluteIndex$3 = toAbsoluteIndex$6; var toLength$f = toLength$o; // `Array.prototype.fill` method implementation // https://tc39.es/ecma262/#sec-array.prototype.fill var arrayFill$1 = function fill(value /* , start = 0, end = @length */) { var O = toObject$7(this); var length = toLength$f(O.length); var argumentsLength = arguments.length; var index = toAbsoluteIndex$3(argumentsLength > 1 ? arguments[1] : undefined, length); var end = argumentsLength > 2 ? arguments[2] : undefined; var endPos = end === undefined ? length : toAbsoluteIndex$3(end, length); while (endPos > index) O[index++] = value; return O; }; var global$8 = global$D; var DESCRIPTORS$3 = descriptors; var NATIVE_ARRAY_BUFFER = arrayBufferNative; var createNonEnumerableProperty$1 = createNonEnumerableProperty$c; var redefineAll$1 = redefineAll$4; var fails$a = fails$B; var anInstance$3 = anInstance$7; var toInteger$4 = toInteger$a; var toLength$e = toLength$o; var toIndex$1 = toIndex$2; var IEEE754 = ieee754; var getPrototypeOf = objectGetPrototypeOf; var setPrototypeOf$1 = objectSetPrototypeOf; var getOwnPropertyNames$1 = objectGetOwnPropertyNames.f; var defineProperty$1 = objectDefineProperty.f; var arrayFill = arrayFill$1; var setToStringTag$2 = setToStringTag$9; var InternalStateModule$3 = internalState; var getInternalState$1 = InternalStateModule$3.get; var setInternalState$3 = InternalStateModule$3.set; var ARRAY_BUFFER$1 = 'ArrayBuffer'; var DATA_VIEW = 'DataView'; var PROTOTYPE = 'prototype'; var WRONG_LENGTH$1 = 'Wrong length'; var WRONG_INDEX = 'Wrong index'; var NativeArrayBuffer$1 = global$8[ARRAY_BUFFER$1]; var $ArrayBuffer = NativeArrayBuffer$1; var $DataView = global$8[DATA_VIEW]; var $DataViewPrototype = $DataView && $DataView[PROTOTYPE]; var ObjectPrototype = Object.prototype; var RangeError$2 = global$8.RangeError; var packIEEE754 = IEEE754.pack; var unpackIEEE754 = IEEE754.unpack; var packInt8 = function (number) { return [number & 0xFF]; }; var packInt16 = function (number) { return [number & 0xFF, number >> 8 & 0xFF]; }; var packInt32 = function (number) { return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF]; }; var unpackInt32 = function (buffer) { return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; }; var packFloat32 = function (number) { return packIEEE754(number, 23, 4); }; var packFloat64 = function (number) { return packIEEE754(number, 52, 8); }; var addGetter$1 = function (Constructor, key) { defineProperty$1(Constructor[PROTOTYPE], key, { get: function () { return getInternalState$1(this)[key]; } }); }; var get = function (view, count, index, isLittleEndian) { var intIndex = toIndex$1(index); var store = getInternalState$1(view); if (intIndex + count > store.byteLength) throw RangeError$2(WRONG_INDEX); var bytes = getInternalState$1(store.buffer).bytes; var start = intIndex + store.byteOffset; var pack = bytes.slice(start, start + count); return isLittleEndian ? pack : pack.reverse(); }; var set = function (view, count, index, conversion, value, isLittleEndian) { var intIndex = toIndex$1(index); var store = getInternalState$1(view); if (intIndex + count > store.byteLength) throw RangeError$2(WRONG_INDEX); var bytes = getInternalState$1(store.buffer).bytes; var start = intIndex + store.byteOffset; var pack = conversion(+value); for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1]; }; if (!NATIVE_ARRAY_BUFFER) { $ArrayBuffer = function ArrayBuffer(length) { anInstance$3(this, $ArrayBuffer, ARRAY_BUFFER$1); var byteLength = toIndex$1(length); setInternalState$3(this, { bytes: arrayFill.call(new Array(byteLength), 0), byteLength: byteLength }); if (!DESCRIPTORS$3) this.byteLength = byteLength; }; $DataView = function DataView(buffer, byteOffset, byteLength) { anInstance$3(this, $DataView, DATA_VIEW); anInstance$3(buffer, $ArrayBuffer, DATA_VIEW); var bufferLength = getInternalState$1(buffer).byteLength; var offset = toInteger$4(byteOffset); if (offset < 0 || offset > bufferLength) throw RangeError$2('Wrong offset'); byteLength = byteLength === undefined ? bufferLength - offset : toLength$e(byteLength); if (offset + byteLength > bufferLength) throw RangeError$2(WRONG_LENGTH$1); setInternalState$3(this, { buffer: buffer, byteLength: byteLength, byteOffset: offset }); if (!DESCRIPTORS$3) { this.buffer = buffer; this.byteLength = byteLength; this.byteOffset = offset; } }; if (DESCRIPTORS$3) { addGetter$1($ArrayBuffer, 'byteLength'); addGetter$1($DataView, 'buffer'); addGetter$1($DataView, 'byteLength'); addGetter$1($DataView, 'byteOffset'); } redefineAll$1($DataView[PROTOTYPE], { getInt8: function getInt8(byteOffset) { return get(this, 1, byteOffset)[0] << 24 >> 24; }, getUint8: function getUint8(byteOffset) { return get(this, 1, byteOffset)[0]; }, getInt16: function getInt16(byteOffset /* , littleEndian */) { var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); return (bytes[1] << 8 | bytes[0]) << 16 >> 16; }, getUint16: function getUint16(byteOffset /* , littleEndian */) { var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); return bytes[1] << 8 | bytes[0]; }, getInt32: function getInt32(byteOffset /* , littleEndian */) { return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)); }, getUint32: function getUint32(byteOffset /* , littleEndian */) { return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0; }, getFloat32: function getFloat32(byteOffset /* , littleEndian */) { return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23); }, getFloat64: function getFloat64(byteOffset /* , littleEndian */) { return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52); }, setInt8: function setInt8(byteOffset, value) { set(this, 1, byteOffset, packInt8, value); }, setUint8: function setUint8(byteOffset, value) { set(this, 1, byteOffset, packInt8, value); }, setInt16: function setInt16(byteOffset, value /* , littleEndian */) { set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); }, setUint16: function setUint16(byteOffset, value /* , littleEndian */) { set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); }, setInt32: function setInt32(byteOffset, value /* , littleEndian */) { set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); }, setUint32: function setUint32(byteOffset, value /* , littleEndian */) { set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); }, setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined); }, setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined); } }); } else { /* eslint-disable no-new -- required for testing */ if (!fails$a(function () { NativeArrayBuffer$1(1); }) || !fails$a(function () { new NativeArrayBuffer$1(-1); }) || fails$a(function () { new NativeArrayBuffer$1(); new NativeArrayBuffer$1(1.5); new NativeArrayBuffer$1(NaN); return NativeArrayBuffer$1.name != ARRAY_BUFFER$1; })) { /* eslint-enable no-new -- required for testing */ $ArrayBuffer = function ArrayBuffer(length) { anInstance$3(this, $ArrayBuffer); return new NativeArrayBuffer$1(toIndex$1(length)); }; var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE] = NativeArrayBuffer$1[PROTOTYPE]; for (var keys = getOwnPropertyNames$1(NativeArrayBuffer$1), j = 0, key; keys.length > j;) { if (!((key = keys[j++]) in $ArrayBuffer)) { createNonEnumerableProperty$1($ArrayBuffer, key, NativeArrayBuffer$1[key]); } } ArrayBufferPrototype.constructor = $ArrayBuffer; } // WebKit bug - the same parent prototype for typed arrays and data view if (setPrototypeOf$1 && getPrototypeOf($DataViewPrototype) !== ObjectPrototype) { setPrototypeOf$1($DataViewPrototype, ObjectPrototype); } // iOS Safari 7.x bug var testView = new $DataView(new $ArrayBuffer(2)); var $setInt8 = $DataViewPrototype.setInt8; testView.setInt8(0, 2147483648); testView.setInt8(1, 2147483649); if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll$1($DataViewPrototype, { setInt8: function setInt8(byteOffset, value) { $setInt8.call(this, byteOffset, value << 24 >> 24); }, setUint8: function setUint8(byteOffset, value) { $setInt8.call(this, byteOffset, value << 24 >> 24); } }, { unsafe: true }); } setToStringTag$2($ArrayBuffer, ARRAY_BUFFER$1); setToStringTag$2($DataView, DATA_VIEW); var arrayBuffer = { ArrayBuffer: $ArrayBuffer, DataView: $DataView }; var toInteger$3 = toInteger$a; var toPositiveInteger$1 = function (it) { var result = toInteger$3(it); if (result < 0) throw RangeError("The argument can't be less than 0"); return result; }; var toPositiveInteger = toPositiveInteger$1; var toOffset$2 = function (it, BYTES) { var offset = toPositiveInteger(it); if (offset % BYTES) throw RangeError('Wrong offset'); return offset; }; var toObject$6 = toObject$g; var toLength$d = toLength$o; var getIterator$1 = getIterator$4; var getIteratorMethod$1 = getIteratorMethod$5; var isArrayIteratorMethod = isArrayIteratorMethod$3; var bind$1 = functionBindContext; var aTypedArrayConstructor$2 = arrayBufferViewCore.aTypedArrayConstructor; var typedArrayFrom$1 = function from(source /* , mapfn, thisArg */) { var O = toObject$6(source); var argumentsLength = arguments.length; var mapfn = argumentsLength > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var iteratorMethod = getIteratorMethod$1(O); var i, length, result, step, iterator, next; if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) { iterator = getIterator$1(O, iteratorMethod); next = iterator.next; O = []; while (!(step = next.call(iterator)).done) { O.push(step.value); } } if (mapping && argumentsLength > 2) { mapfn = bind$1(mapfn, arguments[2], 2); } length = toLength$d(O.length); result = new (aTypedArrayConstructor$2(this))(length); for (i = 0; length > i; i++) { result[i] = mapping ? mapfn(O[i], i) : O[i]; } return result; }; var $$a = _export; var global$7 = global$D; var DESCRIPTORS$2 = descriptors; var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = typedArrayConstructorsRequireWrappers; var ArrayBufferViewCore$o = arrayBufferViewCore; var ArrayBufferModule = arrayBuffer; var anInstance$2 = anInstance$7; var createPropertyDescriptor$1 = createPropertyDescriptor$7; var createNonEnumerableProperty = createNonEnumerableProperty$c; var isInteger$1 = isInteger$3; var toLength$c = toLength$o; var toIndex = toIndex$2; var toOffset$1 = toOffset$2; var toPropertyKey = toPropertyKey$5; var has$1 = has$g; var classof$2 = classof$9; var isObject$3 = isObject$p; var isSymbol = isSymbol$6; var create$1 = objectCreate; var setPrototypeOf = objectSetPrototypeOf; var getOwnPropertyNames = objectGetOwnPropertyNames.f; var typedArrayFrom = typedArrayFrom$1; var forEach = arrayIteration.forEach; var setSpecies$1 = setSpecies$4; var definePropertyModule = objectDefineProperty; var getOwnPropertyDescriptorModule = objectGetOwnPropertyDescriptor; var InternalStateModule$2 = internalState; var inheritIfRequired = inheritIfRequired$3; var getInternalState = InternalStateModule$2.get; var setInternalState$2 = InternalStateModule$2.set; var nativeDefineProperty = definePropertyModule.f; var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; var round = Math.round; var RangeError$1 = global$7.RangeError; var ArrayBuffer$2 = ArrayBufferModule.ArrayBuffer; var DataView$1 = ArrayBufferModule.DataView; var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore$o.NATIVE_ARRAY_BUFFER_VIEWS; var TYPED_ARRAY_CONSTRUCTOR$1 = ArrayBufferViewCore$o.TYPED_ARRAY_CONSTRUCTOR; var TYPED_ARRAY_TAG = ArrayBufferViewCore$o.TYPED_ARRAY_TAG; var TypedArray = ArrayBufferViewCore$o.TypedArray; var TypedArrayPrototype = ArrayBufferViewCore$o.TypedArrayPrototype; var aTypedArrayConstructor$1 = ArrayBufferViewCore$o.aTypedArrayConstructor; var isTypedArray = ArrayBufferViewCore$o.isTypedArray; var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; var WRONG_LENGTH = 'Wrong length'; var fromList = function (C, list) { var index = 0; var length = list.length; var result = new (aTypedArrayConstructor$1(C))(length); while (length > index) result[index] = list[index++]; return result; }; var addGetter = function (it, key) { nativeDefineProperty(it, key, { get: function () { return getInternalState(this)[key]; } }); }; var isArrayBuffer = function (it) { var klass; return it instanceof ArrayBuffer$2 || (klass = classof$2(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer'; }; var isTypedArrayIndex = function (target, key) { return isTypedArray(target) && !isSymbol(key) && key in target && isInteger$1(+key) && key >= 0; }; var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) { key = toPropertyKey(key); return isTypedArrayIndex(target, key) ? createPropertyDescriptor$1(2, target[key]) : nativeGetOwnPropertyDescriptor(target, key); }; var wrappedDefineProperty = function defineProperty(target, key, descriptor) { key = toPropertyKey(key); if (isTypedArrayIndex(target, key) && isObject$3(descriptor) && has$1(descriptor, 'value') && !has$1(descriptor, 'get') && !has$1(descriptor, 'set') // TODO: add validation descriptor w/o calling accessors && !descriptor.configurable && (!has$1(descriptor, 'writable') || descriptor.writable) && (!has$1(descriptor, 'enumerable') || descriptor.enumerable) ) { target[key] = descriptor.value; return target; } return nativeDefineProperty(target, key, descriptor); }; if (DESCRIPTORS$2) { if (!NATIVE_ARRAY_BUFFER_VIEWS) { getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor; definePropertyModule.f = wrappedDefineProperty; addGetter(TypedArrayPrototype, 'buffer'); addGetter(TypedArrayPrototype, 'byteOffset'); addGetter(TypedArrayPrototype, 'byteLength'); addGetter(TypedArrayPrototype, 'length'); } $$a({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor, defineProperty: wrappedDefineProperty }); typedArrayConstructor.exports = function (TYPE, wrapper, CLAMPED) { var BYTES = TYPE.match(/\d+$/)[0] / 8; var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array'; var GETTER = 'get' + TYPE; var SETTER = 'set' + TYPE; var NativeTypedArrayConstructor = global$7[CONSTRUCTOR_NAME]; var TypedArrayConstructor = NativeTypedArrayConstructor; var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype; var exported = {}; var getter = function (that, index) { var data = getInternalState(that); return data.view[GETTER](index * BYTES + data.byteOffset, true); }; var setter = function (that, index, value) { var data = getInternalState(that); if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF; data.view[SETTER](index * BYTES + data.byteOffset, value, true); }; var addElement = function (that, index) { nativeDefineProperty(that, index, { get: function () { return getter(this, index); }, set: function (value) { return setter(this, index, value); }, enumerable: true }); }; if (!NATIVE_ARRAY_BUFFER_VIEWS) { TypedArrayConstructor = wrapper(function (that, data, offset, $length) { anInstance$2(that, TypedArrayConstructor, CONSTRUCTOR_NAME); var index = 0; var byteOffset = 0; var buffer, byteLength, length; if (!isObject$3(data)) { length = toIndex(data); byteLength = length * BYTES; buffer = new ArrayBuffer$2(byteLength); } else if (isArrayBuffer(data)) { buffer = data; byteOffset = toOffset$1(offset, BYTES); var $len = data.byteLength; if ($length === undefined) { if ($len % BYTES) throw RangeError$1(WRONG_LENGTH); byteLength = $len - byteOffset; if (byteLength < 0) throw RangeError$1(WRONG_LENGTH); } else { byteLength = toLength$c($length) * BYTES; if (byteLength + byteOffset > $len) throw RangeError$1(WRONG_LENGTH); } length = byteLength / BYTES; } else if (isTypedArray(data)) { return fromList(TypedArrayConstructor, data); } else { return typedArrayFrom.call(TypedArrayConstructor, data); } setInternalState$2(that, { buffer: buffer, byteOffset: byteOffset, byteLength: byteLength, length: length, view: new DataView$1(buffer) }); while (index < length) addElement(that, index++); }); if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create$1(TypedArrayPrototype); } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) { TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) { anInstance$2(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME); return inheritIfRequired(function () { if (!isObject$3(data)) return new NativeTypedArrayConstructor(toIndex(data)); if (isArrayBuffer(data)) return $length !== undefined ? new NativeTypedArrayConstructor(data, toOffset$1(typedArrayOffset, BYTES), $length) : typedArrayOffset !== undefined ? new NativeTypedArrayConstructor(data, toOffset$1(typedArrayOffset, BYTES)) : new NativeTypedArrayConstructor(data); if (isTypedArray(data)) return fromList(TypedArrayConstructor, data); return typedArrayFrom.call(TypedArrayConstructor, data); }(), dummy, TypedArrayConstructor); }); if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) { if (!(key in TypedArrayConstructor)) { createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]); } }); TypedArrayConstructor.prototype = TypedArrayConstructorPrototype; } if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) { createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor); } createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_CONSTRUCTOR$1, TypedArrayConstructor); if (TYPED_ARRAY_TAG) { createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME); } exported[CONSTRUCTOR_NAME] = TypedArrayConstructor; $$a({ global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS }, exported); if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) { createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES); } if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) { createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES); } setSpecies$1(CONSTRUCTOR_NAME); }; } else typedArrayConstructor.exports = function () { /* empty */ }; var createTypedArrayConstructor = typedArrayConstructor.exports; // `Uint8Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Uint8', function (init) { return function Uint8Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); var toObject$5 = toObject$g; var toAbsoluteIndex$2 = toAbsoluteIndex$6; var toLength$b = toLength$o; var min$4 = Math.min; // `Array.prototype.copyWithin` method implementation // https://tc39.es/ecma262/#sec-array.prototype.copywithin // eslint-disable-next-line es/no-array-prototype-copywithin -- safe var arrayCopyWithin = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { var O = toObject$5(this); var len = toLength$b(O.length); var to = toAbsoluteIndex$2(target, len); var from = toAbsoluteIndex$2(start, len); var end = arguments.length > 2 ? arguments[2] : undefined; var count = min$4((end === undefined ? len : toAbsoluteIndex$2(end, len)) - from, len - to); var inc = 1; if (from < to && to < from + count) { inc = -1; from += count - 1; to += count - 1; } while (count-- > 0) { if (from in O) O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }; var ArrayBufferViewCore$n = arrayBufferViewCore; var $copyWithin = arrayCopyWithin; var aTypedArray$m = ArrayBufferViewCore$n.aTypedArray; var exportTypedArrayMethod$n = ArrayBufferViewCore$n.exportTypedArrayMethod; // `%TypedArray%.prototype.copyWithin` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin exportTypedArrayMethod$n('copyWithin', function copyWithin(target, start /* , end */) { return $copyWithin.call(aTypedArray$m(this), target, start, arguments.length > 2 ? arguments[2] : undefined); }); var ArrayBufferViewCore$m = arrayBufferViewCore; var $every = arrayIteration.every; var aTypedArray$l = ArrayBufferViewCore$m.aTypedArray; var exportTypedArrayMethod$m = ArrayBufferViewCore$m.exportTypedArrayMethod; // `%TypedArray%.prototype.every` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.every exportTypedArrayMethod$m('every', function every(callbackfn /* , thisArg */) { return $every(aTypedArray$l(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); var ArrayBufferViewCore$l = arrayBufferViewCore; var $fill = arrayFill$1; var aTypedArray$k = ArrayBufferViewCore$l.aTypedArray; var exportTypedArrayMethod$l = ArrayBufferViewCore$l.exportTypedArrayMethod; // `%TypedArray%.prototype.fill` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill // eslint-disable-next-line no-unused-vars -- required for `.length` exportTypedArrayMethod$l('fill', function fill(value /* , start, end */) { return $fill.apply(aTypedArray$k(this), arguments); }); var arrayFromConstructorAndList$1 = function (Constructor, list) { var index = 0; var length = list.length; var result = new Constructor(length); while (length > index) result[index] = list[index++]; return result; }; var ArrayBufferViewCore$k = arrayBufferViewCore; var speciesConstructor$1 = speciesConstructor$3; var TYPED_ARRAY_CONSTRUCTOR = ArrayBufferViewCore$k.TYPED_ARRAY_CONSTRUCTOR; var aTypedArrayConstructor = ArrayBufferViewCore$k.aTypedArrayConstructor; // a part of `TypedArraySpeciesCreate` abstract operation // https://tc39.es/ecma262/#typedarray-species-create var typedArraySpeciesConstructor$4 = function (originalArray) { return aTypedArrayConstructor(speciesConstructor$1(originalArray, originalArray[TYPED_ARRAY_CONSTRUCTOR])); }; var arrayFromConstructorAndList = arrayFromConstructorAndList$1; var typedArraySpeciesConstructor$3 = typedArraySpeciesConstructor$4; var typedArrayFromSpeciesAndList = function (instance, list) { return arrayFromConstructorAndList(typedArraySpeciesConstructor$3(instance), list); }; var ArrayBufferViewCore$j = arrayBufferViewCore; var $filter = arrayIteration.filter; var fromSpeciesAndList = typedArrayFromSpeciesAndList; var aTypedArray$j = ArrayBufferViewCore$j.aTypedArray; var exportTypedArrayMethod$k = ArrayBufferViewCore$j.exportTypedArrayMethod; // `%TypedArray%.prototype.filter` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter exportTypedArrayMethod$k('filter', function filter(callbackfn /* , thisArg */) { var list = $filter(aTypedArray$j(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); return fromSpeciesAndList(this, list); }); var ArrayBufferViewCore$i = arrayBufferViewCore; var $find$1 = arrayIteration.find; var aTypedArray$i = ArrayBufferViewCore$i.aTypedArray; var exportTypedArrayMethod$j = ArrayBufferViewCore$i.exportTypedArrayMethod; // `%TypedArray%.prototype.find` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.find exportTypedArrayMethod$j('find', function find(predicate /* , thisArg */) { return $find$1(aTypedArray$i(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }); var ArrayBufferViewCore$h = arrayBufferViewCore; var $findIndex = arrayIteration.findIndex; var aTypedArray$h = ArrayBufferViewCore$h.aTypedArray; var exportTypedArrayMethod$i = ArrayBufferViewCore$h.exportTypedArrayMethod; // `%TypedArray%.prototype.findIndex` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex exportTypedArrayMethod$i('findIndex', function findIndex(predicate /* , thisArg */) { return $findIndex(aTypedArray$h(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }); var ArrayBufferViewCore$g = arrayBufferViewCore; var $forEach = arrayIteration.forEach; var aTypedArray$g = ArrayBufferViewCore$g.aTypedArray; var exportTypedArrayMethod$h = ArrayBufferViewCore$g.exportTypedArrayMethod; // `%TypedArray%.prototype.forEach` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach exportTypedArrayMethod$h('forEach', function forEach(callbackfn /* , thisArg */) { $forEach(aTypedArray$g(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); var ArrayBufferViewCore$f = arrayBufferViewCore; var $includes = arrayIncludes.includes; var aTypedArray$f = ArrayBufferViewCore$f.aTypedArray; var exportTypedArrayMethod$g = ArrayBufferViewCore$f.exportTypedArrayMethod; // `%TypedArray%.prototype.includes` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes exportTypedArrayMethod$g('includes', function includes(searchElement /* , fromIndex */) { return $includes(aTypedArray$f(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }); var ArrayBufferViewCore$e = arrayBufferViewCore; var $indexOf = arrayIncludes.indexOf; var aTypedArray$e = ArrayBufferViewCore$e.aTypedArray; var exportTypedArrayMethod$f = ArrayBufferViewCore$e.exportTypedArrayMethod; // `%TypedArray%.prototype.indexOf` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof exportTypedArrayMethod$f('indexOf', function indexOf(searchElement /* , fromIndex */) { return $indexOf(aTypedArray$e(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }); var global$6 = global$D; var ArrayBufferViewCore$d = arrayBufferViewCore; var ArrayIterators = es_array_iterator; var wellKnownSymbol$4 = wellKnownSymbol$s; var ITERATOR$2 = wellKnownSymbol$4('iterator'); var Uint8Array$2 = global$6.Uint8Array; var arrayValues = ArrayIterators.values; var arrayKeys = ArrayIterators.keys; var arrayEntries = ArrayIterators.entries; var aTypedArray$d = ArrayBufferViewCore$d.aTypedArray; var exportTypedArrayMethod$e = ArrayBufferViewCore$d.exportTypedArrayMethod; var nativeTypedArrayIterator = Uint8Array$2 && Uint8Array$2.prototype[ITERATOR$2]; var CORRECT_ITER_NAME = !!nativeTypedArrayIterator && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined); var typedArrayValues = function values() { return arrayValues.call(aTypedArray$d(this)); }; // `%TypedArray%.prototype.entries` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries exportTypedArrayMethod$e('entries', function entries() { return arrayEntries.call(aTypedArray$d(this)); }); // `%TypedArray%.prototype.keys` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys exportTypedArrayMethod$e('keys', function keys() { return arrayKeys.call(aTypedArray$d(this)); }); // `%TypedArray%.prototype.values` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.values exportTypedArrayMethod$e('values', typedArrayValues, !CORRECT_ITER_NAME); // `%TypedArray%.prototype[@@iterator]` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype-@@iterator exportTypedArrayMethod$e(ITERATOR$2, typedArrayValues, !CORRECT_ITER_NAME); var ArrayBufferViewCore$c = arrayBufferViewCore; var aTypedArray$c = ArrayBufferViewCore$c.aTypedArray; var exportTypedArrayMethod$d = ArrayBufferViewCore$c.exportTypedArrayMethod; var $join = [].join; // `%TypedArray%.prototype.join` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.join // eslint-disable-next-line no-unused-vars -- required for `.length` exportTypedArrayMethod$d('join', function join(separator) { return $join.apply(aTypedArray$c(this), arguments); }); /* eslint-disable es/no-array-prototype-lastindexof -- safe */ var toIndexedObject = toIndexedObject$c; var toInteger$2 = toInteger$a; var toLength$a = toLength$o; var arrayMethodIsStrict$1 = arrayMethodIsStrict$4; var min$3 = Math.min; var $lastIndexOf$1 = [].lastIndexOf; var NEGATIVE_ZERO = !!$lastIndexOf$1 && 1 / [1].lastIndexOf(1, -0) < 0; var STRICT_METHOD$1 = arrayMethodIsStrict$1('lastIndexOf'); var FORCED$4 = NEGATIVE_ZERO || !STRICT_METHOD$1; // `Array.prototype.lastIndexOf` method implementation // https://tc39.es/ecma262/#sec-array.prototype.lastindexof var arrayLastIndexOf = FORCED$4 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { // convert -0 to +0 if (NEGATIVE_ZERO) return $lastIndexOf$1.apply(this, arguments) || 0; var O = toIndexedObject(this); var length = toLength$a(O.length); var index = length - 1; if (arguments.length > 1) index = min$3(index, toInteger$2(arguments[1])); if (index < 0) index = length + index; for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0; return -1; } : $lastIndexOf$1; var ArrayBufferViewCore$b = arrayBufferViewCore; var $lastIndexOf = arrayLastIndexOf; var aTypedArray$b = ArrayBufferViewCore$b.aTypedArray; var exportTypedArrayMethod$c = ArrayBufferViewCore$b.exportTypedArrayMethod; // `%TypedArray%.prototype.lastIndexOf` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof // eslint-disable-next-line no-unused-vars -- required for `.length` exportTypedArrayMethod$c('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) { return $lastIndexOf.apply(aTypedArray$b(this), arguments); }); var ArrayBufferViewCore$a = arrayBufferViewCore; var $map = arrayIteration.map; var typedArraySpeciesConstructor$2 = typedArraySpeciesConstructor$4; var aTypedArray$a = ArrayBufferViewCore$a.aTypedArray; var exportTypedArrayMethod$b = ArrayBufferViewCore$a.exportTypedArrayMethod; // `%TypedArray%.prototype.map` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.map exportTypedArrayMethod$b('map', function map(mapfn /* , thisArg */) { return $map(aTypedArray$a(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) { return new (typedArraySpeciesConstructor$2(O))(length); }); }); var aFunction$2 = aFunction$9; var toObject$4 = toObject$g; var IndexedObject$1 = indexedObject; var toLength$9 = toLength$o; // `Array.prototype.{ reduce, reduceRight }` methods implementation var createMethod = function (IS_RIGHT) { return function (that, callbackfn, argumentsLength, memo) { aFunction$2(callbackfn); var O = toObject$4(that); var self = IndexedObject$1(O); var length = toLength$9(O.length); var index = IS_RIGHT ? length - 1 : 0; var i = IS_RIGHT ? -1 : 1; if (argumentsLength < 2) while (true) { if (index in self) { memo = self[index]; index += i; break; } index += i; if (IS_RIGHT ? index < 0 : length <= index) { throw TypeError('Reduce of empty array with no initial value'); } } for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) { memo = callbackfn(memo, self[index], index, O); } return memo; }; }; var arrayReduce = { // `Array.prototype.reduce` method // https://tc39.es/ecma262/#sec-array.prototype.reduce left: createMethod(false), // `Array.prototype.reduceRight` method // https://tc39.es/ecma262/#sec-array.prototype.reduceright right: createMethod(true) }; var ArrayBufferViewCore$9 = arrayBufferViewCore; var $reduce = arrayReduce.left; var aTypedArray$9 = ArrayBufferViewCore$9.aTypedArray; var exportTypedArrayMethod$a = ArrayBufferViewCore$9.exportTypedArrayMethod; // `%TypedArray%.prototype.reduce` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce exportTypedArrayMethod$a('reduce', function reduce(callbackfn /* , initialValue */) { return $reduce(aTypedArray$9(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); }); var ArrayBufferViewCore$8 = arrayBufferViewCore; var $reduceRight = arrayReduce.right; var aTypedArray$8 = ArrayBufferViewCore$8.aTypedArray; var exportTypedArrayMethod$9 = ArrayBufferViewCore$8.exportTypedArrayMethod; // `%TypedArray%.prototype.reduceRicht` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright exportTypedArrayMethod$9('reduceRight', function reduceRight(callbackfn /* , initialValue */) { return $reduceRight(aTypedArray$8(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); }); var ArrayBufferViewCore$7 = arrayBufferViewCore; var aTypedArray$7 = ArrayBufferViewCore$7.aTypedArray; var exportTypedArrayMethod$8 = ArrayBufferViewCore$7.exportTypedArrayMethod; var floor$3 = Math.floor; // `%TypedArray%.prototype.reverse` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse exportTypedArrayMethod$8('reverse', function reverse() { var that = this; var length = aTypedArray$7(that).length; var middle = floor$3(length / 2); var index = 0; var value; while (index < middle) { value = that[index]; that[index++] = that[--length]; that[length] = value; } return that; }); var ArrayBufferViewCore$6 = arrayBufferViewCore; var toLength$8 = toLength$o; var toOffset = toOffset$2; var toObject$3 = toObject$g; var fails$9 = fails$B; var aTypedArray$6 = ArrayBufferViewCore$6.aTypedArray; var exportTypedArrayMethod$7 = ArrayBufferViewCore$6.exportTypedArrayMethod; var FORCED$3 = fails$9(function () { // eslint-disable-next-line es/no-typed-arrays -- required for testing new Int8Array(1).set({}); }); // `%TypedArray%.prototype.set` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.set exportTypedArrayMethod$7('set', function set(arrayLike /* , offset */) { aTypedArray$6(this); var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1); var length = this.length; var src = toObject$3(arrayLike); var len = toLength$8(src.length); var index = 0; if (len + offset > length) throw RangeError('Wrong length'); while (index < len) this[offset + index] = src[index++]; }, FORCED$3); var ArrayBufferViewCore$5 = arrayBufferViewCore; var typedArraySpeciesConstructor$1 = typedArraySpeciesConstructor$4; var fails$8 = fails$B; var aTypedArray$5 = ArrayBufferViewCore$5.aTypedArray; var exportTypedArrayMethod$6 = ArrayBufferViewCore$5.exportTypedArrayMethod; var $slice$1 = [].slice; var FORCED$2 = fails$8(function () { // eslint-disable-next-line es/no-typed-arrays -- required for testing new Int8Array(1).slice(); }); // `%TypedArray%.prototype.slice` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice exportTypedArrayMethod$6('slice', function slice(start, end) { var list = $slice$1.call(aTypedArray$5(this), start, end); var C = typedArraySpeciesConstructor$1(this); var index = 0; var length = list.length; var result = new C(length); while (length > index) result[index] = list[index++]; return result; }, FORCED$2); var ArrayBufferViewCore$4 = arrayBufferViewCore; var $some = arrayIteration.some; var aTypedArray$4 = ArrayBufferViewCore$4.aTypedArray; var exportTypedArrayMethod$5 = ArrayBufferViewCore$4.exportTypedArrayMethod; // `%TypedArray%.prototype.some` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.some exportTypedArrayMethod$5('some', function some(callbackfn /* , thisArg */) { return $some(aTypedArray$4(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); // TODO: use something more complex like timsort? var floor$2 = Math.floor; var mergeSort = function (array, comparefn) { var length = array.length; var middle = floor$2(length / 2); return length < 8 ? insertionSort(array, comparefn) : merge( mergeSort(array.slice(0, middle), comparefn), mergeSort(array.slice(middle), comparefn), comparefn ); }; var insertionSort = function (array, comparefn) { var length = array.length; var i = 1; var element, j; while (i < length) { j = i; element = array[i]; while (j && comparefn(array[j - 1], element) > 0) { array[j] = array[--j]; } if (j !== i++) array[j] = element; } return array; }; var merge = function (left, right, comparefn) { var llength = left.length; var rlength = right.length; var lindex = 0; var rindex = 0; var result = []; while (lindex < llength || rindex < rlength) { if (lindex < llength && rindex < rlength) { result.push(comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]); } else { result.push(lindex < llength ? left[lindex++] : right[rindex++]); } } return result; }; var arraySort = mergeSort; var userAgent$1 = engineUserAgent; var firefox = userAgent$1.match(/firefox\/(\d+)/i); var engineFfVersion = !!firefox && +firefox[1]; var UA = engineUserAgent; var engineIsIeOrEdge = /MSIE|Trident/.test(UA); var userAgent = engineUserAgent; var webkit = userAgent.match(/AppleWebKit\/(\d+)\./); var engineWebkitVersion = !!webkit && +webkit[1]; var ArrayBufferViewCore$3 = arrayBufferViewCore; var global$5 = global$D; var fails$7 = fails$B; var aFunction$1 = aFunction$9; var toLength$7 = toLength$o; var internalSort$1 = arraySort; var FF$1 = engineFfVersion; var IE_OR_EDGE$1 = engineIsIeOrEdge; var V8$1 = engineV8Version; var WEBKIT$1 = engineWebkitVersion; var aTypedArray$3 = ArrayBufferViewCore$3.aTypedArray; var exportTypedArrayMethod$4 = ArrayBufferViewCore$3.exportTypedArrayMethod; var Uint16Array = global$5.Uint16Array; var nativeSort$1 = Uint16Array && Uint16Array.prototype.sort; // WebKit var ACCEPT_INCORRECT_ARGUMENTS = !!nativeSort$1 && !fails$7(function () { var array = new Uint16Array(2); array.sort(null); array.sort({}); }); var STABLE_SORT$1 = !!nativeSort$1 && !fails$7(function () { // feature detection can be too slow, so check engines versions if (V8$1) return V8$1 < 74; if (FF$1) return FF$1 < 67; if (IE_OR_EDGE$1) return true; if (WEBKIT$1) return WEBKIT$1 < 602; var array = new Uint16Array(516); var expected = Array(516); var index, mod; for (index = 0; index < 516; index++) { mod = index % 4; array[index] = 515 - index; expected[index] = index - 2 * mod + 3; } array.sort(function (a, b) { return (a / 4 | 0) - (b / 4 | 0); }); for (index = 0; index < 516; index++) { if (array[index] !== expected[index]) return true; } }); var getSortCompare$1 = function (comparefn) { return function (x, y) { if (comparefn !== undefined) return +comparefn(x, y) || 0; // eslint-disable-next-line no-self-compare -- NaN check if (y !== y) return -1; // eslint-disable-next-line no-self-compare -- NaN check if (x !== x) return 1; if (x === 0 && y === 0) return 1 / x > 0 && 1 / y < 0 ? 1 : -1; return x > y; }; }; // `%TypedArray%.prototype.sort` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort exportTypedArrayMethod$4('sort', function sort(comparefn) { var array = this; if (comparefn !== undefined) aFunction$1(comparefn); if (STABLE_SORT$1) return nativeSort$1.call(array, comparefn); aTypedArray$3(array); var arrayLength = toLength$7(array.length); var items = Array(arrayLength); var index; for (index = 0; index < arrayLength; index++) { items[index] = array[index]; } items = internalSort$1(array, getSortCompare$1(comparefn)); for (index = 0; index < arrayLength; index++) { array[index] = items[index]; } return array; }, !STABLE_SORT$1 || ACCEPT_INCORRECT_ARGUMENTS); var ArrayBufferViewCore$2 = arrayBufferViewCore; var toLength$6 = toLength$o; var toAbsoluteIndex$1 = toAbsoluteIndex$6; var typedArraySpeciesConstructor = typedArraySpeciesConstructor$4; var aTypedArray$2 = ArrayBufferViewCore$2.aTypedArray; var exportTypedArrayMethod$3 = ArrayBufferViewCore$2.exportTypedArrayMethod; // `%TypedArray%.prototype.subarray` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray exportTypedArrayMethod$3('subarray', function subarray(begin, end) { var O = aTypedArray$2(this); var length = O.length; var beginIndex = toAbsoluteIndex$1(begin, length); var C = typedArraySpeciesConstructor(O); return new C( O.buffer, O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT, toLength$6((end === undefined ? length : toAbsoluteIndex$1(end, length)) - beginIndex) ); }); var global$4 = global$D; var ArrayBufferViewCore$1 = arrayBufferViewCore; var fails$6 = fails$B; var Int8Array$1 = global$4.Int8Array; var aTypedArray$1 = ArrayBufferViewCore$1.aTypedArray; var exportTypedArrayMethod$2 = ArrayBufferViewCore$1.exportTypedArrayMethod; var $toLocaleString = [].toLocaleString; var $slice = [].slice; // iOS Safari 6.x fails here var TO_LOCALE_STRING_BUG = !!Int8Array$1 && fails$6(function () { $toLocaleString.call(new Int8Array$1(1)); }); var FORCED$1 = fails$6(function () { return [1, 2].toLocaleString() != new Int8Array$1([1, 2]).toLocaleString(); }) || !fails$6(function () { Int8Array$1.prototype.toLocaleString.call([1, 2]); }); // `%TypedArray%.prototype.toLocaleString` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring exportTypedArrayMethod$2('toLocaleString', function toLocaleString() { return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray$1(this)) : aTypedArray$1(this), arguments); }, FORCED$1); var exportTypedArrayMethod$1 = arrayBufferViewCore.exportTypedArrayMethod; var fails$5 = fails$B; var global$3 = global$D; var Uint8Array$1 = global$3.Uint8Array; var Uint8ArrayPrototype = Uint8Array$1 && Uint8Array$1.prototype || {}; var arrayToString = [].toString; var arrayJoin = [].join; if (fails$5(function () { arrayToString.call({}); })) { arrayToString = function toString() { return arrayJoin.call(this); }; } var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString; // `%TypedArray%.prototype.toString` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tostring exportTypedArrayMethod$1('toString', arrayToString, IS_NOT_ARRAY_METHOD); var isObject$2 = isObject$p; var classof$1 = classofRaw$1; var wellKnownSymbol$3 = wellKnownSymbol$s; var MATCH$1 = wellKnownSymbol$3('match'); // `IsRegExp` abstract operation // https://tc39.es/ecma262/#sec-isregexp var isRegexp = function (it) { var isRegExp; return isObject$2(it) && ((isRegExp = it[MATCH$1]) !== undefined ? !!isRegExp : classof$1(it) == 'RegExp'); }; var fixRegExpWellKnownSymbolLogic$2 = fixRegexpWellKnownSymbolLogic; var isRegExp$1 = isRegexp; var anObject$3 = anObject$k; var requireObjectCoercible$4 = requireObjectCoercible$a; var speciesConstructor = speciesConstructor$3; var advanceStringIndex$1 = advanceStringIndex$3; var toLength$5 = toLength$o; var toString$5 = toString$d; var callRegExpExec = regexpExecAbstract; var regexpExec = regexpExec$3; var stickyHelpers = regexpStickyHelpers; var fails$4 = fails$B; var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y; var arrayPush = [].push; var min$2 = Math.min; var MAX_UINT32 = 0xFFFFFFFF; // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec // Weex JS has frozen built-in prototypes, so use try / catch wrapper var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails$4(function () { // eslint-disable-next-line regexp/no-empty-group -- required for testing var re = /(?:)/; var originalExec = re.exec; re.exec = function () { return originalExec.apply(this, arguments); }; var result = 'ab'.split(re); return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b'; }); // @@split logic fixRegExpWellKnownSymbolLogic$2('split', function (SPLIT, nativeSplit, maybeCallNative) { var internalSplit; if ( 'abbc'.split(/(b)*/)[1] == 'c' || // eslint-disable-next-line regexp/no-empty-group -- required for testing 'test'.split(/(?:)/, -1).length != 4 || 'ab'.split(/(?:ab)*/).length != 2 || '.'.split(/(.?)(.?)/).length != 4 || // eslint-disable-next-line regexp/no-empty-capturing-group, regexp/no-empty-group -- required for testing '.'.split(/()()/).length > 1 || ''.split(/.?/).length ) { // based on es5-shim implementation, need to rework it internalSplit = function (separator, limit) { var string = toString$5(requireObjectCoercible$4(this)); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; if (lim === 0) return []; if (separator === undefined) return [string]; // If `separator` is not a regex, use native split if (!isRegExp$1(separator)) { return nativeSplit.call(string, separator, lim); } var output = []; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); var lastLastIndex = 0; // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var match, lastIndex, lastLength; while (match = regexpExec.call(separatorCopy, string)) { lastIndex = separatorCopy.lastIndex; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1)); lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= lim) break; } if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop } if (lastLastIndex === string.length) { if (lastLength || !separatorCopy.test('')) output.push(''); } else output.push(string.slice(lastLastIndex)); return output.length > lim ? output.slice(0, lim) : output; }; // Chakra, V8 } else if ('0'.split(undefined, 0).length) { internalSplit = function (separator, limit) { return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit); }; } else internalSplit = nativeSplit; return [ // `String.prototype.split` method // https://tc39.es/ecma262/#sec-string.prototype.split function split(separator, limit) { var O = requireObjectCoercible$4(this); var splitter = separator == undefined ? undefined : separator[SPLIT]; return splitter !== undefined ? splitter.call(separator, O, limit) : internalSplit.call(toString$5(O), separator, limit); }, // `RegExp.prototype[@@split]` method // https://tc39.es/ecma262/#sec-regexp.prototype-@@split // // NOTE: This cannot be properly polyfilled in engines that don't support // the 'y' flag. function (string, limit) { var rx = anObject$3(this); var S = toString$5(string); var res = maybeCallNative(internalSplit, rx, S, limit, internalSplit !== nativeSplit); if (res.done) return res.value; var C = speciesConstructor(rx, RegExp); var unicodeMatching = rx.unicode; var flags = (rx.ignoreCase ? 'i' : '') + (rx.multiline ? 'm' : '') + (rx.unicode ? 'u' : '') + (UNSUPPORTED_Y ? 'g' : 'y'); // ^(? + rx + ) is needed, in combination with some S slicing, to // simulate the 'y' flag. var splitter = new C(UNSUPPORTED_Y ? '^(?:' + rx.source + ')' : rx, flags); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; if (lim === 0) return []; if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : []; var p = 0; var q = 0; var A = []; while (q < S.length) { splitter.lastIndex = UNSUPPORTED_Y ? 0 : q; var z = callRegExpExec(splitter, UNSUPPORTED_Y ? S.slice(q) : S); var e; if ( z === null || (e = min$2(toLength$5(splitter.lastIndex + (UNSUPPORTED_Y ? q : 0)), S.length)) === p ) { q = advanceStringIndex$1(S, q, unicodeMatching); } else { A.push(S.slice(p, q)); if (A.length === lim) return A; for (var i = 1; i <= z.length - 1; i++) { A.push(z[i]); if (A.length === lim) return A; } q = p = e; } } A.push(S.slice(p)); return A; } ]; }, !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC, UNSUPPORTED_Y); var wrapNativeSuper = {exports: {}}; var isNativeFunction = {exports: {}}; (function (module) { function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; })(isNativeFunction); var construct = {exports: {}}; var isNativeReflectConstruct = {exports: {}}; (function (module) { function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; })(isNativeReflectConstruct); (function (module) { var setPrototypeOf = setPrototypeOf$3.exports; var isNativeReflectConstruct$1 = isNativeReflectConstruct.exports; function _construct(Parent, args, Class) { if (isNativeReflectConstruct$1()) { module.exports = _construct = Reflect.construct, module.exports.__esModule = true, module.exports["default"] = module.exports; } else { module.exports = _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) setPrototypeOf(instance, Class.prototype); return instance; }, module.exports.__esModule = true, module.exports["default"] = module.exports; } return _construct.apply(null, arguments); } module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; })(construct); (function (module) { var getPrototypeOf = getPrototypeOf$2.exports; var setPrototypeOf = setPrototypeOf$3.exports; var isNativeFunction$1 = isNativeFunction.exports; var construct$1 = construct.exports; function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !isNativeFunction$1(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct$1(Class, arguments, getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return setPrototypeOf(Wrapper, Class); }, module.exports.__esModule = true, module.exports["default"] = module.exports; return _wrapNativeSuper(Class); } module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; })(wrapNativeSuper); var platform$1 = {exports: {}}; (function (module, exports) { (function () { /** Used to determine if values are of the language type `Object`. */ var objectTypes = { 'function': true, 'object': true }; /** Used as a reference to the global object. */ var root = objectTypes[typeof window === "undefined" ? "undefined" : _typeof$3(window)] && window || this; /** Detect free variable `exports`. */ var freeExports = exports; /** Detect free variable `module`. */ var freeModule = module && !module.nodeType && module; /** Detect free variable `global` from Node.js or Browserified code and use it as `root`. */ var freeGlobal = freeExports && freeModule && _typeof$3(commonjsGlobal) == 'object' && commonjsGlobal; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { root = freeGlobal; } /** * Used as the maximum length of an array-like object. * See the [ES6 spec](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength) * for more details. */ var maxSafeInteger = Math.pow(2, 53) - 1; /** Regular expression to detect Opera. */ var reOpera = /\bOpera/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check for own properties of an object. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to resolve the internal `[[Class]]` of values. */ var toString = objectProto.toString; /*--------------------------------------------------------------------------*/ /** * Capitalizes a string value. * * @private * @param {string} string The string to capitalize. * @returns {string} The capitalized string. */ function capitalize(string) { string = String(string); return string.charAt(0).toUpperCase() + string.slice(1); } /** * A utility function to clean up the OS name. * * @private * @param {string} os The OS name to clean up. * @param {string} [pattern] A `RegExp` pattern matching the OS name. * @param {string} [label] A label for the OS. */ function cleanupOS(os, pattern, label) { // Platform tokens are defined at: // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx // http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx var data = { '10.0': '10', '6.4': '10 Technical Preview', '6.3': '8.1', '6.2': '8', '6.1': 'Server 2008 R2 / 7', '6.0': 'Server 2008 / Vista', '5.2': 'Server 2003 / XP 64-bit', '5.1': 'XP', '5.01': '2000 SP1', '5.0': '2000', '4.0': 'NT', '4.90': 'ME' }; // Detect Windows version from platform tokens. if (pattern && label && /^Win/i.test(os) && !/^Windows Phone /i.test(os) && (data = data[/[\d.]+$/.exec(os)])) { os = 'Windows ' + data; } // Correct character case and cleanup string. os = String(os); if (pattern && label) { os = os.replace(RegExp(pattern, 'i'), label); } os = format(os.replace(/ ce$/i, ' CE').replace(/\bhpw/i, 'web').replace(/\bMacintosh\b/, 'Mac OS').replace(/_PowerPC\b/i, ' OS').replace(/\b(OS X) [^ \d]+/i, '$1').replace(/\bMac (OS X)\b/, '$1').replace(/\/(\d)/, ' $1').replace(/_/g, '.').replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '').replace(/\bx86\.64\b/gi, 'x86_64').replace(/\b(Windows Phone) OS\b/, '$1').replace(/\b(Chrome OS \w+) [\d.]+\b/, '$1').split(' on ')[0]); return os; } /** * An iteration utility for arrays and objects. * * @private * @param {Array|Object} object The object to iterate over. * @param {Function} callback The function called per iteration. */ function each(object, callback) { var index = -1, length = object ? object.length : 0; if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) { while (++index < length) { callback(object[index], index, object); } } else { forOwn(object, callback); } } /** * Trim and conditionally capitalize string values. * * @private * @param {string} string The string to format. * @returns {string} The formatted string. */ function format(string) { string = trim(string); return /^(?:webOS|i(?:OS|P))/.test(string) ? string : capitalize(string); } /** * Iterates over an object's own properties, executing the `callback` for each. * * @private * @param {Object} object The object to iterate over. * @param {Function} callback The function executed per own property. */ function forOwn(object, callback) { for (var key in object) { if (hasOwnProperty.call(object, key)) { callback(object[key], key, object); } } } /** * Gets the internal `[[Class]]` of a value. * * @private * @param {*} value The value. * @returns {string} The `[[Class]]`. */ function getClassOf(value) { return value == null ? capitalize(value) : toString.call(value).slice(8, -1); } /** * Host objects can return type values that are different from their actual * data type. The objects we are concerned with usually return non-primitive * types of "object", "function", or "unknown". * * @private * @param {*} object The owner of the property. * @param {string} property The property to check. * @returns {boolean} Returns `true` if the property value is a non-primitive, else `false`. */ function isHostType(object, property) { var type = object != null ? _typeof$3(object[property]) : 'number'; return !/^(?:boolean|number|string|undefined)$/.test(type) && (type == 'object' ? !!object[property] : true); } /** * Prepares a string for use in a `RegExp` by making hyphens and spaces optional. * * @private * @param {string} string The string to qualify. * @returns {string} The qualified string. */ function qualify(string) { return String(string).replace(/([ -])(?!$)/g, '$1?'); } /** * A bare-bones `Array#reduce` like utility function. * * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function called per iteration. * @returns {*} The accumulated result. */ function reduce(array, callback) { var accumulator = null; each(array, function (value, index) { accumulator = callback(accumulator, value, index, array); }); return accumulator; } /** * Removes leading and trailing whitespace from a string. * * @private * @param {string} string The string to trim. * @returns {string} The trimmed string. */ function trim(string) { return String(string).replace(/^ +| +$/g, ''); } /*--------------------------------------------------------------------------*/ /** * Creates a new platform object. * * @memberOf platform * @param {Object|string} [ua=navigator.userAgent] The user agent string or * context object. * @returns {Object} A platform object. */ function parse(ua) { /** The environment context object. */ var context = root; /** Used to flag when a custom context is provided. */ var isCustomContext = ua && _typeof$3(ua) == 'object' && getClassOf(ua) != 'String'; // Juggle arguments. if (isCustomContext) { context = ua; ua = null; } /** Browser navigator object. */ var nav = context.navigator || {}; /** Browser user agent string. */ var userAgent = nav.userAgent || ''; ua || (ua = userAgent); /** Used to detect if browser is like Chrome. */ var likeChrome = isCustomContext ? !!nav.likeChrome : /\bChrome\b/.test(ua) && !/internal|\n/i.test(toString.toString()); /** Internal `[[Class]]` value shortcuts. */ var objectClass = 'Object', airRuntimeClass = isCustomContext ? objectClass : 'ScriptBridgingProxyObject', enviroClass = isCustomContext ? objectClass : 'Environment', javaClass = isCustomContext && context.java ? 'JavaPackage' : getClassOf(context.java), phantomClass = isCustomContext ? objectClass : 'RuntimeObject'; /** Detect Java environments. */ var java = /\bJava/.test(javaClass) && context.java; /** Detect Rhino. */ var rhino = java && getClassOf(context.environment) == enviroClass; /** A character to represent alpha. */ var alpha = java ? 'a' : "\u03B1"; /** A character to represent beta. */ var beta = java ? 'b' : "\u03B2"; /** Browser document object. */ var doc = context.document || {}; /** * Detect Opera browser (Presto-based). * http://www.howtocreate.co.uk/operaStuff/operaObject.html * http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini */ var opera = context.operamini || context.opera; /** Opera `[[Class]]`. */ var operaClass = reOpera.test(operaClass = isCustomContext && opera ? opera['[[Class]]'] : getClassOf(opera)) ? operaClass : opera = null; /*------------------------------------------------------------------------*/ /** Temporary variable used over the script's lifetime. */ var data; /** The CPU architecture. */ var arch = ua; /** Platform description array. */ var description = []; /** Platform alpha/beta indicator. */ var prerelease = null; /** A flag to indicate that environment features should be used to resolve the platform. */ var useFeatures = ua == userAgent; /** The browser/environment version. */ var version = useFeatures && opera && typeof opera.version == 'function' && opera.version(); /** A flag to indicate if the OS ends with "/ Version" */ var isSpecialCasedOS; /* Detectable layout engines (order is important). */ var layout = getLayout([{ 'label': 'EdgeHTML', 'pattern': 'Edge' }, 'Trident', { 'label': 'WebKit', 'pattern': 'AppleWebKit' }, 'iCab', 'Presto', 'NetFront', 'Tasman', 'KHTML', 'Gecko']); /* Detectable browser names (order is important). */ var name = getName(['Adobe AIR', 'Arora', 'Avant Browser', 'Breach', 'Camino', 'Electron', 'Epiphany', 'Fennec', 'Flock', 'Galeon', 'GreenBrowser', 'iCab', 'Iceweasel', 'K-Meleon', 'Konqueror', 'Lunascape', 'Maxthon', { 'label': 'Microsoft Edge', 'pattern': '(?:Edge|Edg|EdgA|EdgiOS)' }, 'Midori', 'Nook Browser', 'PaleMoon', 'PhantomJS', 'Raven', 'Rekonq', 'RockMelt', { 'label': 'Samsung Internet', 'pattern': 'SamsungBrowser' }, 'SeaMonkey', { 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, 'Sleipnir', 'SlimBrowser', { 'label': 'SRWare Iron', 'pattern': 'Iron' }, 'Sunrise', 'Swiftfox', 'Vivaldi', 'Waterfox', 'WebPositive', { 'label': 'Yandex Browser', 'pattern': 'YaBrowser' }, { 'label': 'UC Browser', 'pattern': 'UCBrowser' }, 'Opera Mini', { 'label': 'Opera Mini', 'pattern': 'OPiOS' }, 'Opera', { 'label': 'Opera', 'pattern': 'OPR' }, 'Chromium', 'Chrome', { 'label': 'Chrome', 'pattern': '(?:HeadlessChrome)' }, { 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' }, { 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' }, { 'label': 'Firefox for iOS', 'pattern': 'FxiOS' }, { 'label': 'IE', 'pattern': 'IEMobile' }, { 'label': 'IE', 'pattern': 'MSIE' }, 'Safari']); /* Detectable products (order is important). */ var product = getProduct([{ 'label': 'BlackBerry', 'pattern': 'BB10' }, 'BlackBerry', { 'label': 'Galaxy S', 'pattern': 'GT-I9000' }, { 'label': 'Galaxy S2', 'pattern': 'GT-I9100' }, { 'label': 'Galaxy S3', 'pattern': 'GT-I9300' }, { 'label': 'Galaxy S4', 'pattern': 'GT-I9500' }, { 'label': 'Galaxy S5', 'pattern': 'SM-G900' }, { 'label': 'Galaxy S6', 'pattern': 'SM-G920' }, { 'label': 'Galaxy S6 Edge', 'pattern': 'SM-G925' }, { 'label': 'Galaxy S7', 'pattern': 'SM-G930' }, { 'label': 'Galaxy S7 Edge', 'pattern': 'SM-G935' }, 'Google TV', 'Lumia', 'iPad', 'iPod', 'iPhone', 'Kindle', { 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, 'Nexus', 'Nook', 'PlayBook', 'PlayStation Vita', 'PlayStation', 'TouchPad', 'Transformer', { 'label': 'Wii U', 'pattern': 'WiiU' }, 'Wii', 'Xbox One', { 'label': 'Xbox 360', 'pattern': 'Xbox' }, 'Xoom']); /* Detectable manufacturers. */ var manufacturer = getManufacturer({ 'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 }, 'Alcatel': {}, 'Archos': {}, 'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 }, 'Asus': { 'Transformer': 1 }, 'Barnes & Noble': { 'Nook': 1 }, 'BlackBerry': { 'PlayBook': 1 }, 'Google': { 'Google TV': 1, 'Nexus': 1 }, 'HP': { 'TouchPad': 1 }, 'HTC': {}, 'Huawei': {}, 'Lenovo': {}, 'LG': {}, 'Microsoft': { 'Xbox': 1, 'Xbox One': 1 }, 'Motorola': { 'Xoom': 1 }, 'Nintendo': { 'Wii U': 1, 'Wii': 1 }, 'Nokia': { 'Lumia': 1 }, 'Oppo': {}, 'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1, 'Galaxy S3': 1, 'Galaxy S4': 1 }, 'Sony': { 'PlayStation': 1, 'PlayStation Vita': 1 }, 'Xiaomi': { 'Mi': 1, 'Redmi': 1 } }); /* Detectable operating systems (order is important). */ var os = getOS(['Windows Phone', 'KaiOS', 'Android', 'CentOS', { 'label': 'Chrome OS', 'pattern': 'CrOS' }, 'Debian', { 'label': 'DragonFly BSD', 'pattern': 'DragonFly' }, 'Fedora', 'FreeBSD', 'Gentoo', 'Haiku', 'Kubuntu', 'Linux Mint', 'OpenBSD', 'Red Hat', 'SuSE', 'Ubuntu', 'Xubuntu', 'Cygwin', 'Symbian OS', 'hpwOS', 'webOS ', 'webOS', 'Tablet OS', 'Tizen', 'Linux', 'Mac OS X', 'Macintosh', 'Mac', 'Windows 98;', 'Windows ']); /*------------------------------------------------------------------------*/ /** * Picks the layout engine from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {null|string} The detected layout engine. */ function getLayout(guesses) { return reduce(guesses, function (result, guess) { return result || RegExp('\\b' + (guess.pattern || qualify(guess)) + '\\b', 'i').exec(ua) && (guess.label || guess); }); } /** * Picks the manufacturer from an array of guesses. * * @private * @param {Array} guesses An object of guesses. * @returns {null|string} The detected manufacturer. */ function getManufacturer(guesses) { return reduce(guesses, function (result, value, key) { // Lookup the manufacturer by product or scan the UA for the manufacturer. return result || (value[product] || value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || RegExp('\\b' + qualify(key) + '(?:\\b|\\w*\\d)', 'i').exec(ua)) && key; }); } /** * Picks the browser name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {null|string} The detected browser name. */ function getName(guesses) { return reduce(guesses, function (result, guess) { return result || RegExp('\\b' + (guess.pattern || qualify(guess)) + '\\b', 'i').exec(ua) && (guess.label || guess); }); } /** * Picks the OS name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {null|string} The detected OS name. */ function getOS(guesses) { return reduce(guesses, function (result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) { result = cleanupOS(result, pattern, guess.label || guess); } return result; }); } /** * Picks the product name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {null|string} The detected product name. */ function getProduct(guesses) { return reduce(guesses, function (result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || RegExp('\\b' + pattern + ' *\\w+-[\\w]*', 'i').exec(ua) || RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua))) { // Split by forward slash and append product version if needed. if ((result = String(guess.label && !RegExp(pattern, 'i').test(guess.label) ? guess.label : result).split('/'))[1] && !/[\d.]+/.test(result[0])) { result[0] += ' ' + result[1]; } // Correct character case and cleanup string. guess = guess.label || guess; result = format(result[0].replace(RegExp(pattern, 'i'), guess).replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ').replace(RegExp('(' + guess + ')[-_.]?(\\w)', 'i'), '$1 $2')); } return result; }); } /** * Resolves the version using an array of UA patterns. * * @private * @param {Array} patterns An array of UA patterns. * @returns {null|string} The detected version. */ function getVersion(patterns) { return reduce(patterns, function (result, pattern) { return result || (RegExp(pattern + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null; }); } /** * Returns `platform.description` when the platform object is coerced to a string. * * @name toString * @memberOf platform * @returns {string} Returns `platform.description` if available, else an empty string. */ function toStringPlatform() { return this.description || ''; } /*------------------------------------------------------------------------*/ // Convert layout to an array so we can add extra details. layout && (layout = [layout]); // Detect Android products. // Browsers on Android devices typically provide their product IDS after "Android;" // up to "Build" or ") AppleWebKit". // Example: // "Mozilla/5.0 (Linux; Android 8.1.0; Moto G (5) Plus) AppleWebKit/537.36 // (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36" if (/\bAndroid\b/.test(os) && !product && (data = /\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(ua))) { product = trim(data[1]) // Replace any language codes (eg. "en-US"). .replace(/^[a-z]{2}-[a-z]{2};\s*/i, '') || null; } // Detect product names that contain their manufacturer's name. if (manufacturer && !product) { product = getProduct([manufacturer]); } else if (manufacturer && product) { product = product.replace(RegExp('^(' + qualify(manufacturer) + ')[-_.\\s]', 'i'), manufacturer + ' ').replace(RegExp('^(' + qualify(manufacturer) + ')[-_.]?(\\w)', 'i'), manufacturer + ' $2'); } // Clean up Google TV. if (data = /\bGoogle TV\b/.exec(product)) { product = data[0]; } // Detect simulators. if (/\bSimulator\b/i.test(ua)) { product = (product ? product + ' ' : '') + 'Simulator'; } // Detect Opera Mini 8+ running in Turbo/Uncompressed mode on iOS. if (name == 'Opera Mini' && /\bOPiOS\b/.test(ua)) { description.push('running in Turbo/Uncompressed mode'); } // Detect IE Mobile 11. if (name == 'IE' && /\blike iPhone OS\b/.test(ua)) { data = parse(ua.replace(/like iPhone OS/, '')); manufacturer = data.manufacturer; product = data.product; } // Detect iOS. else if (/^iP/.test(product)) { name || (name = 'Safari'); os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua)) ? ' ' + data[1].replace(/_/g, '.') : ''); } // Detect Kubuntu. else if (name == 'Konqueror' && /^Linux\b/i.test(os)) { os = 'Kubuntu'; } // Detect Android browsers. else if (manufacturer && manufacturer != 'Google' && (/Chrome/.test(name) && !/\bMobile Safari\b/i.test(ua) || /\bVita\b/.test(product)) || /\bAndroid\b/.test(os) && /^Chrome/.test(name) && /\bVersion\//i.test(ua)) { name = 'Android Browser'; os = /\bAndroid\b/.test(os) ? os : 'Android'; } // Detect Silk desktop/accelerated modes. else if (name == 'Silk') { if (!/\bMobi/i.test(ua)) { os = 'Android'; description.unshift('desktop mode'); } if (/Accelerated *= *true/i.test(ua)) { description.unshift('accelerated'); } } // Detect UC Browser speed mode. else if (name == 'UC Browser' && /\bUCWEB\b/.test(ua)) { description.push('speed mode'); } // Detect PaleMoon identifying as Firefox. else if (name == 'PaleMoon' && (data = /\bFirefox\/([\d.]+)\b/.exec(ua))) { description.push('identifying as Firefox ' + data[1]); } // Detect Firefox OS and products running Firefox. else if (name == 'Firefox' && (data = /\b(Mobile|Tablet|TV)\b/i.exec(ua))) { os || (os = 'Firefox OS'); product || (product = data[1]); } // Detect false positives for Firefox/Safari. else if (!name || (data = !/\bMinefield\b/i.test(ua) && /\b(?:Firefox|Safari)\b/.exec(name))) { // Escape the `/` for Firefox 1. if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) { // Clear name of false positives. name = null; } // Reassign a generic name. if ((data = product || manufacturer || os) && (product || manufacturer || /\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))) { name = /[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os) ? os : data) + ' Browser'; } } // Add Chrome version to description for Electron. else if (name == 'Electron' && (data = (/\bChrome\/([\d.]+)\b/.exec(ua) || 0)[1])) { description.push('Chromium ' + data); } // Detect non-Opera (Presto-based) versions (order is important). if (!version) { version = getVersion(['(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)', 'Version', qualify(name), '(?:Firefox|Minefield|NetFront)']); } // Detect stubborn layout engines. if (data = layout == 'iCab' && parseFloat(version) > 3 && 'WebKit' || /\bOpera\b/.test(name) && (/\bOPR\b/.test(ua) ? 'Blink' : 'Presto') || /\b(?:Midori|Nook|Safari)\b/i.test(ua) && !/^(?:Trident|EdgeHTML)$/.test(layout) && 'WebKit' || !layout && /\bMSIE\b/i.test(ua) && (os == 'Mac OS' ? 'Tasman' : 'Trident') || layout == 'WebKit' && /\bPlayStation\b(?! Vita\b)/i.test(name) && 'NetFront') { layout = [data]; } // Detect Windows Phone 7 desktop mode. if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) { name += ' Mobile'; os = 'Windows Phone ' + (/\+$/.test(data) ? data : data + '.x'); description.unshift('desktop mode'); } // Detect Windows Phone 8.x desktop mode. else if (/\bWPDesktop\b/i.test(ua)) { name = 'IE Mobile'; os = 'Windows Phone 8.x'; description.unshift('desktop mode'); version || (version = (/\brv:([\d.]+)/.exec(ua) || 0)[1]); } // Detect IE 11 identifying as other browsers. else if (name != 'IE' && layout == 'Trident' && (data = /\brv:([\d.]+)/.exec(ua))) { if (name) { description.push('identifying as ' + name + (version ? ' ' + version : '')); } name = 'IE'; version = data[1]; } // Leverage environment features. if (useFeatures) { // Detect server-side environments. // Rhino has a global function while others have a global object. if (isHostType(context, 'global')) { if (java) { data = java.lang.System; arch = data.getProperty('os.arch'); os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version'); } if (rhino) { try { version = context.require('ringo/engine').version.join('.'); name = 'RingoJS'; } catch (e) { if ((data = context.system) && data.global.system == context.system) { name = 'Narwhal'; os || (os = data[0].os || null); } } if (!name) { name = 'Rhino'; } } else if (_typeof$3(context.process) == 'object' && !context.process.browser && (data = context.process)) { if (_typeof$3(data.versions) == 'object') { if (typeof data.versions.electron == 'string') { description.push('Node ' + data.versions.node); name = 'Electron'; version = data.versions.electron; } else if (typeof data.versions.nw == 'string') { description.push('Chromium ' + version, 'Node ' + data.versions.node); name = 'NW.js'; version = data.versions.nw; } } if (!name) { name = 'Node.js'; arch = data.arch; os = data.platform; version = /[\d.]+/.exec(data.version); version = version ? version[0] : null; } } } // Detect Adobe AIR. else if (getClassOf(data = context.runtime) == airRuntimeClass) { name = 'Adobe AIR'; os = data.flash.system.Capabilities.os; } // Detect PhantomJS. else if (getClassOf(data = context.phantom) == phantomClass) { name = 'PhantomJS'; version = (data = data.version || null) && data.major + '.' + data.minor + '.' + data.patch; } // Detect IE compatibility modes. else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) { // We're in compatibility mode when the Trident version + 4 doesn't // equal the document mode. version = [version, doc.documentMode]; if ((data = +data[1] + 4) != version[1]) { description.push('IE ' + version[1] + ' mode'); layout && (layout[1] = ''); version[1] = data; } version = name == 'IE' ? String(version[1].toFixed(1)) : version[0]; } // Detect IE 11 masking as other browsers. else if (typeof doc.documentMode == 'number' && /^(?:Chrome|Firefox)\b/.test(name)) { description.push('masking as ' + name + ' ' + version); name = 'IE'; version = '11.0'; layout = ['Trident']; os = 'Windows'; } os = os && format(os); } // Detect prerelease phases. if (version && (data = /(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) || /(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) || /\bMinefield\b/i.test(ua) && 'a')) { prerelease = /b/i.test(data) ? 'beta' : 'alpha'; version = version.replace(RegExp(data + '\\+?$'), '') + (prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || ''); } // Detect Firefox Mobile. if (name == 'Fennec' || name == 'Firefox' && /\b(?:Android|Firefox OS|KaiOS)\b/.test(os)) { name = 'Firefox Mobile'; } // Obscure Maxthon's unreliable version. else if (name == 'Maxthon' && version) { version = version.replace(/\.[\d.]+/, '.x'); } // Detect Xbox 360 and Xbox One. else if (/\bXbox\b/i.test(product)) { if (product == 'Xbox 360') { os = null; } if (product == 'Xbox 360' && /\bIEMobile\b/.test(ua)) { description.unshift('mobile mode'); } } // Add mobile postfix. else if ((/^(?:Chrome|IE|Opera)$/.test(name) || name && !product && !/Browser|Mobi/.test(name)) && (os == 'Windows CE' || /Mobi/i.test(ua))) { name += ' Mobile'; } // Detect IE platform preview. else if (name == 'IE' && useFeatures) { try { if (context.external === null) { description.unshift('platform preview'); } } catch (e) { description.unshift('embedded'); } } // Detect BlackBerry OS version. // http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp else if ((/\bBlackBerry\b/.test(product) || /\bBB10\b/.test(ua)) && (data = (RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] || version)) { data = [data, /BB10/.test(ua)]; os = (data[1] ? (product = null, manufacturer = 'BlackBerry') : 'Device Software') + ' ' + data[0]; version = null; } // Detect Opera identifying/masking itself as another browser. // http://www.opera.com/support/kb/view/843/ else if (this != forOwn && product != 'Wii' && (useFeatures && opera || /Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua) || name == 'Firefox' && /\bOS X (?:\d+\.){2,}/.test(os) || name == 'IE' && (os && !/^Win/.test(os) && version > 5.5 || /\bWindows XP\b/.test(os) && version > 8 || version == 8 && !/\bTrident\b/.test(ua))) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) { // When "identifying", the UA contains both Opera and the other browser's name. data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : ''); if (reOpera.test(name)) { if (/\bIE\b/.test(data) && os == 'Mac OS') { os = null; } data = 'identify' + data; } // When "masking", the UA contains only the other browser's name. else { data = 'mask' + data; if (operaClass) { name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2')); } else { name = 'Opera'; } if (/\bIE\b/.test(data)) { os = null; } if (!useFeatures) { version = null; } } layout = ['Presto']; description.push(data); } // Detect WebKit Nightly and approximate Chrome/Safari versions. if (data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1]) { // Correct build number for numeric comparison. // (e.g. "532.5" becomes "532.05") data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data]; // Nightly builds are postfixed with a "+". if (name == 'Safari' && data[1].slice(-1) == '+') { name = 'WebKit Nightly'; prerelease = 'alpha'; version = data[1].slice(0, -1); } // Clear incorrect browser versions. else if (version == data[1] || version == (data[2] = (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1])) { version = null; } // Use the full Chrome version when available. data[1] = (/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(ua) || 0)[1]; // Detect Blink layout engine. if (data[0] == 537.36 && data[2] == 537.36 && parseFloat(data[1]) >= 28 && layout == 'WebKit') { layout = ['Blink']; } // Detect JavaScriptCore. // http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi if (!useFeatures || !likeChrome && !data[1]) { layout && (layout[1] = 'like Safari'); data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : data < 537 ? 6 : data < 538 ? 7 : data < 601 ? 8 : data < 602 ? 9 : data < 604 ? 10 : data < 606 ? 11 : data < 608 ? 12 : '12'); } else { layout && (layout[1] = 'like Chrome'); data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : data < 537.11 ? '21+' : data < 537.13 ? 23 : data < 537.18 ? 24 : data < 537.24 ? 25 : data < 537.36 ? 26 : layout != 'Blink' ? '27' : '28'); } // Add the postfix of ".x" or "+" for approximate versions. layout && (layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+')); // Obscure version for some Safari 1-2 releases. if (name == 'Safari' && (!version || parseInt(version) > 45)) { version = data; } else if (name == 'Chrome' && /\bHeadlessChrome/i.test(ua)) { description.unshift('headless'); } } // Detect Opera desktop modes. if (name == 'Opera' && (data = /\bzbov|zvav$/.exec(os))) { name += ' '; description.unshift('desktop mode'); if (data == 'zvav') { name += 'Mini'; version = null; } else { name += 'Mobile'; } os = os.replace(RegExp(' *' + data + '$'), ''); } // Detect Chrome desktop mode. else if (name == 'Safari' && /\bChrome\b/.exec(layout && layout[1])) { description.unshift('desktop mode'); name = 'Chrome Mobile'; version = null; if (/\bOS X\b/.test(os)) { manufacturer = 'Apple'; os = 'iOS 4.3+'; } else { os = null; } } // Newer versions of SRWare Iron uses the Chrome tag to indicate its version number. else if (/\bSRWare Iron\b/.test(name) && !version) { version = getVersion('Chrome'); } // Strip incorrect OS versions. if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 && ua.indexOf('/' + data + '-') > -1) { os = trim(os.replace(data, '')); } // Ensure OS does not include the browser name. if (os && os.indexOf(name) != -1 && !RegExp(name + ' OS').test(os)) { os = os.replace(RegExp(' *' + qualify(name) + ' *'), ''); } // Add layout engine. if (layout && !/\b(?:Avant|Nook)\b/.test(name) && (/Browser|Lunascape|Maxthon/.test(name) || name != 'Safari' && /^iOS/.test(os) && /\bSafari\b/.test(layout[1]) || /^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(name) && layout[1])) { // Don't add layout details to description if they are falsey. (data = layout[layout.length - 1]) && description.push(data); } // Combine contextual information. if (description.length) { description = ['(' + description.join('; ') + ')']; } // Append manufacturer to description. if (manufacturer && product && product.indexOf(manufacturer) < 0) { description.push('on ' + manufacturer); } // Append product to description. if (product) { description.push((/^on /.test(description[description.length - 1]) ? '' : 'on ') + product); } // Parse the OS into an object. if (os) { data = / ([\d.+]+)$/.exec(os); isSpecialCasedOS = data && os.charAt(os.length - data[0].length - 1) == '/'; os = { 'architecture': 32, 'family': data && !isSpecialCasedOS ? os.replace(data[0], '') : os, 'version': data ? data[1] : null, 'toString': function toString() { var version = this.version; return this.family + (version && !isSpecialCasedOS ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : ''); } }; } // Add browser/OS architecture. if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) { if (os) { os.architecture = 64; os.family = os.family.replace(RegExp(' *' + data), ''); } if (name && (/\bWOW64\b/i.test(ua) || useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform) && !/\bWin64; x64\b/i.test(ua))) { description.unshift('32-bit'); } } // Chrome 39 and above on OS X is always 64-bit. else if (os && /^OS X/.test(os.family) && name == 'Chrome' && parseFloat(version) >= 39) { os.architecture = 64; } ua || (ua = null); /*------------------------------------------------------------------------*/ /** * The platform object. * * @name platform * @type Object */ var platform = {}; /** * The platform description. * * @memberOf platform * @type string|null */ platform.description = ua; /** * The name of the browser's layout engine. * * The list of common layout engines include: * "Blink", "EdgeHTML", "Gecko", "Trident" and "WebKit" * * @memberOf platform * @type string|null */ platform.layout = layout && layout[0]; /** * The name of the product's manufacturer. * * The list of manufacturers include: * "Apple", "Archos", "Amazon", "Asus", "Barnes & Noble", "BlackBerry", * "Google", "HP", "HTC", "LG", "Microsoft", "Motorola", "Nintendo", * "Nokia", "Samsung" and "Sony" * * @memberOf platform * @type string|null */ platform.manufacturer = manufacturer; /** * The name of the browser/environment. * * The list of common browser names include: * "Chrome", "Electron", "Firefox", "Firefox for iOS", "IE", * "Microsoft Edge", "PhantomJS", "Safari", "SeaMonkey", "Silk", * "Opera Mini" and "Opera" * * Mobile versions of some browsers have "Mobile" appended to their name: * eg. "Chrome Mobile", "Firefox Mobile", "IE Mobile" and "Opera Mobile" * * @memberOf platform * @type string|null */ platform.name = name; /** * The alpha/beta release indicator. * * @memberOf platform * @type string|null */ platform.prerelease = prerelease; /** * The name of the product hosting the browser. * * The list of common products include: * * "BlackBerry", "Galaxy S4", "Lumia", "iPad", "iPod", "iPhone", "Kindle", * "Kindle Fire", "Nexus", "Nook", "PlayBook", "TouchPad" and "Transformer" * * @memberOf platform * @type string|null */ platform.product = product; /** * The browser's user agent string. * * @memberOf platform * @type string|null */ platform.ua = ua; /** * The browser/environment version. * * @memberOf platform * @type string|null */ platform.version = name && version; /** * The name of the operating system. * * @memberOf platform * @type Object */ platform.os = os || { /** * The CPU architecture the OS is built for. * * @memberOf platform.os * @type number|null */ 'architecture': null, /** * The family of the OS. * * Common values include: * "Windows", "Windows Server 2008 R2 / 7", "Windows Server 2008 / Vista", * "Windows XP", "OS X", "Linux", "Ubuntu", "Debian", "Fedora", "Red Hat", * "SuSE", "Android", "iOS" and "Windows Phone" * * @memberOf platform.os * @type string|null */ 'family': null, /** * The version of the OS. * * @memberOf platform.os * @type string|null */ 'version': null, /** * Returns the OS string. * * @memberOf platform.os * @returns {string} The OS string. */ 'toString': function toString() { return 'null'; } }; platform.parse = parse; platform.toString = toStringPlatform; if (platform.version) { description.unshift(version); } if (platform.name) { description.unshift(name); } if (os && name && !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product))) { description.push(product ? '(' + os + ')' : 'on ' + os); } if (description.length) { platform.description = description.join(' '); } return platform; } /*--------------------------------------------------------------------------*/ // Export platform. var platform = parse(); // Some AMD build optimizers, like r.js, check for condition patterns like the following: if (freeExports && freeModule) { // Export for CommonJS support. forOwn(platform, function (value, key) { freeExports[key] = value; }); } else { // Export to the global object. root.platform = platform; } }).call(commonjsGlobal); })(platform$1, platform$1.exports); var fixRegExpWellKnownSymbolLogic$1 = fixRegexpWellKnownSymbolLogic; var anObject$2 = anObject$k; var toLength$4 = toLength$o; var toString$4 = toString$d; var requireObjectCoercible$3 = requireObjectCoercible$a; var advanceStringIndex = advanceStringIndex$3; var regExpExec$1 = regexpExecAbstract; // @@match logic fixRegExpWellKnownSymbolLogic$1('match', function (MATCH, nativeMatch, maybeCallNative) { return [ // `String.prototype.match` method // https://tc39.es/ecma262/#sec-string.prototype.match function match(regexp) { var O = requireObjectCoercible$3(this); var matcher = regexp == undefined ? undefined : regexp[MATCH]; return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](toString$4(O)); }, // `RegExp.prototype[@@match]` method // https://tc39.es/ecma262/#sec-regexp.prototype-@@match function (string) { var rx = anObject$2(this); var S = toString$4(string); var res = maybeCallNative(nativeMatch, rx, S); if (res.done) return res.value; if (!rx.global) return regExpExec$1(rx, S); var fullUnicode = rx.unicode; rx.lastIndex = 0; var A = []; var n = 0; var result; while ((result = regExpExec$1(rx, S)) !== null) { var matchStr = toString$4(result[0]); A[n] = matchStr; if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength$4(rx.lastIndex), fullUnicode); n++; } return n === 0 ? null : A; } ]; }); // `SameValue` abstract operation // https://tc39.es/ecma262/#sec-samevalue // eslint-disable-next-line es/no-object-is -- safe var sameValue$1 = Object.is || function is(x, y) { // eslint-disable-next-line no-self-compare -- NaN check return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; var fixRegExpWellKnownSymbolLogic = fixRegexpWellKnownSymbolLogic; var anObject$1 = anObject$k; var requireObjectCoercible$2 = requireObjectCoercible$a; var sameValue = sameValue$1; var toString$3 = toString$d; var regExpExec = regexpExecAbstract; // @@search logic fixRegExpWellKnownSymbolLogic('search', function (SEARCH, nativeSearch, maybeCallNative) { return [ // `String.prototype.search` method // https://tc39.es/ecma262/#sec-string.prototype.search function search(regexp) { var O = requireObjectCoercible$2(this); var searcher = regexp == undefined ? undefined : regexp[SEARCH]; return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](toString$3(O)); }, // `RegExp.prototype[@@search]` method // https://tc39.es/ecma262/#sec-regexp.prototype-@@search function (string) { var rx = anObject$1(this); var S = toString$3(string); var res = maybeCallNative(nativeSearch, rx, S); if (res.done) return res.value; var previousLastIndex = rx.lastIndex; if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0; var result = regExpExec(rx, S); if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex; return result === null ? -1 : result.index; } ]; }); var $$9 = _export; var toAbsoluteIndex = toAbsoluteIndex$6; var toInteger$1 = toInteger$a; var toLength$3 = toLength$o; var toObject$2 = toObject$g; var arraySpeciesCreate = arraySpeciesCreate$3; var createProperty = createProperty$5; var arrayMethodHasSpeciesSupport = arrayMethodHasSpeciesSupport$5; var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('splice'); var max = Math.max; var min$1 = Math.min; var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; // `Array.prototype.splice` method // https://tc39.es/ecma262/#sec-array.prototype.splice // with adding support of @@species $$9({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, { splice: function splice(start, deleteCount /* , ...items */) { var O = toObject$2(this); var len = toLength$3(O.length); var actualStart = toAbsoluteIndex(start, len); var argumentsLength = arguments.length; var insertCount, actualDeleteCount, A, k, from, to; if (argumentsLength === 0) { insertCount = actualDeleteCount = 0; } else if (argumentsLength === 1) { insertCount = 0; actualDeleteCount = len - actualStart; } else { insertCount = argumentsLength - 2; actualDeleteCount = min$1(max(toInteger$1(deleteCount), 0), len - actualStart); } if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) { throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED); } A = arraySpeciesCreate(O, actualDeleteCount); for (k = 0; k < actualDeleteCount; k++) { from = actualStart + k; if (from in O) createProperty(A, k, O[from]); } A.length = actualDeleteCount; if (insertCount < actualDeleteCount) { for (k = actualStart; k < len - actualDeleteCount; k++) { from = k + actualDeleteCount; to = k + insertCount; if (from in O) O[to] = O[from]; else delete O[to]; } for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1]; } else if (insertCount > actualDeleteCount) { for (k = len - actualDeleteCount; k > actualStart; k--) { from = k + actualDeleteCount - 1; to = k + insertCount - 1; if (from in O) O[to] = O[from]; else delete O[to]; } } for (k = 0; k < insertCount; k++) { O[k + actualStart] = arguments[k + 2]; } O.length = len - actualDeleteCount + insertCount; return A; } }); (function (exports) { var global = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; Object.defineProperty(exports, '__esModule', { value: true }); var _asyncToGenerator = asyncToGenerator.exports; var _createClass = createClass.exports; var _assertThisInitialized = assertThisInitialized.exports; var _get = get$1.exports; var _inherits = inherits.exports; var _possibleConstructorReturn = possibleConstructorReturn.exports; var _getPrototypeOf = getPrototypeOf$2.exports; var _classCallCheck = classCallCheck.exports; var _defineProperty = defineProperty$5.exports; var _regeneratorRuntime = require$$8; var _typeof = _typeof$2.exports; var declarativeTypeValidator = browser$7; var loglevelLog = loglevel.exports; var StateMachine = stateMachine.exports; var uuid = uuid_1; var _wrapNativeSuper = wrapNativeSuper.exports; var operationRetrier = browser$5; var platform = platform$1.exports; function _interopDefaultLegacy(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function get() { return e[k]; } }); } }); } n['default'] = e; return Object.freeze(n); } var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator); var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass); var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized); var _get__default = /*#__PURE__*/_interopDefaultLegacy(_get); var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits); var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn); var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf); var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck); var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty); var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime); var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof); var loglevelLog__namespace = /*#__PURE__*/_interopNamespace(loglevelLog); var StateMachine__namespace = /*#__PURE__*/_interopNamespace(StateMachine); var _wrapNativeSuper__default = /*#__PURE__*/_interopDefaultLegacy(_wrapNativeSuper); var platform__namespace = /*#__PURE__*/_interopNamespace(platform); function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default['default'](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; } return c > 3 && r && Object.defineProperty(target, key, r), r; } function __metadata(metadataKey, metadataValue) { if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default['default'](Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } var domain; // This constructor is used to store event handlers. Instantiating this is // faster than explicitly calling `Object.create(null)` to get a "clean" empty // object (tested with v8 v4.9). function EventHandlers() {} EventHandlers.prototype = Object.create(null); function EventEmitter() { EventEmitter.init.call(this); } // nodejs oddity // require('events') === require('events').EventEmitter EventEmitter.EventEmitter = EventEmitter; EventEmitter.usingDomains = false; EventEmitter.prototype.domain = undefined; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; EventEmitter.init = function () { this.domain = null; if (EventEmitter.usingDomains) { // if there is an active domain, then attach to it. if (domain.active) ; } if (!this._events || this._events === Object.getPrototypeOf(this)._events) { this._events = new EventHandlers(); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self); } } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1); } } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2); } } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2, arg3); } } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].apply(self, args); } } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events, domain; var doError = type === 'error'; events = this._events; if (events) doError = doError && events.error == null;else if (!doError) return false; domain = this.domain; // If there is no 'error' event listener then throw. if (doError) { er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); er.domainEmitter = this; er.domain = domain; er.domainThrown = false; domain.emit('error', er); } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) { args[i - 1] = arguments[i]; } emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = new EventHandlers(); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; emitWarning(w); } } } return target; } function emitWarning(e) { typeof console.warn === 'function' ? console.warn(e) : console.log(e); } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function _onceWrap(target, type, listener) { var fired = false; function g() { target.removeListener(type, g); if (!fired) { fired = true; listener.apply(target, arguments); } } g.listener = listener; return g; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener && list.listener === listener) { if (--this._eventsCount === 0) this._events = new EventHandlers();else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (list.length === 1) { list[0] = undefined; if (--this._eventsCount === 0) { this._events = new EventHandlers(); return this; } else { delete events[type]; } } else { spliceOne(list, position); } if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; // Alias for removeListener added in NodeJS 10.0 // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener EventEmitter.prototype.off = function (type, listener) { return this.removeListener(type, listener); }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = new EventHandlers(); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = new EventHandlers();else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); for (var i = 0, key; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = new EventHandlers(); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order do { this.removeListener(type, listeners[listeners.length - 1]); } while (listeners[0]); } return this; }; EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = [];else { evlistener = events[type]; if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener); } return ret; }; EventEmitter.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; } list.pop(); } function arrayClone(arr, i) { var copy = new Array(i); while (i--) { copy[i] = arr[i]; } return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } var log = loglevelLog__namespace.getLogger("twilsock"); // twilsock is used by Flex SDK. Please DO NOT change function prepareLine(prefix, args) { return ["".concat(new Date().toISOString(), " Twilsock ").concat(prefix, ":")].concat(Array.from(args)); } var Logger = /*#__PURE__*/function () { function Logger(prefix) { _classCallCheck__default['default'](this, Logger); _defineProperty__default['default'](this, "prefix", ""); this.prefix = prefix !== null && prefix !== undefined && prefix.length > 0 ? " " + prefix + ":" : ""; } _createClass__default['default'](Logger, [{ key: "setLevel", value: function setLevel(level) { log.setLevel(level); } }, { key: "trace", value: function trace() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log.trace.apply(null, prepareLine("T", args)); } }, { key: "debug", value: function debug() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } log.debug.apply(null, prepareLine("D", args)); } }, { key: "info", value: function info() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } log.info.apply(null, prepareLine("I", args)); } }, { key: "warn", value: function warn() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } log.warn.apply(null, prepareLine("W", args)); } }, { key: "error", value: function error() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } log.error.apply(null, prepareLine("E", args)); } }], [{ key: "setLevel", value: function setLevel(level) { log.setLevel(level); } }, { key: "trace", value: function trace() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } log.trace.apply(null, prepareLine("T", args)); } }, { key: "debug", value: function debug() { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } log.debug.apply(null, prepareLine("D", args)); } }, { key: "info", value: function info() { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } log.info.apply(null, prepareLine("I", args)); } }, { key: "warn", value: function warn() { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { args[_key9] = arguments[_key9]; } log.warn.apply(null, prepareLine("W", args)); } }, { key: "error", value: function error() { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { args[_key10] = arguments[_key10]; } log.error.apply(null, prepareLine("E", args)); } }]); return Logger; }(); var logInstance = new Logger(""); var version = "0.12.2"; /** * Settings container for the Twilsock client library */ var Configuration = /*#__PURE__*/function () { /** * @param {String} token - authentication token * @param {Object} options - options to override defaults */ function Configuration(token, activeGrant, options) { _classCallCheck__default['default'](this, Configuration); _defineProperty__default['default'](this, "confirmedCapabilities", new Set()); this.activeGrant = activeGrant; this._token = token; var region = options.region || "us1"; var defaultTwilsockUrl = "wss://tsock.".concat(region, ".twilio.com/v3/wsconnect"); var twilsockOptions = options.twilsock || options.Twilsock || {}; this.url = twilsockOptions.uri || defaultTwilsockUrl; this._continuationToken = options.continuationToken ? options.continuationToken : null; this.logLevel = options.logLevel ? options.logLevel : "error"; this.retryPolicy = options.retryPolicy ? options.retryPolicy : { min: 1 * 1000, max: 2 * 60 * 1000, randomness: 0.2 }; this.clientMetadata = options.clientMetadata ? options.clientMetadata : {}; this.clientMetadata.ver = version; this.initRegistrations = options.initRegistrations ? options.initRegistrations : null; this.tweaks = options.tweaks ? options.tweaks : null; } _createClass__default['default'](Configuration, [{ key: "token", get: function get() { return this._token; } }, { key: "continuationToken", get: function get() { return this._continuationToken; } }, { key: "updateToken", value: function updateToken(token) { this._token = token; } }, { key: "updateContinuationToken", value: function updateContinuationToken(continuationToken) { this._continuationToken = continuationToken; } }]); return Configuration; }(); var AbstractMessage = function AbstractMessage(id) { _classCallCheck__default['default'](this, AbstractMessage); this.id = id || "TM".concat(uuid.v4()); }; function _createSuper$f(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$f(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$f() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Init = /*#__PURE__*/function (_AbstractMessage) { _inherits__default['default'](Init, _AbstractMessage); var _super = _createSuper$f(Init); function Init(token, continuationToken, metadata, registrations, tweaks) { var _this; _classCallCheck__default['default'](this, Init); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "method", "init"); _this.token = token; _this.continuation_token = continuationToken; _this.metadata = metadata; _this.registrations = registrations; _this.tweaks = tweaks; _this.capabilities = ["client_update", "offline_storage", "telemetry.v1"]; return _this; } return Init; }(AbstractMessage); function _createSuper$e(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$e(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$e() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var InitReply = /*#__PURE__*/function (_AbstractMessage) { _inherits__default['default'](InitReply, _AbstractMessage); var _super = _createSuper$e(InitReply); function InitReply(id, continuationToken, confirmedCapabilities, continuationTokenStatus, offlineStorage, initRegistrations, debugInfo) { var _this; _classCallCheck__default['default'](this, InitReply); _this = _super.call(this, id); _this.continuationToken = continuationToken; _this.continuationTokenStatus = continuationTokenStatus; _this.offlineStorage = offlineStorage; _this.initRegistrations = initRegistrations; _this.debugInfo = debugInfo; _this.confirmedCapabilities = confirmedCapabilities; return _this; } return InitReply; }(AbstractMessage); function _createSuper$d(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$d(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$d() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Update = /*#__PURE__*/function (_AbstractMessage) { _inherits__default['default'](Update, _AbstractMessage); var _super = _createSuper$d(Update); function Update(token) { var _this; _classCallCheck__default['default'](this, Update); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "method", "update"); _this.token = token; return _this; } return Update; }(AbstractMessage); function _createSuper$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Message = /*#__PURE__*/function (_AbstractMessage) { _inherits__default['default'](Message, _AbstractMessage); var _super = _createSuper$c(Message); function Message(grant, contentType, request) { var _this; _classCallCheck__default['default'](this, Message); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "method", "message"); _this.active_grant = grant; _this.payload_type = contentType; _this.http_request = request; return _this; } return Message; }(AbstractMessage); function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Reply = /*#__PURE__*/function (_AbstractMessage) { _inherits__default['default'](Reply, _AbstractMessage); var _super = _createSuper$b(Reply); function Reply(id) { var _this; _classCallCheck__default['default'](this, Reply); _this = _super.call(this, id); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "method", "reply"); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "payload_type", "application/json"); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "status", { code: 200, status: "OK" }); return _this; } return Reply; }(AbstractMessage); function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Close = /*#__PURE__*/function (_AbstractMessage) { _inherits__default['default'](Close, _AbstractMessage); var _super = _createSuper$a(Close); function Close() { var _this; _classCallCheck__default['default'](this, Close); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "method", "close"); return _this; } return Close; }(AbstractMessage); function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TelemetryEvent = function TelemetryEvent(start, // relative to event send time end, // relative to event send time title, details, id, // optional, default will be random assigned by backend type) { _classCallCheck__default['default'](this, TelemetryEvent); this.start = start; this.end = end; this.title = title; this.details = details; this.id = id; this.type = type; } // optional, default will be "SDK" assigned by backend ; var Telemetry = /*#__PURE__*/function (_AbstractMessage) { _inherits__default['default'](Telemetry, _AbstractMessage); var _super = _createSuper$9(Telemetry); function Telemetry(events) { var _this; _classCallCheck__default['default'](this, Telemetry); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "method", "telemetry.v1"); _this.events = events; return _this; } return Telemetry; }(AbstractMessage); function byteLength(s) { var escstr = encodeURIComponent(s); var binstr = escstr.replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(Number("0x" + p1)); }); return binstr.length; } function stringToUint8Array(s) { var escstr = encodeURIComponent(s); var binstr = escstr.replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(Number("0x" + p1)); }); var ua = new Uint8Array(binstr.length); Array.prototype.forEach.call(binstr, function (ch, i) { ua[i] = ch.charCodeAt(0); }); return ua; } function uint8ArrayToString(ua) { var binstr = Array.prototype.map.call(ua, function (ch) { return String.fromCharCode(ch); }).join(""); var escstr = binstr.replace(/(.)/g, function (m, p) { var code = p.charCodeAt(0).toString(16).toUpperCase(); if (code.length < 2) { code = "0" + code; } return "%" + code; }); return decodeURIComponent(escstr); } function getJsonObject(array) { return JSON.parse(uint8ArrayToString(array)); } function getMagic(buffer) { var strMagic = ""; var idx = 0; for (; idx < buffer.length; ++idx) { var chr = String.fromCharCode(buffer[idx]); strMagic += chr; if (chr === "\r") { idx += 2; break; } } var magics = strMagic.split(" "); return { size: idx, protocol: magics[0], version: magics[1], headerSize: Number(magics[2]) }; } var Parser = /*#__PURE__*/function () { function Parser() { _classCallCheck__default['default'](this, Parser); } _createClass__default['default'](Parser, null, [{ key: "parse", value: function parse(message) { var fieldMargin = 2; var dataView = new Uint8Array(message); var magic = getMagic(dataView); if (magic.protocol !== "TWILSOCK" || magic.version !== "V3.0") { logInstance.error("unsupported protocol: ".concat(magic.protocol, " ver ").concat(magic.version)); //throw new Error('Unsupported protocol'); //this.fsm.unsupportedProtocol(); return null; } var header; try { header = getJsonObject(dataView.subarray(magic.size, magic.size + magic.headerSize)); } catch (e) { logInstance.error("failed to parse message header", e, message); //throw new Error('Failed to parse message'); //this.fsm.protocolError(); return null; } logInstance.debug("message received: ", header.method); logInstance.trace("message received: ", header); var payload; if (header.payload_size > 0) { var payloadOffset = fieldMargin + magic.size + magic.headerSize; var payloadSize = header.payload_size; if (!header.hasOwnProperty("payload_type") || header.payload_type.indexOf("application/json") === 0) { try { payload = getJsonObject(dataView.subarray(payloadOffset, payloadOffset + payloadSize)); } catch (e) { logInstance.error("failed to parse message body", e, message); //this.fsm.protocolError(); return null; } } else if (header.payload_type.indexOf("text/plain") === 0) { payload = uint8ArrayToString(dataView.subarray(payloadOffset, payloadOffset + payloadSize)); } } return { method: header.method, header: header, payload: payload }; } }, { key: "createPacket", value: function createPacket(header) { var payloadString = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; header.payload_size = byteLength(payloadString); // eslint-disable-line camelcase var headerString = JSON.stringify(header); var magicString = "TWILSOCK V3.0 " + byteLength(headerString); logInstance.debug("send request:", magicString + headerString + payloadString); var message = stringToUint8Array(magicString + "\r\n" + headerString + "\r\n" + payloadString); return message.buffer; } }]); return Parser; }(); function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TwilsockError = /*#__PURE__*/function (_Error) { _inherits__default['default'](TwilsockError, _Error); var _super = _createSuper$8(TwilsockError); function TwilsockError(description) { _classCallCheck__default['default'](this, TwilsockError); return _super.call(this, description); } return TwilsockError; }( /*#__PURE__*/_wrapNativeSuper__default['default'](Error)); function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TwilsockReplyError = /*#__PURE__*/function (_TwilsockError) { _inherits__default['default'](TwilsockReplyError, _TwilsockError); var _super = _createSuper$7(TwilsockReplyError); function TwilsockReplyError(description, reply) { var _this; _classCallCheck__default['default'](this, TwilsockReplyError); _this = _super.call(this, description); _this.reply = reply; return _this; } return TwilsockReplyError; }(TwilsockError); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var BackoffRetrier = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](BackoffRetrier, _EventEmitter); var _super = _createSuper$6(BackoffRetrier); function BackoffRetrier(options) { var _this; _classCallCheck__default['default'](this, BackoffRetrier); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "newBackoff", null); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "usedBackoff", null); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "retrier", null); _this.options = options ? _objectSpread({}, options) : {}; return _this; } /** * Should be called once per attempt series to start retrier. */ _createClass__default['default'](BackoffRetrier, [{ key: "inProgress", get: function get() { return !!this.retrier; } }, { key: "start", value: function start() { if (this.inProgress) { throw new Error("Already waiting for next attempt, call finishAttempt(success : boolean) to finish it"); } this.createRetrier(); } /** * Should be called to stop retrier entirely. */ }, { key: "stop", value: function stop() { this.cleanRetrier(); this.newBackoff = null; this.usedBackoff = null; } /** * Modifies backoff for next attempt. * Expected behavior: * - If there was no backoff passed previously reschedulling next attempt to given backoff * - If previous backoff was longer then ignoring this one. * - If previous backoff was shorter then reschedulling with this one. * With or without backoff retrier will keep growing normally. * @param delay delay of next attempts in ms. */ }, { key: "modifyBackoff", value: function modifyBackoff(delay) { this.newBackoff = delay; } /** * Mark last emmited attempt as failed, initiating either next of fail if limits were hit. */ }, { key: "attemptFailed", value: function attemptFailed() { if (!this.inProgress) { throw new Error("No attempt is in progress"); } if (this.newBackoff) { var shouldUseNewBackoff = !this.usedBackoff || this.usedBackoff < this.newBackoff; if (shouldUseNewBackoff) { this.createRetrier(); } else { var _this$retrier; (_this$retrier = this.retrier) === null || _this$retrier === void 0 ? void 0 : _this$retrier.failed(new Error()); } } else { var _this$retrier2; (_this$retrier2 = this.retrier) === null || _this$retrier2 === void 0 ? void 0 : _this$retrier2.failed(new Error()); } } }, { key: "cancel", value: function cancel() { var _this$retrier3; (_this$retrier3 = this.retrier) === null || _this$retrier3 === void 0 ? void 0 : _this$retrier3.cancel(); } }, { key: "cleanRetrier", value: function cleanRetrier() { var _this$retrier4, _this$retrier5; (_this$retrier4 = this.retrier) === null || _this$retrier4 === void 0 ? void 0 : _this$retrier4.removeAllListeners(); (_this$retrier5 = this.retrier) === null || _this$retrier5 === void 0 ? void 0 : _this$retrier5.cancel(); this.retrier = null; } }, { key: "getRetryPolicy", value: function getRetryPolicy() { var clone = _objectSpread({}, this.options); if (this.newBackoff) { clone.min = this.newBackoff; clone.max = this.options.max && this.options.max > this.newBackoff ? this.options.max : this.newBackoff; } // As we're always skipping first attempt we should add one extra if limit is present clone.maxAttemptsCount = this.options.maxAttemptsCount ? this.options.maxAttemptsCount + 1 : undefined; return clone; } }, { key: "createRetrier", value: function createRetrier() { var _this2 = this; this.cleanRetrier(); var retryPolicy = this.getRetryPolicy(); this.retrier = new operationRetrier.Retrier(retryPolicy); this.retrier.once("attempt", function () { var _this2$retrier, _this2$retrier2; (_this2$retrier = _this2.retrier) === null || _this2$retrier === void 0 ? void 0 : _this2$retrier.on("attempt", function () { return _this2.emit("attempt"); }); (_this2$retrier2 = _this2.retrier) === null || _this2$retrier2 === void 0 ? void 0 : _this2$retrier2.failed(new Error("Skipping first attempt")); }); this.retrier.on("failed", function (err) { return _this2.emit("failed", err); }); this.usedBackoff = this.newBackoff; this.newBackoff = null; this.retrier.start(); // .catch(err => {}); } }]); return BackoffRetrier; }(EventEmitter); function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var DISCONNECTING_TIMEOUT = 3000; // Wraps asynchronous rescheduling // Just makes it simpler to find these hacks over the code // Currently there's exactly one instance of this in closeSocket() function trampoline(f) { setTimeout(f, 0); } /** * Twilsock channel level protocol implementation */ var TwilsockChannel = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](TwilsockChannel, _EventEmitter); var _super = _createSuper$5(TwilsockChannel); function TwilsockChannel(websocket, transport, config) { var _this; _classCallCheck__default['default'](this, TwilsockChannel); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "disconnectingTimer", null); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "disconnectedPromiseResolve", null); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "terminalStates", ["disconnected", "rejected"]); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "tokenExpiredSasCode", 20104); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "terminationReason", "Connection is not initialized"); _this.websocket = websocket; _this.websocket.on("connected", function () { return _this.fsm.socketConnected(); }); _this.websocket.on("disconnected", function () { return _this.fsm.socketClosed(); }); _this.websocket.on("message", function (message) { return _this.onIncomingMessage(message); }); _this.websocket.on("socketError", function (e) { return _this.emit("connectionError", { terminal: false, message: "Socket error: ".concat(e.message), httpStatusCode: null, errorCode: null }); }); _this.transport = transport; _this.config = config; _this.retrier = new BackoffRetrier(config.retryPolicy); _this.retrier.on("attempt", function () { return _this.retry(); }); _this.retrier.on("failed", function (err) { logInstance.warn("Retrying failed: ".concat(err.message)); _this.disconnect(); }); if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") { window.addEventListener("online", function () { logInstance.debug("Browser reported connectivity state: online"); _this.resetBackoff(); _this.fsm.systemOnline(); }); window.addEventListener("offline", function () { logInstance.debug("Browser reported connectivity state: offline"); _this.websocket.close(); _this.fsm.socketClosed(); }); } // We have to use a factory function in here because using the default // StateMachine constructor would cause an error for the consumers of the // rollup bundles. This is a quirk unique to the javascript-state-machine // library. var TwilsockStateMachine = StateMachine__namespace.factory({ init: "disconnected", transitions: [{ name: "userConnect", from: ["disconnected", "rejected"], to: "connecting" }, { name: "userConnect", from: ["connecting", "connected"] }, { name: "userDisconnect", from: ["connecting", "initialising", "connected", "updating", "retrying", "rejected", "waitSocketClosed", "waitOffloadSocketClosed"], to: "disconnecting" }, { name: "userRetry", from: ["retrying"], to: "connecting" }, { name: "socketConnected", from: ["connecting"], to: "initialising" }, { name: "socketClosed", from: ["connecting", "initialising", "connected", "updating", "error", "waitOffloadSocketClosed"], to: "retrying" }, { name: "socketClosed", from: ["disconnecting"], to: "disconnected" }, { name: "socketClosed", from: ["waitSocketClosed"], to: "disconnected" }, { name: "socketClosed", from: ["rejected"], to: "rejected" }, { name: "initSuccess", from: ["initialising"], to: "connected" }, { name: "initError", from: ["initialising"], to: "error" }, { name: "tokenRejected", from: ["initialising", "updating"], to: "rejected" }, { name: "protocolError", from: ["initialising", "connected", "updating"], to: "error" }, { name: "receiveClose", from: ["initialising", "connected", "updating"], to: "waitSocketClosed" }, { name: "receiveOffload", from: ["initialising", "connected", "updating"], to: "waitOffloadSocketClosed" }, { name: "unsupportedProtocol", from: ["initialising", "connected", "updating"], to: "unsupported" }, { name: "receiveFatalClose", from: ["initialising", "connected", "updating"], to: "unsupported" }, { name: "userUpdateToken", from: ["disconnected", "rejected", "connecting", "retrying"], to: "connecting" }, { name: "userUpdateToken", from: ["connected"], to: "updating" }, { name: "updateSuccess", from: ["updating"], to: "connected" }, { name: "updateError", from: ["updating"], to: "error" }, { name: "userSend", from: ["connected"], to: "connected" }, { name: "systemOnline", from: ["retrying"], to: "connecting" }], methods: { onConnecting: function onConnecting() { _this.setupSocket(); _this.emit("connecting"); }, onEnterInitialising: function onEnterInitialising() { _this.sendInit(); }, onLeaveInitialising: function onLeaveInitialising() { _this.cancelInit(); }, onEnterUpdating: function onEnterUpdating() { _this.sendUpdate(); }, onLeaveUpdating: function onLeaveUpdating() { _this.cancelUpdate(); }, onEnterRetrying: function onEnterRetrying() { _this.initRetry(); _this.emit("connecting"); }, onEnterConnected: function onEnterConnected() { _this.resetBackoff(); _this.onConnected(); }, onUserUpdateToken: function onUserUpdateToken() { _this.resetBackoff(); }, onTokenRejected: function onTokenRejected() { _this.resetBackoff(); _this.closeSocket(true); _this.finalizeSocket(); }, onUserDisconnect: function onUserDisconnect() { _this.closeSocket(true); }, onEnterDisconnecting: function onEnterDisconnecting() { _this.startDisconnectTimer(); }, onLeaveDisconnecting: function onLeaveDisconnecting() { _this.cancelDisconnectTimer(); }, onEnterWaitSocketClosed: function onEnterWaitSocketClosed() { _this.startDisconnectTimer(); }, onLeaveWaitSocketClosed: function onLeaveWaitSocketClosed() { _this.cancelDisconnectTimer(); }, onEnterWaitOffloadSocketClosed: function onEnterWaitOffloadSocketClosed() { _this.startDisconnectTimer(); }, onLeaveWaitOffloadSocketClosed: function onLeaveWaitOffloadSocketClosed() { _this.cancelDisconnectTimer(); }, onDisconnected: function onDisconnected() { _this.resetBackoff(); _this.finalizeSocket(); }, onReceiveClose: function onReceiveClose() { _this.onCloseReceived(); }, onReceiveOffload: function onReceiveOffload(event, args) { logInstance.debug("onreceiveoffload: ", args); _this.modifyBackoff(args.body); _this.onCloseReceived(); }, onUnsupported: function onUnsupported() { _this.closeSocket(true); _this.finalizeSocket(); }, onError: function onError(lifecycle, graceful) { _this.closeSocket(graceful); _this.finalizeSocket(); }, onEnterState: function onEnterState(event) { if (event.from !== "none") { _this.changeState(event); } }, onInvalidTransition: function onInvalidTransition(transition, from, to) { logInstance.warn("FSM: unexpected transition", from, to); } } }); _this.fsm = new TwilsockStateMachine(); return _this; } _createClass__default['default'](TwilsockChannel, [{ key: "changeState", value: function changeState(event) { logInstance.debug("FSM: ".concat(event.transition, ": ").concat(event.from, " --> ").concat(event.to)); if (this.lastEmittedState !== this.state) { this.lastEmittedState = this.state; this.emit("stateChanged", this.state); } } }, { key: "resetBackoff", value: function resetBackoff() { logInstance.trace("resetBackoff"); this.retrier.stop(); } }, { key: "modifyBackoff", value: function modifyBackoff(body) { logInstance.trace("modifyBackoff", body); var backoffPolicy = body ? body.backoff_policy : null; if (backoffPolicy && typeof backoffPolicy.reconnect_min_ms === "number") { this.retrier.modifyBackoff(backoffPolicy.reconnect_min_ms); } } }, { key: "startDisconnectTimer", value: function startDisconnectTimer() { var _this2 = this; logInstance.trace("startDisconnectTimer"); if (this.disconnectingTimer) { clearTimeout(this.disconnectingTimer); this.disconnectingTimer = null; } this.disconnectingTimer = setTimeout(function () { logInstance.debug("disconnecting is timed out"); _this2.closeSocket(true); }, DISCONNECTING_TIMEOUT); } }, { key: "cancelDisconnectTimer", value: function cancelDisconnectTimer() { logInstance.trace("cancelDisconnectTimer"); if (this.disconnectingTimer) { clearTimeout(this.disconnectingTimer); this.disconnectingTimer = null; } } }, { key: "isConnected", get: function get() { return this.state === "connected" && this.websocket.isConnected; } }, { key: "state", get: function get() { switch (this.fsm.state) { case "connecting": case "initialising": case "retrying": case "error": return "connecting"; case "updating": case "connected": return "connected"; case "rejected": return "denied"; case "disconnecting": case "waitSocketClosed": case "waitOffloadSocketClosed": return "disconnecting"; case "disconnected": default: return "disconnected"; } } }, { key: "initRetry", value: function initRetry() { logInstance.debug("initRetry"); if (this.retrier.inProgress) { this.retrier.attemptFailed(); } else { this.retrier.start(); } } }, { key: "retry", value: function retry() { if (this.fsm.state != "connecting") { logInstance.trace("retry"); this.websocket.close(); this.fsm.userRetry(); } else { logInstance.trace("can\t retry as already connecting"); } } }, { key: "onConnected", value: function onConnected() { this.emit("connected"); } }, { key: "finalizeSocket", value: function finalizeSocket() { logInstance.trace("finalizeSocket"); this.websocket.close(); this.emit("disconnected"); if (this.disconnectedPromiseResolve) { this.disconnectedPromiseResolve(); this.disconnectedPromiseResolve = null; } } }, { key: "setupSocket", value: function setupSocket() { logInstance.trace("setupSocket:", this.config.token); this.emit("beforeConnect"); // This is used by client to record startup telemetry event this.websocket.connect(); } }, { key: "onIncomingMessage", value: function onIncomingMessage(message) { var parsedMessage = Parser.parse(message); if (!parsedMessage) { return; } var method = parsedMessage.method, header = parsedMessage.header, payload = parsedMessage.payload; if (method !== "reply") { this.confirmReceiving(header); } if (method === "notification") { this.emit("message", header.message_type, payload); } else if (header.method === "reply") { this.transport.processReply({ id: header.id, status: header.status, header: header, body: payload }); } else if (header.method === "client_update") { if (header.client_update_type === "token_about_to_expire") { this.emit("tokenAboutToExpire"); } } else if (header.method === "close") { if (header.status.code === 308) { logInstance.debug("Connection has been offloaded"); this.fsm.receiveOffload({ status: header.status.status, body: payload }); } else if (header.status.code === 406) { // Not acceptable message var _message = "Server closed connection because can't parse protocol: ".concat(JSON.stringify(header.status)); this.emitReplyConnectionError(_message, header, true); logInstance.error(_message); this.fsm.receiveFatalClose(); } else if (header.status.code === 417) { // Protocol error logInstance.error("Server closed connection because can't parse client reply: ".concat(JSON.stringify(header.status))); this.fsm.receiveFatalClose(header.status.status); } else if (header.status.code === 410) { // Expired token logInstance.warn("Server closed connection: ".concat(JSON.stringify(header.status))); this.fsm.receiveClose(header.status.status); this.emit("tokenExpired"); } else if (header.status.code === 401) { // Authentication fail logInstance.error("Server closed connection: ".concat(JSON.stringify(header.status))); this.fsm.receiveClose(header.status.status); } else { logInstance.warn("unexpected message: ", header.status); // Try to reconnect this.fsm.receiveOffload({ status: header.status.status, body: null }); } } } }, { key: "sendInit", value: function () { var _sendInit = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() { var reply, isTerminalError; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: logInstance.trace("sendInit"); _context.prev = 1; this.emit("beforeSendInit"); // This is used by client to record startup telemetry event _context.next = 5; return this.transport.sendInit(); case 5: reply = _context.sent; this.config.updateContinuationToken(reply.continuationToken); this.config.confirmedCapabilities = reply.confirmedCapabilities; this.fsm.initSuccess(reply); this.emit("initialized", reply); this.emit("tokenUpdated"); _context.next = 17; break; case 13: _context.prev = 13; _context.t0 = _context["catch"](1); if (_context.t0 instanceof TwilsockReplyError) { isTerminalError = false; logInstance.warn("Init rejected by server: ".concat(JSON.stringify(_context.t0.reply.status))); this.emit("sendInitFailed"); // This is used by client to record startup telemetry event // @todo emit telemetry from inside "if" below for more granularity... if (_context.t0.reply.status.code === 401 || _context.t0.reply.status.code === 403) { isTerminalError = true; this.fsm.tokenRejected(_context.t0.reply.status); if (_context.t0.reply.status.errorCode === this.tokenExpiredSasCode) { this.emit("tokenExpired"); } } else if (_context.t0.reply.status.code === 429) { this.modifyBackoff(_context.t0.reply.body); this.fsm.initError(true); } else if (_context.t0.reply.status.code === 500) { this.fsm.initError(false); } else { this.fsm.initError(true); } this.emitReplyConnectionError(_context.t0.message, _context.t0.reply, isTerminalError); } else { this.terminationReason = _context.t0.message; this.emit("connectionError", { terminal: true, message: "Unknown error during connection initialisation: ".concat(_context.t0.message, "\n").concat(JSON.stringify(_context.t0, null, 2)), httpStatusCode: null, errorCode: null }); this.fsm.initError(true); } this.emit("tokenUpdated", _context.t0); case 17: case "end": return _context.stop(); } } }, _callee, this, [[1, 13]]); })); function sendInit() { return _sendInit.apply(this, arguments); } return sendInit; }() }, { key: "sendUpdate", value: function () { var _sendUpdate = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2() { var message, reply, isTerminalError; return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: logInstance.trace("sendUpdate"); message = new Update(this.config.token); _context2.prev = 2; _context2.next = 5; return this.transport.sendWithReply(message); case 5: reply = _context2.sent; this.fsm.updateSuccess(reply.body); this.emit("tokenUpdated"); _context2.next = 14; break; case 10: _context2.prev = 10; _context2.t0 = _context2["catch"](2); if (_context2.t0 instanceof TwilsockReplyError) { isTerminalError = false; logInstance.warn("Token update rejected by server: ".concat(JSON.stringify(_context2.t0.reply.status))); if (_context2.t0.reply.status.code === 401 || _context2.t0.reply.status.code === 403) { isTerminalError = true; this.fsm.tokenRejected(_context2.t0.reply.status); if (_context2.t0.reply.status.errorCode === this.tokenExpiredSasCode) { this.emit("tokenExpired"); } } else if (_context2.t0.reply.status.code === 429) { this.modifyBackoff(_context2.t0.reply.body); this.fsm.updateError(_context2.t0.reply.status); } else { this.fsm.updateError(_context2.t0.reply.status); } this.emitReplyConnectionError(_context2.t0.message, _context2.t0.reply, isTerminalError); } else { this.emit("error", false, _context2.t0.message, null, null); this.fsm.updateError(_context2.t0); } this.emit("tokenUpdated", _context2.t0); case 14: case "end": return _context2.stop(); } } }, _callee2, this, [[2, 10]]); })); function sendUpdate() { return _sendUpdate.apply(this, arguments); } return sendUpdate; }() }, { key: "emitReplyConnectionError", value: function emitReplyConnectionError(message, header, terminal) { var description = header.status && header.status.description ? header.status.description : message; var httpStatusCode = header.status.code; var errorCode = header.status && header.status.errorCode ? header.status.errorCode : null; if (terminal) { this.terminationReason = description; } this.emit("connectionError", { terminal: terminal, message: "Connection error: ".concat(description), httpStatusCode: httpStatusCode, errorCode: errorCode }); } }, { key: "cancelInit", value: function cancelInit() { logInstance.trace("cancelInit"); // TODO: implement } }, { key: "cancelUpdate", value: function cancelUpdate() { logInstance.trace("cancelUpdate"); // TODO: implement } /** * Should be called for each message to confirm it received */ }, { key: "confirmReceiving", value: function confirmReceiving(messageHeader) { logInstance.trace("confirmReceiving"); try { //@todo send telemetry events AnyEvents this.transport.send(new Reply(messageHeader.id)); } catch (e) { logInstance.debug("failed to confirm packet receiving", e); } } /** * Shutdown connection */ }, { key: "closeSocket", value: function closeSocket(graceful) { var _this3 = this; logInstance.trace("closeSocket (graceful: ".concat(graceful, ")")); if (graceful && this.transport.isConnected) { this.transport.sendClose(); } this.websocket.close(); trampoline(function () { return _this3.fsm.socketClosed(); }); } /** * Initiate the twilsock connection * If already connected, it does nothing */ }, { key: "connect", value: function connect() { logInstance.trace("connect"); this.fsm.userConnect(); } /** * Close twilsock connection * If already disconnected, it does nothing */ }, { key: "disconnect", value: function disconnect() { var _this4 = this; logInstance.trace("disconnect"); if (this.fsm.is("disconnected")) { return Promise.resolve(); } return new Promise(function (resolve) { _this4.disconnectedPromiseResolve = resolve; _this4.fsm.userDisconnect(); }); } /** * Update fpa token for twilsock connection */ }, { key: "updateToken", value: function updateToken(token) { var _this5 = this; logInstance.trace("updateToken:", token); return new Promise(function (resolve, reject) { _this5.once("tokenUpdated", function (e) { if (e) { reject(e); } else { resolve(); } }); _this5.fsm.userUpdateToken(); }); } }, { key: "isTerminalState", get: function get() { return this.terminalStates.indexOf(this.fsm.state) !== -1; } }, { key: "getTerminationReason", get: function get() { return this.terminationReason; } }, { key: "onCloseReceived", value: function onCloseReceived() { this.websocket.close(); } }]); return TwilsockChannel; }(EventEmitter); var Metadata = /*#__PURE__*/function () { function Metadata() { _classCallCheck__default['default'](this, Metadata); } _createClass__default['default'](Metadata, null, [{ key: "getMetadata", value: function getMetadata(options) { var _platform$name, _platform$version, _platform$os$family, _platform$os, _platform$os$version, _platform$os2, _platform$os$architec, _platform$os3; var overrides = options && options.clientMetadata ? options.clientMetadata : {}; var fieldNames = ["ver", "env", "envv", "os", "osv", "osa", "type", "sdk", "sdkv", "dev", "devv", "devt", "app", "appv"]; var defaults = { env: (_platform$name = platform__namespace.name) !== null && _platform$name !== void 0 ? _platform$name : "unknown", envv: (_platform$version = platform__namespace.version) !== null && _platform$version !== void 0 ? _platform$version : "unknown", os: (_platform$os$family = (_platform$os = platform__namespace.os) === null || _platform$os === void 0 ? void 0 : _platform$os.family) !== null && _platform$os$family !== void 0 ? _platform$os$family : "unknown", osv: (_platform$os$version = (_platform$os2 = platform__namespace.os) === null || _platform$os2 === void 0 ? void 0 : _platform$os2.version) !== null && _platform$os$version !== void 0 ? _platform$os$version : "unknown", osa: (_platform$os$architec = (_platform$os3 = platform__namespace.os) === null || _platform$os3 === void 0 ? void 0 : _platform$os3.architecture) !== null && _platform$os$architec !== void 0 ? _platform$os$architec : "unknown", sdk: "js-default" }; var finalClientMetadata = {}; fieldNames.filter(function (key) { return key in overrides || key in defaults; }).forEach(function (key) { return finalClientMetadata[key] = key in overrides ? overrides[key] : defaults[key]; }); return finalClientMetadata; } }]); return Metadata; }(); var REQUEST_TIMEOUT$1 = 30000; function isHttpSuccess$1(code) { return code >= 200 && code < 300; } /** * Makes sure that body is properly stringified */ function preparePayload(payload) { switch (_typeof__default['default'](payload)) { case "undefined": return ""; case "object": return JSON.stringify(payload); default: return payload; } } var PacketInterface = /*#__PURE__*/function () { function PacketInterface(channel, config) { var _this = this; _classCallCheck__default['default'](this, PacketInterface); this.config = config; this.activeRequests = new Map(); this.channel = channel; this.channel.on("reply", function (reply) { return _this.processReply(reply); }); this.channel.on("disconnected", function () { _this.activeRequests.forEach(function (descriptor) { clearTimeout(descriptor.timeout); descriptor.reject(new TwilsockError("disconnected")); }); _this.activeRequests.clear(); }); } _createClass__default['default'](PacketInterface, [{ key: "isConnected", get: function get() { return this.channel.isConnected; } }, { key: "processReply", value: function processReply(reply) { var request = this.activeRequests.get(reply.id); if (request) { clearTimeout(request.timeout); this.activeRequests.delete(reply.id); if (!isHttpSuccess$1(reply.status.code)) { request.reject(new TwilsockReplyError("Transport failure: " + reply.status.status, reply)); logInstance.trace("message rejected"); } else { request.resolve(reply); } } } }, { key: "storeRequest", value: function storeRequest(id, resolve, reject) { var requestDescriptor = { resolve: resolve, reject: reject, timeout: setTimeout(function () { logInstance.trace("request", id, "is timed out"); reject(new TwilsockError("Twilsock: request timeout: " + id)); }, REQUEST_TIMEOUT$1) }; this.activeRequests.set(id, requestDescriptor); } }, { key: "shutdown", value: function shutdown() { this.activeRequests.forEach(function (descriptor) { clearTimeout(descriptor.timeout); descriptor.reject(new TwilsockError("Twilsock: request cancelled by user")); }); this.activeRequests.clear(); } }, { key: "sendInit", value: function () { var _sendInit = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() { var metadata, message, response; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: logInstance.trace("sendInit"); metadata = Metadata.getMetadata(this.config); message = new Init(this.config.token, this.config.continuationToken, metadata, this.config.initRegistrations, this.config.tweaks); _context.next = 5; return this.sendWithReply(message); case 5: response = _context.sent; return _context.abrupt("return", new InitReply(response.id, response.header.continuation_token, new Set(response.header.capabilities), response.header.continuation_token_status, response.header.offline_storage, response.header.init_registrations, response.header.debug_info)); case 7: case "end": return _context.stop(); } } }, _callee, this); })); function sendInit() { return _sendInit.apply(this, arguments); } return sendInit; }() }, { key: "sendClose", value: function sendClose() { var message = new Close(); //@todo send telemetry AnyEventsIncludingUnfinished this.send(message); } }, { key: "sendWithReply", value: function sendWithReply(header, payload) { var _this2 = this; return new Promise(function (resolve, reject) { var id = _this2.send(header, payload); _this2.storeRequest(id, resolve, reject); }); } }, { key: "send", value: function send(header, payload) { header.id = header.id || "TM".concat(uuid.v4()); var message = Parser.createPacket(header, preparePayload(payload)); try { this.channel.send(message); return header.id; } catch (e) { logInstance.debug("failed to send ", header, e); logInstance.trace(e.stack); throw e; } } }]); return PacketInterface; }(); function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var WebSocketChannel = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](WebSocketChannel, _EventEmitter); var _super = _createSuper$4(WebSocketChannel); function WebSocketChannel(url) { var _this; _classCallCheck__default['default'](this, WebSocketChannel); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "socket", null); _this.url = url; _this.url = url; _this.WebSocket = global["WebSocket"] || global["MozWebSocket"] || {}; return _this; } _createClass__default['default'](WebSocketChannel, [{ key: "isConnected", get: function get() { return !!this.socket && this.socket.readyState === 1; } }, { key: "connect", value: function connect() { var _this2 = this; logInstance.trace("connecting to socket"); var socket; try { socket = new this.WebSocket(this.url); } catch (e) { logInstance.debug("Socket error: ".concat(this.url)); this.emit("socketError", e); return; } socket.binaryType = "arraybuffer"; socket.onopen = function () { logInstance.debug("socket opened ".concat(_this2.url)); _this2.emit("connected"); }; socket.onclose = function (e) { logInstance.debug("socket closed", e); _this2.emit("disconnected", e); }; socket.onerror = function (e) { logInstance.debug("Socket error:", e); _this2.emit("socketError", e); }; socket.onmessage = function (message) { _this2.emit("message", message.data); }; this.socket = socket; } }, { key: "send", value: function send(message) { return this.socket && this.socket.send(message); } }, { key: "close", value: function close() { logInstance.trace("closing socket"); if (this.socket) { this.socket.onopen = null; this.socket.onclose = null; this.socket.onerror = null; this.socket.onmessage = null; try { this.socket.close(); } finally {} } } }]); return WebSocketChannel; }(EventEmitter); function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * Registrations module handles all operations with registration contexts through twilsock. * Main role: it automatically refreshes all registrations after reconnect. */ var Registrations = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](Registrations, _EventEmitter); var _super = _createSuper$3(Registrations); function Registrations(transport) { var _this; _classCallCheck__default['default'](this, Registrations); _this = _super.call(this); _this.transport = transport; _this.registrations = new Map(); _this.registrationsInProgress = new Map(); return _this; } _createClass__default['default'](Registrations, [{ key: "putNotificationContext", value: function () { var _putNotificationContext = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(contextId, context) { var header; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: header = { method: "put_notification_ctx", notification_ctx_id: contextId }; _context.next = 3; return this.transport.sendWithReply(header, context); case 3: case "end": return _context.stop(); } } }, _callee, this); })); function putNotificationContext(_x, _x2) { return _putNotificationContext.apply(this, arguments); } return putNotificationContext; }() }, { key: "deleteNotificationContext", value: function () { var _deleteNotificationContext = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(contextId) { var message; return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: message = { method: "delete_notification_ctx", notification_ctx_id: contextId }; _context2.next = 3; return this.transport.sendWithReply(message); case 3: case "end": return _context2.stop(); } } }, _callee2, this); })); function deleteNotificationContext(_x3) { return _deleteNotificationContext.apply(this, arguments); } return deleteNotificationContext; }() }, { key: "updateRegistration", value: function () { var _updateRegistration = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(contextId, context) { var registrationAttempts, attemptId; return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: logInstance.debug("update registration for context", contextId); registrationAttempts = this.registrationsInProgress.get(contextId); if (!registrationAttempts) { registrationAttempts = new Set(); this.registrationsInProgress.set(contextId, registrationAttempts); } attemptId = uuid.v4(); registrationAttempts.add(attemptId); _context3.prev = 5; _context3.next = 8; return this.putNotificationContext(contextId, context); case 8: logInstance.debug("registration attempt succeeded for context", context); registrationAttempts.delete(attemptId); if (registrationAttempts.size === 0) { this.registrationsInProgress.delete(contextId); this.emit("registered", contextId); } _context3.next = 19; break; case 13: _context3.prev = 13; _context3.t0 = _context3["catch"](5); logInstance.warn("registration attempt failed for context", context); logInstance.debug(_context3.t0); registrationAttempts.delete(attemptId); if (registrationAttempts.size === 0) { this.registrationsInProgress.delete(contextId); this.emit("registrationFailed", contextId, _context3.t0); } case 19: case "end": return _context3.stop(); } } }, _callee3, this, [[5, 13]]); })); function updateRegistration(_x4, _x5) { return _updateRegistration.apply(this, arguments); } return updateRegistration; }() }, { key: "updateRegistrations", value: function () { var _updateRegistrations = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4() { var _this2 = this; var promises; return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: logInstance.trace("refreshing ".concat(this.registrations.size, " registrations")); promises = []; this.registrations.forEach(function (context, id) { promises.push(_this2.updateRegistration(id, context)); }); _context4.next = 5; return Promise.all(promises); case 5: case "end": return _context4.stop(); } } }, _callee4, this); })); function updateRegistrations() { return _updateRegistrations.apply(this, arguments); } return updateRegistrations; }() }, { key: "setNotificationsContext", value: function () { var _setNotificationsContext = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(contextId, context) { return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (!(!contextId || !context)) { _context5.next = 2; break; } throw new TwilsockError("Invalid arguments provided"); case 2: this.registrations.set(contextId, context); _context5.next = 5; return this.updateRegistration(contextId, context); case 5: return _context5.abrupt("return", _context5.sent); case 6: case "end": return _context5.stop(); } } }, _callee5, this); })); function setNotificationsContext(_x6, _x7) { return _setNotificationsContext.apply(this, arguments); } return setNotificationsContext; }() }, { key: "removeNotificationsContext", value: function () { var _removeNotificationsContext = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(contextId) { return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (this.registrations.has(contextId)) { _context6.next = 2; break; } return _context6.abrupt("return"); case 2: _context6.next = 4; return this.deleteNotificationContext(contextId); case 4: if (this.transport.isConnected) { this.registrations.delete(contextId); } case 5: case "end": return _context6.stop(); } } }, _callee6, this); })); function removeNotificationsContext(_x8) { return _removeNotificationsContext.apply(this, arguments); } return removeNotificationsContext; }() }]); return Registrations; }(EventEmitter); function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TwilsockUpstreamError = /*#__PURE__*/function (_TwilsockError) { _inherits__default['default'](TwilsockUpstreamError, _TwilsockError); var _super = _createSuper$2(TwilsockUpstreamError); function TwilsockUpstreamError(status, description, body) { var _this; _classCallCheck__default['default'](this, TwilsockUpstreamError); _this = _super.call(this, description); _this.status = status; _this.description = description; _this.body = body; return _this; } return TwilsockUpstreamError; }(TwilsockError); function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TransportUnavailableError = /*#__PURE__*/function (_TwilsockError) { _inherits__default['default'](TransportUnavailableError, _TwilsockError); var _super = _createSuper$1(TransportUnavailableError); function TransportUnavailableError(description) { _classCallCheck__default['default'](this, TransportUnavailableError); return _super.call(this, description); } return TransportUnavailableError; }(TwilsockError); var REQUEST_TIMEOUT = 20000; function isHttpSuccess(code) { return code >= 200 && code < 300; } function isHttpReply(packet) { return packet && packet.header && packet.header.http_status; } function parseUri(uri) { var match = uri.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/); if (match) { var uriStruct = { protocol: match[1], host: match[2], hostname: match[3], port: match[4], pathname: match[5], search: match[6], hash: match[7], params: {} }; if (uriStruct.search.length > 0) { var paramsString = uriStruct.search.substring(1); uriStruct.params = paramsString.split("&").map(function (el) { return el.split("="); }).reduce(function (prev, curr) { if (!prev.hasOwnProperty(curr[0])) { prev[curr[0]] = curr[1]; } else if (Array.isArray(prev[curr[0]])) { prev[curr[0]].push(curr[1]); } else { prev[curr[0]] = [prev[curr[0]], curr[1]]; } return prev; }, {}); } return uriStruct; } throw new TwilsockError("Incorrect URI: " + uri); } function twilsockAddress(method, uri) { var parsedUri = parseUri(uri); var to = { method: method, host: parsedUri.host, path: parsedUri.pathname }; if (parsedUri.params) { to.params = parsedUri.params; } return to; } function twilsockParams(method, uri, headers, body, grant) { return { to: twilsockAddress(method, uri), headers: headers, body: body, grant: grant }; } var Upstream = /*#__PURE__*/function () { function Upstream(transport, twilsock, config) { _classCallCheck__default['default'](this, Upstream); this.config = config; this.transport = transport; this.pendingMessages = []; this.twilsock = twilsock; } _createClass__default['default'](Upstream, [{ key: "saveMessage", value: function saveMessage(message) { var _this = this; return new Promise(function (resolve, reject) { var requestDescriptor = { message: message, resolve: resolve, reject: reject, alreadyRejected: false, timeout: setTimeout(function () { logInstance.debug("request is timed out"); reject(new TwilsockError("request '".concat(message.to.method, "' to '").concat(message.to.host, "' timed out"))); requestDescriptor.alreadyRejected = true; }, REQUEST_TIMEOUT) }; _this.pendingMessages.push(requestDescriptor); }); } }, { key: "sendPendingMessages", value: function sendPendingMessages() { var _this2 = this; var _loop = function _loop() { var request = _this2.pendingMessages[0]; // Do not send message if we've rejected its promise already if (!request.alreadyRejected) { try { var message = request.message; _this2.actualSend(message).then(function (response) { return request.resolve(response); }).catch(function (e) { return request.reject(e); }); clearTimeout(request.timeout); } catch (e) { logInstance.debug("Failed to send pending message", e); return "break"; } } _this2.pendingMessages.splice(0, 1); }; while (this.pendingMessages.length > 0) { var _ret = _loop(); if (_ret === "break") break; } } }, { key: "rejectPendingMessages", value: function rejectPendingMessages() { var _this3 = this; this.pendingMessages.forEach(function (message) { message.reject(new TransportUnavailableError( // @todo Error Unhandled promise rejection! "Unable to connect: " + _this3.twilsock.getTerminationReason)); message.alreadyRejected = true; clearTimeout(message.timeout); }); this.pendingMessages.splice(0, this.pendingMessages.length); } }, { key: "actualSend", value: function () { var _actualSend = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(message) { var _message$grant; var address, headers, body, grant, httpRequest, upstreamMessage, reply; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: address = message.to; headers = message.headers; body = message.body; grant = (_message$grant = message.grant) !== null && _message$grant !== void 0 ? _message$grant : this.config.activeGrant; httpRequest = { host: address.host, path: address.path, method: address.method, params: address.params, headers: headers }; upstreamMessage = new Message(grant, headers["Content-Type"] || "application/json", httpRequest); logInstance.trace("Sending upstream message", upstreamMessage); _context.next = 9; return this.transport.sendWithReply(upstreamMessage, body); case 9: reply = _context.sent; logInstance.trace("Received upstream message response", reply); if (!(isHttpReply(reply) && !isHttpSuccess(reply.header.http_status.code))) { _context.next = 13; break; } throw new TwilsockUpstreamError(reply.header.http_status.code, reply.header.http_status.status, reply.body); case 13: return _context.abrupt("return", { status: reply.header.http_status, headers: reply.header.http_headers, body: reply.body }); case 14: case "end": return _context.stop(); } } }, _callee, this); })); function actualSend(_x) { return _actualSend.apply(this, arguments); } return actualSend; }() /** * Send an upstream message * @param {string} method The upstream method * @param {string} url URL to send the message to * @param {object} [headers] The message headers * @param {any} [body] The message body * @param {string} [grant] The product grant * @returns {Promise} Result from remote side */ }, { key: "send", value: function send(method, url) { var headers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var body = arguments.length > 3 ? arguments[3] : undefined; var grant = arguments.length > 4 ? arguments[4] : undefined; if (this.twilsock.isTerminalState) { return Promise.reject(new TransportUnavailableError("Unable to connect: " + this.twilsock.getTerminationReason)); } var twilsockMessage = twilsockParams(method, url, headers, body, grant); if (!this.twilsock.isConnected) { return this.saveMessage(twilsockMessage); } return this.actualSend(twilsockMessage); } }]); return Upstream; }(); var Deferred = /*#__PURE__*/function () { function Deferred() { var _this = this; _classCallCheck__default['default'](this, Deferred); this._promise = new Promise(function (resolve, reject) { _this._resolve = resolve; _this._reject = reject; }); } _createClass__default['default'](Deferred, [{ key: "promise", get: function get() { return this._promise; } }, { key: "update", value: function update(value) { this._resolve(value); } }, { key: "set", value: function set(value) { this._resolve(value); } }, { key: "fail", value: function fail(e) { this._reject(e); } }]); return Deferred; }(); var OfflineProductStorage = /*#__PURE__*/function () { function OfflineProductStorage(id) { _classCallCheck__default['default'](this, OfflineProductStorage); this.id = id; } _createClass__default['default'](OfflineProductStorage, null, [{ key: "create", value: function create(productPayload) { if (productPayload instanceof Object && "storage_id" in productPayload) { return new OfflineProductStorage(productPayload.storage_id); } else { throw new TwilsockError('Field "storage_id" is missing'); } } }]); return OfflineProductStorage; }(); var TokenStorage = /*#__PURE__*/function () { function TokenStorage() { _classCallCheck__default['default'](this, TokenStorage); _defineProperty__default['default'](this, "initializedFlag", "twilio_twilsock_token_storage"); _defineProperty__default['default'](this, "tokenStoragePrefix", "twilio_continuation_token_"); if (!TokenStorage._instance) { this.initialize(); TokenStorage._instance = this; } return TokenStorage._instance; } _createClass__default['default'](TokenStorage, [{ key: "sessionStorage", value: function sessionStorage() { try { return global["sessionStorage"]; } catch (err) { return null; } } }, { key: "window", value: function window() { try { return global["window"]; } catch (err) { return null; } } }, { key: "storeToken", value: function storeToken(continuationToken, productId) { if (this.canStore()) { this.sessionStorage.setItem(this.getKeyName(productId), continuationToken); } } }, { key: "getStoredToken", value: function getStoredToken(productId) { if (!this.canStore()) { return null; } return this.sessionStorage.getItem(this.getKeyName(productId)); } }, { key: "initialize", value: function initialize() { var _this = this; if (this.canStore()) { var flag = this.sessionStorage.getItem(this.initializedFlag); // Duplicated tab, cleaning up all stored keys if (flag) { this.clear(); } this.sessionStorage.setItem(this.initializedFlag, "true"); // When leaving page or refreshing var removeStorageItem = this.sessionStorage.removeItem; this.window.addEventListener("unload", function () { removeStorageItem(_this.initializedFlag); }); } } }, { key: "clear", value: function clear() { if (this.canStore()) { var keyToDelete = []; for (var i = 0; i < this.sessionStorage.length; i++) { var key = this.sessionStorage.key(i); // We manually removed startsWith here due to some problems with babel polyfill setup. // Restore it when we figure out what's wrong. //if (key.startsWith(TokenStorage.tokenStoragePrefix)) { if (key && key.indexOf(this.tokenStoragePrefix) === 0) { keyToDelete.push(key); } } var removeStorageItem = this.sessionStorage.removeItem; keyToDelete.forEach(function (key) { return removeStorageItem(key); }); removeStorageItem(this.initializedFlag); } } }, { key: "getKeyName", value: function getKeyName(productId) { return "".concat(this.tokenStoragePrefix).concat(productId); } }, { key: "canStore", value: function canStore() { return !!(this.sessionStorage && this.sessionStorage.length && this.window); } }]); return TokenStorage; }(); _defineProperty__default['default'](TokenStorage, "_instance", null); var TokenStorage$1 = new TokenStorage(); var TelemetryEventDescription = /*#__PURE__*/function () { function TelemetryEventDescription(title, details, start, end, type, id) { _classCallCheck__default['default'](this, TelemetryEventDescription); this.title = title; this.details = details; this.start = start; this.type = type; this.id = id; this.end = end; } // Prepare telemetry event right before sending it. // Convert times to relative. _createClass__default['default'](TelemetryEventDescription, [{ key: "toTelemetryEvent", value: function toTelemetryEvent() { // Fix dates var now = new Date(); var actualStart = this.start; var actualEnd = this.end ? this.end : now; if (actualEnd < actualStart) { var tmp = actualEnd; actualEnd = actualStart; actualStart = tmp; } // Converting dates to relative offset from current moment in ms var startOffset = actualStart.getTime() - now.getTime(); var endOffset = actualEnd.getTime() - now.getTime(); var result = new TelemetryEvent(startOffset, endOffset, this.title, this.details, this.id, this.type); return result; } }]); return TelemetryEventDescription; }(); exports.TelemetryPoint = void 0; (function (TelemetryPoint) { TelemetryPoint[TelemetryPoint["Start"] = 0] = "Start"; TelemetryPoint[TelemetryPoint["End"] = 1] = "End"; })(exports.TelemetryPoint || (exports.TelemetryPoint = {})); exports.EventSendingLimitation = void 0; (function (EventSendingLimitation) { EventSendingLimitation[EventSendingLimitation["MinEventsPortion"] = 0] = "MinEventsPortion"; EventSendingLimitation[EventSendingLimitation["AnyEvents"] = 1] = "AnyEvents"; EventSendingLimitation[EventSendingLimitation["AnyEventsIncludingUnfinished"] = 2] = "AnyEventsIncludingUnfinished"; })(exports.EventSendingLimitation || (exports.EventSendingLimitation = {})); var TelemetryTracker = /*#__PURE__*/function () { // accumulated events count that is big enough to be sent out of schedule (not on timer but on new event registration) // max events batch size to be sent in a single Telemetry message // started events: have TelemetryEvent::startTime only // events ready to send function TelemetryTracker(config, packetInterface) { _classCallCheck__default['default'](this, TelemetryTracker); _defineProperty__default['default'](this, "minEventsPortionToSend", 50); _defineProperty__default['default'](this, "maxEventsPortionToSend", 100); _defineProperty__default['default'](this, "pendingEvents", new Map()); _defineProperty__default['default'](this, "readyEvents", []); _defineProperty__default['default'](this, "hasInitializationFinished", false); _defineProperty__default['default'](this, "_canSendTelemetry", false); this.config = config; this.packetInterface = packetInterface; } // Keeping this private prevents the type declaration from being generated properly. // Ideally, this should be private. _createClass__default['default'](TelemetryTracker, [{ key: "isTelemetryEnabled", get: function get() { return this.config.confirmedCapabilities.has("telemetry.v1"); } }, { key: "canSendTelemetry", get: function get() { return this._canSendTelemetry && this.isTelemetryEnabled; }, set: function set(enable) { logInstance.debug("TelemetryTracker.canSendTelemetry: ".concat(enable, " TelemetryTracker.isTelemetryEnabled: ").concat(this.isTelemetryEnabled)); // We want to keep telemetry events added in advance but // we need to purge events from previous connection when being disconnected if (this._canSendTelemetry && !enable) { this.pendingEvents.clear(); this.readyEvents = []; } this._canSendTelemetry = enable; if (enable) { this.sendTelemetry(exports.EventSendingLimitation.AnyEvents); } if (enable && !this.hasInitializationFinished) { this.hasInitializationFinished = true; } } // Add complete event }, { key: "addTelemetryEvent", value: function addTelemetryEvent(event) { // Allow adding events before initialization. if (!this.canSendTelemetry && this.hasInitializationFinished) { return; } this.readyEvents.push(event); } // Add incomplete event (with either starting or ending time point) }, { key: "addPartialEvent", value: function addPartialEvent(incompleteEvent, eventKey, point) { logInstance.debug("Adding ".concat(point === exports.TelemetryPoint.Start ? "starting" : "ending", " timepoint for '").concat(eventKey, "' event")); var exists = this.pendingEvents.has(eventKey); if (point === exports.TelemetryPoint.Start) { if (exists) { logInstance.debug("Overwriting starting point for '".concat(eventKey, "' event")); } this.pendingEvents.set(eventKey, incompleteEvent); } else { if (!exists) { logInstance.info("Could not find started event for '".concat(eventKey, "' event")); return; } this.addTelemetryEvent(this.merge(this.pendingEvents.get(eventKey), incompleteEvent)); this.pendingEvents.delete(eventKey); } } }, { key: "getTelemetryToSend", value: function getTelemetryToSend(sendingLimit) { if (!this.canSendTelemetry || this.readyEvents.length == 0) { return []; // Events are collected but not sent until telemetry is enabled } if (sendingLimit == exports.EventSendingLimitation.MinEventsPortion && this.readyEvents.length < this.minEventsPortionToSend) { return []; } return this.getTelemetryPortion(sendingLimit == exports.EventSendingLimitation.AnyEventsIncludingUnfinished); } }, { key: "getTelemetryPortion", value: function getTelemetryPortion(includeUnfinished) { var _this = this; var eventsPortionToSend = Math.min(this.readyEvents.length, this.maxEventsPortionToSend); var res = this.readyEvents.splice(0, eventsPortionToSend); if (includeUnfinished && res.length < this.maxEventsPortionToSend) { this.pendingEvents.forEach(function (value, key) { if (res.length >= _this.maxEventsPortionToSend) { return; // @fixme does not end the loop early } var event = _this.pendingEvents.get(key); _this.pendingEvents.delete(key); res.push(new TelemetryEventDescription("[UNFINISHED] ".concat(event.title), // add prefix title to mark unfinished events for CleanSock event.details, event.start, null, // Not ended, on sending will be replaced with now event.type, event.id)); }); } return res; } // Merging 2 partial events: // use start.startTime & end.endTime. // For other fields, // if there are values in end, use them, // else use values from start. }, { key: "merge", value: function merge(start, end) { return new TelemetryEventDescription(end.title ? end.title : start.title, end.details ? end.details : start.details, start.start, end.end, end.type ? end.type : start.type, end.id ? end.id : start.id); } }, { key: "sendTelemetryIfMinimalPortionCollected", value: function sendTelemetryIfMinimalPortionCollected() { this.sendTelemetry(exports.EventSendingLimitation.MinEventsPortion); } // NB: getTelemetryToSend will return non-empty array only if we have already received initReply // and telemetry.v1 capability is enabled there. }, { key: "sendTelemetry", value: function sendTelemetry(limit) { var events = this.getTelemetryToSend(limit); if (events.length === 0) { return; // not enough telemetry data collected } try { this.packetInterface.send(new Telemetry(events.map(function (e) { return e.toTelemetryEvent(); }))); } catch (err) { logInstance.debug("Error while sending ".concat(events.length, " telemetry events due to ").concat(err, "; they will be resubmitted")); this.readyEvents = this.readyEvents.concat(events); } } }]); return TelemetryTracker; }(); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TelemetryEvents = function TelemetryEvents() { _classCallCheck__default['default'](this, TelemetryEvents); }; /** * @alias Twilsock * @classdesc Client library for the Twilsock service * It allows to recevie service-generated updates as well as bi-directional transport * @fires Twilsock#message * @fires Twilsock#connected * @fires Twilsock#disconnected * @fires Twilsock#tokenAboutToExpire * @fires Twilsock#tokenExpired * @fires Twilsock#stateChanged * @fires Twilsock#connectionError */ _defineProperty__default['default'](TelemetryEvents, "TWILSOCK_CONNECT", "twilsock.sdk.connect"); _defineProperty__default['default'](TelemetryEvents, "TWILSOCK_INIT", "twilsock.sdk.init"); exports.TwilsockClient = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](TwilsockClient, _EventEmitter); var _super = _createSuper(TwilsockClient); /** * @param {string} token Twilio access token * @param {string} productId Product identifier. Should be the same as a grant name in token * @param {object} options Twilsock configuration options */ function TwilsockClient(token, productId, options) { var _this; _classCallCheck__default['default'](this, TwilsockClient); _this = _super.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "version", version); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "offlineStorageDeferred", new Deferred()); options.continuationToken = options.continuationToken ? options.continuationToken : TokenStorage$1.getStoredToken(productId); var config = _this.config = new Configuration(token, productId, options); logInstance.setLevel(config.logLevel); var websocket = new WebSocketChannel(config.url); var transport = new PacketInterface(websocket, config); _this.channel = new TwilsockChannel(websocket, transport, config); _this.registrations = new Registrations(transport); _this.upstream = new Upstream(transport, _this.channel, config); // Send telemetry only when connected and initialised _this.telemetryTracker = new TelemetryTracker(config, transport); _this.channel.on("initialized", function () { return _this.telemetryTracker.canSendTelemetry = true; }); websocket.on("disconnected", function () { return _this.telemetryTracker.canSendTelemetry = false; }); _this.registrations.on("registered", function (id) { return _this.emit("registered", id); }); _this.channel.on("message", function (type, message) { return setTimeout(function () { return _this.emit("message", type, message); }, 0); }); _this.channel.on("stateChanged", function (state) { return setTimeout(function () { return _this.emit("stateChanged", state); }, 0); }); _this.channel.on("connectionError", function (connectionError) { return setTimeout(function () { return _this.emit("connectionError", connectionError); }, 0); }); _this.channel.on("tokenAboutToExpire", function () { return setTimeout(function () { return _this.emit("tokenAboutToExpire"); }, 0); }); _this.channel.on("tokenExpired", function () { return setTimeout(function () { return _this.emit("tokenExpired"); }, 0); }); _this.channel.on("connected", function () { return _this.registrations.updateRegistrations(); }); _this.channel.on("connected", function () { return _this.upstream.sendPendingMessages(); }); _this.channel.on("connected", function () { return setTimeout(function () { return _this.emit("connected"); }, 0); }); // Twilsock telemetry events _this.channel.on("beforeConnect", function () { return _this.telemetryTracker.addPartialEvent(new TelemetryEventDescription("Establish WebSocket connection", "", new Date()), TelemetryEvents.TWILSOCK_CONNECT, exports.TelemetryPoint.Start); }); _this.channel.on("connected", function () { return _this.telemetryTracker.addPartialEvent(new TelemetryEventDescription("Establish WebSocket connection", "", new Date(), new Date()), TelemetryEvents.TWILSOCK_CONNECT, exports.TelemetryPoint.End); }); _this.channel.on("beforeSendInit", function () { return _this.telemetryTracker.addPartialEvent(new TelemetryEventDescription("Send Twilsock init", "", new Date()), TelemetryEvents.TWILSOCK_INIT, exports.TelemetryPoint.Start); }); _this.channel.on("initialized", function () { return _this.telemetryTracker.addPartialEvent(new TelemetryEventDescription("Send Twilsock init", "Succeeded", new Date(), new Date()), TelemetryEvents.TWILSOCK_INIT, exports.TelemetryPoint.End); }); _this.channel.on("sendInitFailed", function () { return _this.telemetryTracker.addPartialEvent(new TelemetryEventDescription("Send Twilsock init", "Failed", new Date(), new Date()), TelemetryEvents.TWILSOCK_INIT, exports.TelemetryPoint.End); }); _this.channel.on("initialized", function (initReply) { _this.handleStorageId(productId, initReply); TokenStorage$1.storeToken(initReply.continuationToken, productId); setTimeout(function () { return _this.emit("initialized", initReply); }, 0); }); _this.channel.on("disconnected", function () { return setTimeout(function () { return _this.emit("disconnected"); }, 0); }); _this.channel.on("disconnected", function () { return _this.upstream.rejectPendingMessages(); }); _this.channel.on("disconnected", function () { return _this.offlineStorageDeferred.fail(new TwilsockError("Client disconnected")); }); _this.offlineStorageDeferred.promise.catch(function () { return void 0; }); return _this; } _createClass__default['default'](TwilsockClient, [{ key: "emit", value: function emit(event) { var _get2; for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } logInstance.debug("Emitting ".concat(event.toString(), "(").concat(args.map(function (a) { return JSON.stringify(a); }).join(", "), ")")); return (_get2 = _get__default['default'](_getPrototypeOf__default['default'](TwilsockClient.prototype), "emit", this)).call.apply(_get2, [this, event].concat(args)); } }, { key: "handleStorageId", value: function handleStorageId(productId, initReply) { if (!initReply.offlineStorage) { this.offlineStorageDeferred.fail(new TwilsockError("No offline storage id")); } else if (initReply.offlineStorage.hasOwnProperty(productId)) { try { this.offlineStorageDeferred.set(OfflineProductStorage.create(initReply.offlineStorage[productId])); logInstance.debug("Offline storage for '".concat(productId, "' product: ").concat(JSON.stringify(initReply.offlineStorage[productId]), ".")); } catch (e) { this.offlineStorageDeferred.fail(new TwilsockError("Failed to parse offline storage for ".concat(productId, " ").concat(JSON.stringify(initReply.offlineStorage[productId]), ". ").concat(e, "."))); } } else { this.offlineStorageDeferred.fail(new TwilsockError("No offline storage id for '".concat(productId, "' product: ").concat(JSON.stringify(initReply.offlineStorage)))); } } /** * Get offline storage ID * @returns {Promise} */ }, { key: "storageId", value: function storageId() { return this.offlineStorageDeferred.promise; } /** * Indicates if twilsock is connected now * @returns {Boolean} */ }, { key: "isConnected", get: function get() { return this.channel.isConnected; } /** * Current state * @returns {ConnectionState} */ }, { key: "state", get: function get() { return this.channel.state; } /** * Update token * @param {String} token * @returns {Promise} */ }, { key: "updateToken", value: function () { var _updateToken = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(token) { return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: logInstance.trace("updating token '".concat(token, "'")); if (!(this.config.token === token)) { _context.next = 3; break; } return _context.abrupt("return"); case 3: this.config.updateToken(token); _context.next = 6; return this.channel.updateToken(token); case 6: return _context.abrupt("return", _context.sent); case 7: case "end": return _context.stop(); } } }, _callee, this); })); function updateToken(_x) { return _updateToken.apply(this, arguments); } return updateToken; }() /** * Updates notification context. * This method shouldn't be used anyone except twilio notifications library * @param contextId id of notification context * @param context value of notification context * @private */ }, { key: "setNotificationsContext", value: function () { var _setNotificationsContext = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(contextId, context) { return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.registrations.setNotificationsContext(contextId, context); case 2: case "end": return _context2.stop(); } } }, _callee2, this); })); function setNotificationsContext(_x2, _x3) { return _setNotificationsContext.apply(this, arguments); } return setNotificationsContext; }() /** * Remove notification context. * This method shouldn't be used anyone except twilio notifications library * @param contextId id of notification context * @private */ }, { key: "removeNotificationsContext", value: function () { var _removeNotificationsContext = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(contextId) { return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.registrations.removeNotificationsContext(contextId); case 2: case "end": return _context3.stop(); } } }, _callee3, this); })); function removeNotificationsContext(_x4) { return _removeNotificationsContext.apply(this, arguments); } return removeNotificationsContext; }() /** * Connect to the server * @fires Twilsock#connected * @public * @returns {void} */ }, { key: "connect", value: function connect() { return this.channel.connect(); } /** * Disconnect from the server * @fires Twilsock#disconnected * @public * @returns {Promise} */ }, { key: "disconnect", value: function () { var _disconnect = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4() { return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: this.telemetryTracker.sendTelemetry(exports.EventSendingLimitation.AnyEventsIncludingUnfinished); _context4.next = 3; return this.channel.disconnect(); case 3: return _context4.abrupt("return", _context4.sent); case 4: case "end": return _context4.stop(); } } }, _callee4, this); })); function disconnect() { return _disconnect.apply(this, arguments); } return disconnect; }() /** * Get HTTP request to upstream service * @param {string} url Upstream service url * @param {headers} headers Set of custom headers * @param {string} [grant] The product grant * @returns {Promise} */ }, { key: "get", value: function () { var _get3 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(url, headers, grant) { return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: this.telemetryTracker.sendTelemetry(exports.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment _context5.next = 3; return this.upstream.send("GET", url, headers, undefined, grant); case 3: return _context5.abrupt("return", _context5.sent); case 4: case "end": return _context5.stop(); } } }, _callee5, this); })); function get(_x5, _x6, _x7) { return _get3.apply(this, arguments); } return get; }() /** * Post HTTP request to upstream service * @param {string} url Upstream service url * @param {headers} headers Set of custom headers * @param {body} body Body to send * @param {string} [grant] The product grant * @returns {Promise} */ }, { key: "post", value: function () { var _post = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(url, headers, body, grant) { return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: this.telemetryTracker.sendTelemetry(exports.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment _context6.next = 3; return this.upstream.send("POST", url, headers, body, grant); case 3: return _context6.abrupt("return", _context6.sent); case 4: case "end": return _context6.stop(); } } }, _callee6, this); })); function post(_x8, _x9, _x10, _x11) { return _post.apply(this, arguments); } return post; }() /** * Put HTTP request to upstream service * @param {string} url Upstream service url * @param {headers} headers Set of custom headers * @param {body} body Body to send * @param {string} [grant] The product grant * @returns {Promise} */ }, { key: "put", value: function () { var _put = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee7(url, headers, body, grant) { return _regeneratorRuntime__default['default'].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: this.telemetryTracker.sendTelemetry(exports.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment _context7.next = 3; return this.upstream.send("PUT", url, headers, body, grant); case 3: return _context7.abrupt("return", _context7.sent); case 4: case "end": return _context7.stop(); } } }, _callee7, this); })); function put(_x12, _x13, _x14, _x15) { return _put.apply(this, arguments); } return put; }() /** * Delete HTTP request to upstream service * @param {string} url Upstream service url * @param {headers} headers Set of custom headers * @param {body} body Body to send * @param {string} [grant] The product grant * @returns {Promise} */ }, { key: "delete", value: function () { var _delete2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee8(url, headers, body, grant) { return _regeneratorRuntime__default['default'].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: this.telemetryTracker.sendTelemetry(exports.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment _context8.next = 3; return this.upstream.send("DELETE", url, headers, body, grant); case 3: return _context8.abrupt("return", _context8.sent); case 4: case "end": return _context8.stop(); } } }, _callee8, this); })); function _delete(_x16, _x17, _x18, _x19) { return _delete2.apply(this, arguments); } return _delete; }() /** * Submits internal telemetry event. Not to be used for any customer and/or sensitive data. * @param {TelemetryEventDescription} event Event details. * @returns {void} */ }, { key: "addTelemetryEvent", value: function addTelemetryEvent(event) { this.telemetryTracker.addTelemetryEvent(event); this.telemetryTracker.sendTelemetryIfMinimalPortionCollected(); // send telemetry if need } /** * Submits internal telemetry event. Not to be used for any customer and/or sensitive data. * @param {TelemetryEventDescription} event Event details. * @param {string} eventKey Unique event key. * @param {TelemetryPoint} point Is this partial event for start or end of measurement. * @returns {void} */ }, { key: "addPartialTelemetryEvent", value: function addPartialTelemetryEvent(event, eventKey, point) { this.telemetryTracker.addPartialEvent(event, eventKey, point); if (point === exports.TelemetryPoint.End) { // this telemetry event is complete, so minimal portion could become ready to send this.telemetryTracker.sendTelemetryIfMinimalPortionCollected(); // send telemetry if need } } }]); return TwilsockClient; }(EventEmitter); exports.TwilsockClient = __decorate([declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, declarativeTypeValidator.nonEmptyString, [declarativeTypeValidator.pureObject, "undefined", declarativeTypeValidator.literal(null)]), __metadata("design:paramtypes", [String, String, Object])], exports.TwilsockClient); /** * Twilsock destination address descriptor * @typedef {Object} Twilsock#Address * @property {String} method - HTTP method. (POST, PUT, etc) * @property {String} host - host name without path. (e.g. my.company.com) * @property {String} path - path on the host (e.g. /my/app/to/call.php) */ /** * Twilsock upstream message * @typedef {Object} Twilsock#Message * @property {Twilsock#Address} to - destination address * @property {Object} headers - HTTP headers * @property {Object} body - Body */ /** * Fired when new message received * @param {Twilsock#Message} message * @event Twilsock#message */ /** * Fired when socket connected * @param {String} URI of endpoint * @event Twilsock#connected */ /** * Fired when socket disconnected * @event Twilsock#disconnected */ /** * Fired when token is about to expire and should be updated * @event Twilsock#tokenAboutToExpire */ /** * Fired when token has expired and connection is aborted * @event Twilsock#tokenExpired */ /** * Fired when socket connected * @param ConnectionState state - general twilsock state * @event Twilsock#stateChanged */ /** * Fired when connection is interrupted by unexpected reason * @type {Object} * @property {Boolean} terminal - twilsock will stop connection attempts * @property {String} message - root cause * @property {Number} [httpStatusCode] - http status code if available * @property {Number} [errorCode] - Twilio public error code if available * @event Twilsock#connectionError */ var InitRegistration = /*#__PURE__*/function () { // It's a Set but TS cannot serialize Sets properly. function InitRegistration(product) { _classCallCheck__default['default'](this, InitRegistration); this.product = product; this.type = "ers"; this.notification_protocol_version = 0; this.message_types = []; } /* * @internal * * Populate init registrations section in the Twilsock configuration generically with * passed-in list of types to register. * * Used only by the SDK, ignore. * * @param {string[]} types List of types to add to init registrations in options. * @param {object} options Twilsock options object to update. Omit to create a new one. */ _createClass__default['default'](InitRegistration, [{ key: "populateInitRegistrations", value: function populateInitRegistrations(types) { var s = new Set(this.message_types); // Update options reference in place for (var idx in types) { s.add(types[idx]); } this.message_types = Array.from(s); } }]); return InitRegistration; }(); exports.InitRegistration = InitRegistration; exports.TelemetryEventDescription = TelemetryEventDescription; exports.TelemetryTracker = TelemetryTracker; exports.TransportUnavailableError = TransportUnavailableError; exports.Twilsock = exports.TwilsockClient; exports.TwilsockError = TwilsockError; })(browser$4); var browser$3 = {}; var DESCRIPTORS$1 = descriptors; var fails$3 = fails$B; var objectKeys = objectKeys$4; var getOwnPropertySymbolsModule = objectGetOwnPropertySymbols; var propertyIsEnumerableModule = objectPropertyIsEnumerable; var toObject$1 = toObject$g; var IndexedObject = indexedObject; // eslint-disable-next-line es/no-object-assign -- safe var $assign = Object.assign; // eslint-disable-next-line es/no-object-defineproperty -- required for testing var defineProperty = Object.defineProperty; // `Object.assign` method // https://tc39.es/ecma262/#sec-object.assign var objectAssign = !$assign || fails$3(function () { // should have correct order of operations (Edge bug) if (DESCRIPTORS$1 && $assign({ b: 1 }, $assign(defineProperty({}, 'a', { enumerable: true, get: function () { defineProperty(this, 'b', { value: 3, enumerable: false }); } }), { b: 2 })).b !== 1) return true; // should work with symbols and should have deterministic property order (V8 bug) var A = {}; var B = {}; // eslint-disable-next-line es/no-symbol -- safe var symbol = Symbol(); var alphabet = 'abcdefghijklmnopqrst'; A[symbol] = 7; alphabet.split('').forEach(function (chr) { B[chr] = chr; }); return $assign({}, A)[symbol] != 7 || objectKeys($assign({}, B)).join('') != alphabet; }) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length` var T = toObject$1(target); var argumentsLength = arguments.length; var index = 1; var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; var propertyIsEnumerable = propertyIsEnumerableModule.f; while (argumentsLength > index) { var S = IndexedObject(arguments[index++]); var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S); var length = keys.length; var j = 0; var key; while (length > j) { key = keys[j++]; if (!DESCRIPTORS$1 || propertyIsEnumerable.call(S, key)) T[key] = S[key]; } } return T; } : $assign; var $$8 = _export; var assign$1 = objectAssign; // `Object.assign` method // https://tc39.es/ecma262/#sec-object.assign // eslint-disable-next-line es/no-object-assign -- required for testing $$8({ target: 'Object', stat: true, forced: Object.assign !== assign$1 }, { assign: assign$1 }); (function (exports) { Object.defineProperty(exports, '__esModule', { value: true }); var _asyncToGenerator = asyncToGenerator.exports; var _classCallCheck = classCallCheck.exports; var _createClass = createClass.exports; var _inherits = inherits.exports; var _possibleConstructorReturn = possibleConstructorReturn.exports; var _getPrototypeOf = getPrototypeOf$2.exports; var _regeneratorRuntime = require$$8; var _typeof = _typeof$2.exports; var twilsock = browser$4; var _assertThisInitialized = assertThisInitialized.exports; var _defineProperty = defineProperty$5.exports; var operationRetrier = browser$5; var _slicedToArray = slicedToArray.exports; var _toConsumableArray = toConsumableArray.exports; var logger = loglevel.exports; var uuid = uuid_1; var declarativeTypeValidator = browser$7; function _interopDefaultLegacy(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function get() { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator); var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck); var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass); var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits); var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn); var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf); var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime); var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof); var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized); var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty); var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray); var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray); var logger__namespace = /*#__PURE__*/_interopNamespace(logger); var uuid__namespace = /*#__PURE__*/_interopNamespace(uuid); function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default["default"](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; } return c > 3 && r && Object.defineProperty(target, key, r), r; } function __metadata(metadataKey, metadataValue) { if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default["default"](Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } var domain; // This constructor is used to store event handlers. Instantiating this is // faster than explicitly calling `Object.create(null)` to get a "clean" empty // object (tested with v8 v4.9). function EventHandlers() {} EventHandlers.prototype = Object.create(null); function EventEmitter() { EventEmitter.init.call(this); } // nodejs oddity // require('events') === require('events').EventEmitter EventEmitter.EventEmitter = EventEmitter; EventEmitter.usingDomains = false; EventEmitter.prototype.domain = undefined; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; EventEmitter.init = function () { this.domain = null; if (EventEmitter.usingDomains) { // if there is an active domain, then attach to it. if (domain.active) ; } if (!this._events || this._events === Object.getPrototypeOf(this)._events) { this._events = new EventHandlers(); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self); } } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1); } } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2); } } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2, arg3); } } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].apply(self, args); } } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events, domain; var doError = type === 'error'; events = this._events; if (events) doError = doError && events.error == null;else if (!doError) return false; domain = this.domain; // If there is no 'error' event listener then throw. if (doError) { er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); er.domainEmitter = this; er.domain = domain; er.domainThrown = false; domain.emit('error', er); } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) { args[i - 1] = arguments[i]; } emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = new EventHandlers(); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; emitWarning(w); } } } return target; } function emitWarning(e) { typeof console.warn === 'function' ? console.warn(e) : console.log(e); } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function _onceWrap(target, type, listener) { var fired = false; function g() { target.removeListener(type, g); if (!fired) { fired = true; listener.apply(target, arguments); } } g.listener = listener; return g; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener && list.listener === listener) { if (--this._eventsCount === 0) this._events = new EventHandlers();else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (list.length === 1) { list[0] = undefined; if (--this._eventsCount === 0) { this._events = new EventHandlers(); return this; } else { delete events[type]; } } else { spliceOne(list, position); } if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; // Alias for removeListener added in NodeJS 10.0 // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener EventEmitter.prototype.off = function (type, listener) { return this.removeListener(type, listener); }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = new EventHandlers(); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = new EventHandlers();else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); for (var i = 0, key; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = new EventHandlers(); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order do { this.removeListener(type, listeners[listeners.length - 1]); } while (listeners[0]); } return this; }; EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = [];else { evlistener = events[type]; if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener); } return ret; }; EventEmitter.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; } list.pop(); } function arrayClone(arr, i) { var copy = new Array(i); while (i--) { copy[i] = arr[i]; } return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } var log = logger__namespace.getLogger("twilio-notificatiions"); function prepareLine(prefix, args) { return ["".concat(new Date().toISOString(), " Twilio.Notifications ").concat(prefix, ":")].concat(Array.from(args)); } var Logger = /*#__PURE__*/function () { function Logger() { _classCallCheck__default["default"](this, Logger); } _createClass__default["default"](Logger, [{ key: "setLevel", value: function setLevel(level) { log.setLevel(level); } }, { key: "trace", value: function trace() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log.trace.apply(null, prepareLine("T", args)); } }, { key: "debug", value: function debug() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } log.debug.apply(null, prepareLine("D", args)); } }, { key: "info", value: function info() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } log.info.apply(null, prepareLine("I", args)); } }, { key: "warn", value: function warn() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } log.warn.apply(null, prepareLine("W", args)); } }, { key: "error", value: function error() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } log.error.apply(null, prepareLine("E", args)); } }]); return Logger; }(); var logInstance = new Logger(); function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RegistrationState = /*#__PURE__*/_createClass__default["default"](function RegistrationState() { var token = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; var notificationId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; var messageTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set(); _classCallCheck__default["default"](this, RegistrationState); this.token = token; this.notificationId = notificationId; this.messageTypes = messageTypes; }); function setDifference(a, b) { return [].concat(_toConsumableArray__default["default"](_toConsumableArray__default["default"](a).filter(function (x) { return !b.has(x); })), _toConsumableArray__default["default"](_toConsumableArray__default["default"](b).filter(function (x) { return !a.has(x); }))); } function hasDifference(a, b) { var reasons = new Set(); if (a.notificationId !== b.notificationId) { reasons.add("notificationId"); } if (a.token !== b.token) { reasons.add("token"); } if (setDifference(a.messageTypes, b.messageTypes).length > 0) { reasons.add("messageType"); } return [reasons.size > 0, reasons]; } var Connector = /*#__PURE__*/function (_EventEmitter) { _inherits__default["default"](Connector, _EventEmitter); var _super = _createSuper$3(Connector); // @todo replace with FSM function Connector(channelType) { var _this; _classCallCheck__default["default"](this, Connector); _this = _super.call(this); _defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "desiredState", new RegistrationState()); _defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "currentState", new RegistrationState()); _defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "_hasActiveAttempt", false); _this.channelType = channelType; return _this; } /** * Set desired notification ID for the registration. * Call commitChanges() afterwards to commit this change. * @param notificationId Notification context ID to register. */ _createClass__default["default"](Connector, [{ key: "setNotificationId", value: function setNotificationId(notificationId) { this.desiredState.notificationId = notificationId; } /** * Return true is this connector is in usable state and should be able to commit changes. */ }, { key: "isActive", value: function isActive() { return this.desiredState.notificationId !== ""; } }, { key: "subscribe", value: function subscribe(messageType) { if (this.desiredState.messageTypes.has(messageType)) { logInstance.debug("message type '".concat(messageType, "' for channel ").concat(this.channelType, " is already registered")); return; } this.desiredState.messageTypes.add(messageType); } }, { key: "unsubscribe", value: function unsubscribe(messageType) { if (!this.desiredState.messageTypes.has(messageType)) { return; } this.desiredState.messageTypes.delete(messageType); } }, { key: "updateToken", value: function updateToken(token) { // @todo not entirely correct? this.desiredState.token = token; } /** * Perform actual registration after all required changes are settled. */ }, { key: "commitChanges", value: function () { var _commitChanges = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() { var _hasDifference, _hasDifference2, needToUpdate, reasons, stateToPersist, persistedState; return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!this._hasActiveAttempt) { _context.next = 3; break; } // Concurrent access violation logInstance.error("One registration attempt is already in progress"); throw new Error("One registration attempt is already in progress"); case 3: _hasDifference = hasDifference(this.desiredState, this.currentState), _hasDifference2 = _slicedToArray__default["default"](_hasDifference, 2), needToUpdate = _hasDifference2[0], reasons = _hasDifference2[1]; if (needToUpdate) { _context.next = 6; break; } return _context.abrupt("return"); case 6: if (!this.currentState.notificationId) { reasons.delete("notificationId"); } logInstance.trace("Persisting ".concat(this.channelType, " registration"), reasons, this.desiredState); _context.prev = 8; this._hasActiveAttempt = true; stateToPersist = new RegistrationState(); stateToPersist.token = this.desiredState.token; stateToPersist.notificationId = this.desiredState.notificationId; stateToPersist.messageTypes = new Set(this.desiredState.messageTypes); if (!(stateToPersist.messageTypes.size > 0)) { _context.next = 24; break; } _context.next = 17; return this.updateRegistration(stateToPersist, reasons); case 17: persistedState = _context.sent; this.currentState.token = persistedState.token; this.currentState.notificationId = persistedState.notificationId; this.currentState.messageTypes = new Set(persistedState.messageTypes); // @todo twilsock emits registered(notificationContextId) when this context is reg'd this.emit("stateChanged", this.channelType, "registered", this.currentState); _context.next = 30; break; case 24: _context.next = 26; return this.removeRegistration(); case 26: this.currentState.token = stateToPersist.token; this.currentState.notificationId = stateToPersist.notificationId; this.currentState.messageTypes.clear(); this.emit("stateChanged", this.channelType, "unregistered", this.currentState); case 30: _context.next = 35; break; case 32: _context.prev = 32; _context.t0 = _context["catch"](8); throw _context.t0; case 35: _context.prev = 35; this._hasActiveAttempt = false; return _context.finish(35); case 38: case "end": return _context.stop(); } } }, _callee, this, [[8, 32, 35, 38]]); })); function commitChanges() { return _commitChanges.apply(this, arguments); } return commitChanges; }() }]); return Connector; }(EventEmitter); function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var retrierConfig = { min: 2000, max: 120000, randomness: 0.2 }; /** * Manages the registrations on ERS service. * Deduplicates registrations and manages them automatically. */ var RegistrarConnector = /*#__PURE__*/function (_Connector) { _inherits__default["default"](RegistrarConnector, _Connector); var _super = _createSuper$2(RegistrarConnector); /** * Creates new instance of the ERS registrar * * @param channelType {string} Channel this connector will be servicing. * @param context {any} productId, platform, and protocolVersion. * @param twilsock {TwilsockClient} connection transport. * @param registrarUrl {string} */ function RegistrarConnector(channelType, context, // context is separate from config because it's not shared with other connectors twilsock, registrarUrl) { var _this; _classCallCheck__default["default"](this, RegistrarConnector); _this = _super.call(this, channelType); _defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "registrationId", null); _this.context = context; _this.twilsock = twilsock; _this.registrarUrl = registrarUrl; return _this; } _createClass__default["default"](RegistrarConnector, [{ key: "updateRegistration", value: function () { var _updateRegistration = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(registration, reasons) { var _this2 = this; var registrarRequest, productId, url, headers, response; return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!reasons.has("notificationId")) { _context.next = 3; break; } _context.next = 3; return this.removeRegistration(); case 3: if (!(!registration.notificationId || !registration.notificationId.length)) { _context.next = 6; break; } logInstance.error("No push notification ID for registration"); throw new Error("No push notification ID for registration"); case 6: logInstance.trace("Registering", this.channelType, registration); registrarRequest = { endpoint_platform: this.context.platform, channel_type: this.channelType, version: this.context.protocolVersion.toString(), message_types: Array.from(registration.messageTypes), data: { registration_id: registration.notificationId } //ttl: 'PT24H' - This is totally ignored by notify, all bindings use PT1Y ttl. }; productId = this.context.productId; url = "".concat(this.registrarUrl, "?productId=").concat(productId); headers = { "Content-Type": "application/json" // 'X-Twilio-Token': registration.token }; logInstance.trace("Creating registration for channel ".concat(this.channelType)); _context.prev = 12; _context.next = 15; return new operationRetrier.AsyncRetrier(retrierConfig).run(function () { return _this2.twilsock.post(url, headers, registrarRequest, productId); }); case 15: response = _context.sent; this.registrationId = response.body.id; logInstance.debug("Registration created: ", response); _context.next = 24; break; case 20: _context.prev = 20; _context.t0 = _context["catch"](12); logInstance.error("Registration failed: ", _context.t0); throw _context.t0; case 24: return _context.abrupt("return", registration); case 25: case "end": return _context.stop(); } } }, _callee, this, [[12, 20]]); })); function updateRegistration(_x, _x2) { return _updateRegistration.apply(this, arguments); } return updateRegistration; }() }, { key: "removeRegistration", value: function () { var _removeRegistration = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() { var _this3 = this; var productId, url, headers; return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (this.registrationId) { _context2.next = 2; break; } return _context2.abrupt("return"); case 2: productId = this.context.productId; url = "".concat(this.registrarUrl, "/").concat(this.registrationId, "?productId=").concat(productId); headers = { "Content-Type": "application/json" // 'X-Twilio-Token': this.config.token }; logInstance.trace("Removing registration for ".concat(this.channelType)); _context2.prev = 6; _context2.next = 9; return new operationRetrier.AsyncRetrier(Object.assign(retrierConfig, { maxAttemptsCount: 3 })).run(function () { return _this3.twilsock.delete(url, headers, {}, productId); }); case 9: this.registrationId = null; this.currentState.notificationId = ""; logInstance.debug("Registration removed for ".concat(this.channelType)); _context2.next = 18; break; case 14: _context2.prev = 14; _context2.t0 = _context2["catch"](6); logInstance.error("Failed to remove registration ", this.channelType, _context2.t0); throw _context2.t0; case 18: case "end": return _context2.stop(); } } }, _callee2, this, [[6, 14]]); })); function removeRegistration() { return _removeRegistration.apply(this, arguments); } return removeRegistration; }() }, { key: "sendDeviceRemoveRequest", value: function () { var _sendDeviceRemoveRequest = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(registrationId) { var _this4 = this; var productId, url, headers, payload; return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(registrationId === "")) { _context3.next = 2; break; } throw new Error("Empty registration ID"); case 2: productId = this.context.productId; url = "".concat(this.registrarUrl, "?productId=").concat(productId); headers = { "Content-Type": "application/json" // @todo Content-Length?? }; payload = { binding_type: this.channelType, address: registrationId }; _context3.prev = 6; logInstance.trace("Removing old registrations for ".concat(this.channelType)); _context3.next = 10; return new operationRetrier.AsyncRetrier(Object.assign(retrierConfig, { maxAttemptsCount: 3 })).run(function () { return _this4.twilsock.delete(url, headers, payload, productId); }); case 10: this.registrationId = null; this.currentState.notificationId = ""; logInstance.debug("Registration removed for ".concat(this.channelType)); _context3.next = 19; break; case 15: _context3.prev = 15; _context3.t0 = _context3["catch"](6); logInstance.error("Failed to remove registration ", this.channelType, _context3.t0); throw _context3.t0; case 19: case "end": return _context3.stop(); } } }, _callee3, this, [[6, 15]]); })); function sendDeviceRemoveRequest(_x3) { return _sendDeviceRemoveRequest.apply(this, arguments); } return sendDeviceRemoveRequest; }() }]); return RegistrarConnector; }(Connector); function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * Registrar connector implementation for twilsock -- @todo Drop twilsock.connector COMPLETELY?! */ var TwilsockConnector = /*#__PURE__*/function (_Connector) { _inherits__default["default"](TwilsockConnector, _Connector); var _super = _createSuper$1(TwilsockConnector); /** * Create twilsock registration connector. * @param productId product ID * @param platform platform ID string * @param twilsock {TwilsockClient} connection transport. */ function TwilsockConnector(productId, platform, twilsock) { var _this; _classCallCheck__default["default"](this, TwilsockConnector); _this = _super.call(this, "twilsock"); _defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "contextId", uuid__namespace.v4()); _this.productId = productId; _this.platform = platform; _this.twilsock = twilsock; return _this; } _createClass__default["default"](TwilsockConnector, [{ key: "updateRegistration", value: function () { var _updateRegistration = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(registration, reasons) { var messageTypes, context; return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (reasons.has("messageType")) { _context.next = 2; break; } return _context.abrupt("return", registration); case 2: messageTypes = Array.from(registration.messageTypes); context = { product_id: this.productId, notification_protocol_version: 4, endpoint_platform: this.platform, message_types: messageTypes }; _context.prev = 4; _context.next = 7; return this.twilsock.setNotificationsContext(this.contextId, context); case 7: _context.next = 13; break; case 9: _context.prev = 9; _context.t0 = _context["catch"](4); logInstance.error("Failed to update twilsock notification context: ".concat(_context.t0)); throw _context.t0; case 13: return _context.abrupt("return", registration); case 14: case "end": return _context.stop(); } } }, _callee, this, [[4, 9]]); })); function updateRegistration(_x, _x2) { return _updateRegistration.apply(this, arguments); } return updateRegistration; }() }, { key: "removeRegistration", value: function () { var _removeRegistration = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() { return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; _context2.next = 3; return this.twilsock.removeNotificationsContext(this.contextId); case 3: _context2.next = 9; break; case 5: _context2.prev = 5; _context2.t0 = _context2["catch"](0); logInstance.error("Failed to remove twilsock notification context: ".concat(_context2.t0)); throw _context2.t0; case 9: case "end": return _context2.stop(); } } }, _callee2, this, [[0, 5]]); })); function removeRegistration() { return _removeRegistration.apply(this, arguments); } return removeRegistration; }() // eslint-disable-next-line @typescript-eslint/no-unused-vars }, { key: "sendDeviceRemoveRequest", value: function () { var _sendDeviceRemoveRequest = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(registrationId) { return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: case "end": return _context3.stop(); } } }, _callee3); })); function sendDeviceRemoveRequest(_x3) { return _sendDeviceRemoveRequest.apply(this, arguments); } return sendDeviceRemoveRequest; }() }]); return TwilsockConnector; }(Connector); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Client_1; var channelTypeRule = declarativeTypeValidator.literal("apn", "fcm", "twilsock"); /** * @class * @alias Notifications * @classdesc The helper library for the notification service. * Provides high level api for creating and managing notification subscriptions and receiving messages * Creates the instance of Notification helper library * * @constructor * @param {string} token - Twilio access token * @param {Notifications#ClientOptions} options - Options to customize client behavior * * @event stateChanged channelType (registered|unregistered) -- coming from connector, i.e. it's per-connector type! * @event transportState Forwarded from Twilsock's stateChanged event. * @event message Routed from twilsock as a notification event. */ exports.Notifications = Client_1 = /*#__PURE__*/function (_EventEmitter) { _inherits__default["default"](Client, _EventEmitter); var _super = _createSuper(Client); function Client(token) { var _options$logLevel, _options$productId, _options$twilsockClie, _options$notification, _ref, _config$region; var _this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck__default["default"](this, Client); _this = _super.call(this); options.logLevel = (_options$logLevel = options.logLevel) !== null && _options$logLevel !== void 0 ? _options$logLevel : "error"; logInstance.setLevel(options.logLevel); var productId = (_options$productId = options.productId) !== null && _options$productId !== void 0 ? _options$productId : "notifications"; var startTwilsock = !options.twilsockClient; var twilsock$1 = options.twilsockClient = (_options$twilsockClie = options.twilsockClient) !== null && _options$twilsockClie !== void 0 ? _options$twilsockClie : new twilsock.TwilsockClient(token, productId, options); var config = (_options$notification = options.notifications) !== null && _options$notification !== void 0 ? _options$notification : {}; var region = (_ref = (_config$region = config.region) !== null && _config$region !== void 0 ? _config$region : options.region) !== null && _ref !== void 0 ? _ref : "us1"; var defaultUrl = "https://ers.".concat(region, ".twilio.com/v1/registrations"); var registrarUrl = config.ersUrl || defaultUrl; _this.connectors = new Map(); var platform = Client_1._detectPlatform(); _this.connectors.set("apn", new RegistrarConnector("apn", { protocolVersion: 4, productId: productId, platform: platform }, twilsock$1, registrarUrl)); _this.connectors.set("fcm", new RegistrarConnector("fcm", { protocolVersion: 3, productId: productId, platform: platform }, twilsock$1, registrarUrl)); _this.connectors.set("twilsock", new TwilsockConnector(productId, platform, twilsock$1)); twilsock$1.on("stateChanged", function (state) { return _this.emit("transportState", state); }); _this._connector("twilsock").on("stateChanged", function (type, value, state) { return _this.emit("stateChanged", type, value, state); }); _this._connector("apn").on("stateChanged", function (type, value, state) { return _this.emit("stateChanged", type, value, state); }); _this._connector("fcm").on("stateChanged", function (type, value, state) { return _this.emit("stateChanged", type, value, state); }); // Router twilsock$1.on("message", function (type, message) { return _this._routeMessage(type, message); }); _this.updateToken(token); // Start only if we created twilsock locally, // otherwise it's the responsibility of whoever created the Twilsock client. if (startTwilsock) { twilsock$1.connect(); _this.twilsock = twilsock$1; } return _this; } _createClass__default["default"](Client, [{ key: "shutdown", value: function () { var _shutdown = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() { return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: this.connectors.clear(); if (!this.twilsock) { _context.next = 4; break; } _context.next = 4; return this.twilsock.disconnect(); case 4: case "end": return _context.stop(); } } }, _callee, this); })); function shutdown() { return _shutdown.apply(this, arguments); } return shutdown; }() /** * Set OS-provided APNS/FCM registration binding for the given channel type. Not used for 'twilsock'. * * You must call this function once you've received the ID of your device from the underlying OS. * * @param {ChannelType} channelType Channel type ('apn'/'fcm'). * @param {string} pushRegistrationId Token received from FCM/APNS system on device. */ }, { key: "setPushRegistrationId", value: function setPushRegistrationId(channelType, pushRegistrationId) { logInstance.debug("Set ".concat(channelType, " push registration id '").concat(pushRegistrationId, "'")); this._connector(channelType).setNotificationId(pushRegistrationId); } /** * Subscribe to a given message type for a given channel type. * * Creates a subscriptions to receive incoming messages according to message type. * Subscription establishes a binding and you will receive a signal when a notification * of this type has been received by the library. * * Subscribed binding is preserved for 1 year, after which time it needs to be re-subscribed. * This is the responsibility of the client SDK. * * @param {ChannelType} channelType Supported are 'twilsock', 'apn' and 'fcm' * @param {string} messageType The type of message that you want to receive */ }, { key: "subscribe", value: function subscribe(channelType, messageType) { logInstance.debug("Add ".concat(channelType, " subscriptions for message type ").concat(messageType)); this._connector(channelType).subscribe(messageType); } /** * Unsubscribe from a given message type. * * Unsubscribing breaks a binding and you will not receive more notifications for this message type. * Please note that you have to call commitChanges() and receive a successful result before * the subscription is actually removed. * * @param {ChannelType} channelType Supported are 'twilsock', 'apn' and 'fcm' * @param {string} messageType The type of message that you don't want to receive anymore */ }, { key: "unsubscribe", value: function unsubscribe(channelType, messageType) { logInstance.debug("Remove ".concat(channelType, " subscriptions for message type ").concat(messageType)); this._connector(channelType).unsubscribe(messageType); } /** * Update subscription token. You must update the token when the old one expires. * * When you receive onTokenWillExpire event from twilsock, call this function with the new refreshed * token _after_ you have updated twilsock and other associated objects with the new token. * * @param {string} token Authentication token for registrations */ }, { key: "updateToken", value: function updateToken(token) { this.connectors.forEach(function (connector) { return connector.updateToken(token); }); } /** * Commit all collected subscription changes as a batched update. This function tries to reduce * number of network calls necessary to update bindings status. */ }, { key: "commitChanges", value: function () { var _commitChanges = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() { var promises; return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: promises = []; this.connectors.forEach(function (connector) { if (connector.isActive()) { promises.push(connector.commitChanges()); } }); _context2.next = 4; return Promise.all(promises); case 4: case "end": return _context2.stop(); } } }, _callee2, this); })); function commitChanges() { return _commitChanges.apply(this, arguments); } return commitChanges; }() /** * Clear existing registrations directly using provided device token. * This is useful to ensure stopped subscriptions without resubscribing. * * This function goes completely beside the state machine and removes all registrations. * Use with caution: if it races with current state machine operations, madness will ensue. * * @param {ChannelType} channelType Channel type ('apn'/'fcm'). * @param {string} registrationId Token received from FCM/APNS system on device. */ }, { key: "removeRegistrations", value: function () { var _removeRegistrations = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(channelType, registrationId) { return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this._connector(channelType).sendDeviceRemoveRequest(registrationId); case 2: case "end": return _context3.stop(); } } }, _callee3, this); })); function removeRegistrations(_x, _x2) { return _removeRegistrations.apply(this, arguments); } return removeRegistrations; }() /** * Handle incoming push notification. * Client application should call this method when it receives push notifications and pass the received data. * @param {Object} message push message * @return {PushNotification} A reformatted payload with extracted message type. */ }, { key: "handlePushNotification", value: function handlePushNotification(message) { return { messageType: message.twi_message_type, payload: message.payload }; } /** * Routes messages to the external subscribers */ }, { key: "_routeMessage", value: function _routeMessage(type, message) { logInstance.debug("Notification message arrived: ", type, message); this.emit("message", type, message); } /** * @param {String} type Channel type * @throws {Error} Error with description */ }, { key: "_connector", value: function _connector(type) { var connector = this.connectors.get(type); if (!connector) { throw new Error("Unknown channel type: ".concat(type)); } return connector; } /** * Returns platform string limited to max 128 chars */ }], [{ key: "_detectPlatform", value: function _detectPlatform() { var platform = ""; if (typeof navigator !== "undefined") { platform = "unknown"; if (typeof navigator.product !== "undefined") { platform = navigator.product; } if (typeof navigator.userAgent !== "undefined") { platform = navigator.userAgent; } } else { platform = "web"; } return platform.substring(0, 128); } }]); return Client; }(EventEmitter); __decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "setPushRegistrationId", null); __decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "subscribe", null); __decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "unsubscribe", null); __decorate([declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "updateToken", null); __decorate([declarativeTypeValidator.validateTypesAsync(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", Promise)], exports.Notifications.prototype, "removeRegistrations", null); exports.Notifications = Client_1 = __decorate([declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, [declarativeTypeValidator.pureObject, "undefined", declarativeTypeValidator.literal(null)]), __metadata("design:paramtypes", [String, Object])], exports.Notifications); })(browser$3); var browser$2 = {}; Object.defineProperty(browser$2, '__esModule', { value: true }); var _asyncToGenerator = asyncToGenerator.exports; var _classCallCheck = classCallCheck.exports; var _createClass = createClass.exports; var _assertThisInitialized = assertThisInitialized.exports; var _inherits = inherits.exports; var _possibleConstructorReturn = possibleConstructorReturn.exports; var _getPrototypeOf = getPrototypeOf$2.exports; var _defineProperty = defineProperty$5.exports; var _regeneratorRuntime = require$$8; var _typeof = _typeof$2.exports; var declarativeTypeValidator = browser$7; var twilsock = browser$4; var _wrapNativeSuper = wrapNativeSuper.exports; var loglevelLog = loglevel.exports; var _slicedToArray = slicedToArray.exports; var operationRetrier = browser$5; var uuid = uuid_1; var _get = get$1.exports; var platform = platform$1.exports; function _interopDefaultLegacy$2(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } function _interopNamespace$1(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function get() { return e[k]; } }); } }); } n['default'] = e; return Object.freeze(n); } var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy$2(_asyncToGenerator); var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy$2(_classCallCheck); var _createClass__default = /*#__PURE__*/_interopDefaultLegacy$2(_createClass); var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy$2(_assertThisInitialized); var _inherits__default = /*#__PURE__*/_interopDefaultLegacy$2(_inherits); var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy$2(_possibleConstructorReturn); var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy$2(_getPrototypeOf); var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy$2(_defineProperty); var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy$2(_regeneratorRuntime); var _typeof__default = /*#__PURE__*/_interopDefaultLegacy$2(_typeof); var _wrapNativeSuper__default = /*#__PURE__*/_interopDefaultLegacy$2(_wrapNativeSuper); var loglevelLog__namespace = /*#__PURE__*/_interopNamespace$1(loglevelLog); var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy$2(_slicedToArray); var uuid__namespace = /*#__PURE__*/_interopNamespace$1(uuid); var _get__default = /*#__PURE__*/_interopDefaultLegacy$2(_get); var platform__namespace = /*#__PURE__*/_interopNamespace$1(platform); function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default['default'](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; } return c > 3 && r && Object.defineProperty(target, key, r), r; } function __metadata(metadataKey, metadataValue) { if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default['default'](Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } var domain; // This constructor is used to store event handlers. Instantiating this is // faster than explicitly calling `Object.create(null)` to get a "clean" empty // object (tested with v8 v4.9). function EventHandlers() {} EventHandlers.prototype = Object.create(null); function EventEmitter() { EventEmitter.init.call(this); } // nodejs oddity // require('events') === require('events').EventEmitter EventEmitter.EventEmitter = EventEmitter; EventEmitter.usingDomains = false; EventEmitter.prototype.domain = undefined; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; EventEmitter.init = function () { this.domain = null; if (EventEmitter.usingDomains) { // if there is an active domain, then attach to it. if (domain.active) ; } if (!this._events || this._events === Object.getPrototypeOf(this)._events) { this._events = new EventHandlers(); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self); } } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1); } } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2); } } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2, arg3); } } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].apply(self, args); } } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events, domain; var doError = type === 'error'; events = this._events; if (events) doError = doError && events.error == null;else if (!doError) return false; domain = this.domain; // If there is no 'error' event listener then throw. if (doError) { er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); er.domainEmitter = this; er.domain = domain; er.domainThrown = false; domain.emit('error', er); } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) { args[i - 1] = arguments[i]; } emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = new EventHandlers(); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; emitWarning(w); } } } return target; } function emitWarning(e) { typeof console.warn === 'function' ? console.warn(e) : console.log(e); } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function _onceWrap(target, type, listener) { var fired = false; function g() { target.removeListener(type, g); if (!fired) { fired = true; listener.apply(target, arguments); } } g.listener = listener; return g; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener && list.listener === listener) { if (--this._eventsCount === 0) this._events = new EventHandlers();else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (list.length === 1) { list[0] = undefined; if (--this._eventsCount === 0) { this._events = new EventHandlers(); return this; } else { delete events[type]; } } else { spliceOne(list, position); } if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; // Alias for removeListener added in NodeJS 10.0 // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener EventEmitter.prototype.off = function (type, listener) { return this.removeListener(type, listener); }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = new EventHandlers(); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = new EventHandlers();else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); for (var i = 0, key; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = new EventHandlers(); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order do { this.removeListener(type, listeners[listeners.length - 1]); } while (listeners[0]); } return this; }; EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = [];else { evlistener = events[type]; if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener); } return ret; }; EventEmitter.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; } list.pop(); } function arrayClone(arr, i) { var copy = new Array(i); while (i--) { copy[i] = arr[i]; } return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } /** * Construct URI with query parameters */ var UriBuilder = /*#__PURE__*/function () { function UriBuilder(base) { _classCallCheck__default['default'](this, UriBuilder); this.base = base; this.args = new Array(); this.paths = new Array(); } _createClass__default['default'](UriBuilder, [{ key: "pathSegment", value: function pathSegment(name) { this.paths.push(encodeURIComponent(name)); return this; } }, { key: "queryParam", value: function queryParam(name, value) { if (typeof value !== 'undefined') { this.args.push(encodeURIComponent(name) + '=' + encodeURIComponent(value)); } return this; } }, { key: "build", value: function build() { var result = this.base; if (this.paths.length) { result += '/' + this.paths.join('/'); } if (this.args.length) { result += '?' + this.args.join('&'); } return result; } }]); return UriBuilder; }(); function _createSuper$7$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$7$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * Generic SyncLibrary error class */ var SyncError = /*#__PURE__*/function (_Error) { _inherits__default['default'](SyncError, _Error); var _super = _createSuper$7$1(SyncError); function SyncError(message) { var _this; var status = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var code = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; _classCallCheck__default['default'](this, SyncError); _this = _super.call(this); _this.name = _this.constructor.name; _this.message = "".concat(message, " (status: ").concat(status, ", code: ").concat(code, ")"); _this.status = status; _this.code = code; return _this; } return SyncError; }( /*#__PURE__*/_wrapNativeSuper__default['default'](Error)); var SyncNetworkError = /*#__PURE__*/function (_SyncError) { _inherits__default['default'](SyncNetworkError, _SyncError); var _super2 = _createSuper$7$1(SyncNetworkError); function SyncNetworkError(message) { var _this2; var status = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var code = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var body = arguments.length > 3 ? arguments[3] : undefined; _classCallCheck__default['default'](this, SyncNetworkError); _this2 = _super2.call(this, message, status, code); _this2.body = body; return _this2; } return SyncNetworkError; }(SyncError); /** * Deep-clone an object. Note that this does not work on object containing * functions. * @param {object} obj - the object to deep-clone * @return {object} */ function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); } function validatePageSize(pageSize) { var validPageSize = pageSize === undefined || isPositiveInteger(pageSize); if (!validPageSize) { throw new SyncError("Invalid pageSize parameter. Expected a positive integer, was '".concat(pageSize, "'."), 400, 20007); } } function isInteger(number) { return !isNaN(parseInt(number)) && isFinite(number); } function isPositiveInteger(number) { return isInteger(number) && number > 0; } var log$7 = loglevelLog__namespace.getLogger('twilio-sync'); // twilio-sync is used by Flex SDK. Please DO NOT change function prepareLine(prefix, args) { return ["".concat(new Date().toISOString(), " Sync ").concat(prefix, ":")].concat(Array.from(args)); } var log$1$1 = { setLevel: function setLevel(level) { log$7.setLevel(level); }, trace: function trace() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log$7.trace.apply(null, prepareLine('T', args)); }, debug: function debug() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } log$7.debug.apply(null, prepareLine('D', args)); }, info: function info() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } log$7.info.apply(null, prepareLine('I', args)); }, warn: function warn() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } log$7.warn.apply(null, prepareLine('W', args)); }, error: function error() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } log$7.error.apply(null, prepareLine('E', args)); } }; var SUBSCRIPTIONS_PATH = '/v4/Subscriptions'; var MAPS_PATH = '/v3/Maps'; var LISTS_PATH = '/v3/Lists'; var DOCUMENTS_PATH = '/v3/Documents'; var STREAMS_PATH = '/v3/Streams'; var INSIGHTS_PATH = '/v3/Insights'; function getWithDefault(container, key, defaultValue) { if (container && typeof container[key] !== 'undefined') { return container[key]; } return defaultValue; } /** * Settings container for Sync library */ var Configuration = /*#__PURE__*/function () { /** * @param {Object} options */ function Configuration() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck__default['default'](this, Configuration); var region = options.region || 'us1'; var defaultCdsUrl = "https://cds.".concat(region, ".twilio.com"); var baseUri = options.cdsUri || defaultCdsUrl; this.settings = { subscriptionsUri: baseUri + SUBSCRIPTIONS_PATH, documentsUri: baseUri + DOCUMENTS_PATH, listsUri: baseUri + LISTS_PATH, mapsUri: baseUri + MAPS_PATH, streamsUri: baseUri + STREAMS_PATH, insightsUri: baseUri + INSIGHTS_PATH, sessionStorageEnabled: getWithDefault(options.Sync, 'enableSessionStorage', true), productId: options.productId }; } _createClass__default['default'](Configuration, [{ key: "subscriptionsUri", get: function get() { return this.settings.subscriptionsUri; } }, { key: "documentsUri", get: function get() { return this.settings.documentsUri; } }, { key: "listsUri", get: function get() { return this.settings.listsUri; } }, { key: "mapsUri", get: function get() { return this.settings.mapsUri; } }, { key: "streamsUri", get: function get() { return this.settings.streamsUri; } }, { key: "insightsUri", get: function get() { return this.settings.insightsUri; } }, { key: "backoffConfig", get: function get() { return this.settings.backoffConfig || {}; } }, { key: "sessionStorageEnabled", get: function get() { return this.settings.sessionStorageEnabled; } }, { key: "productId", get: function get() { return this.settings.productId; } }]); return Configuration; }(); function _createForOfIteratorHelper$3(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$3(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$3(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen); } function _arrayLikeToArray$3(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * A data container used by the Subscriptions class to track subscribed entities' local * representations and their state. */ var SubscribedEntity = /*#__PURE__*/function () { function SubscribedEntity(entity) { _classCallCheck__default['default'](this, SubscribedEntity); this.localObject = entity; this.pendingCorrelationId = null; this.pendingAction = null; this.established = false; this.retryCount = 0; } _createClass__default['default'](SubscribedEntity, [{ key: "sid", get: function get() { return this.localObject.sid; } }, { key: "type", get: function get() { return this.localObject.type; } }, { key: "lastEventId", get: function get() { return this.localObject.lastEventId; } // below properties are specific to Insights only }, { key: "indexName", get: function get() { return this.localObject.indexName; } }, { key: "queryString", get: function get() { return this.localObject.queryString; } }, { key: "isEstablished", get: function get() { return this.established; } }, { key: "update", value: function update(event, isStrictlyOrdered) { this.localObject._update(event, isStrictlyOrdered); } }, { key: "updatePending", value: function updatePending(action, correlationId) { this.pendingAction = action; this.pendingCorrelationId = correlationId; } }, { key: "reset", value: function reset() { this.updatePending(null, null); this.retryCount = 0; this.established = false; this.setSubscriptionState('none'); } }, { key: "markAsFailed", value: function markAsFailed(message) { this.rejectedWithError = message.error; this.updatePending(null, null); this.localObject.reportFailure(new SyncError("Failed to subscribe on service events: ".concat(message.error.message), message.error.status, message.error.code)); } }, { key: "complete", value: function complete(eventId) { this.updatePending(null, null); this.established = true; this.localObject._advanceLastEventId(eventId); } }, { key: "setSubscriptionState", value: function setSubscriptionState(newState) { this.localObject._setSubscriptionState(newState); } }]); return SubscribedEntity; }(); /** * @class Subscriptions * @classdesc A manager which, in batches of varying size, continuously persists the * subscription intent of the caller to the Sync backend until it achieves a * converged state. */ var Subscriptions = /*#__PURE__*/function () { // This is always the full set of subscribables (SubscribedEntity instances) intended by // the client. At any point, whatever the state of these subscriptions on the server, this // is the intent of the user to which the SDK must converge. // This includes the set of subscribables (SubscribedEntity instances) for whom a request // has been dispatched (whether or not this particular request ultimately succeeds) to // establish a live subscription. Entities are removed when the corresponding "cancel" // request is dispatched. // If the server includes a `ttl_in_s` attribute in the poke response, subscriptionTtlTimer is started for that duration // such that when it fires, it repokes the entire sync set (i.e., emulates a reconnect). Every reconnect resets the timer. // After the timer has fired, the first poke request includes a `reason: ttl` attribute in the body. /** * @constructor * Prepares a new Subscriptions manager object with zero subscribed or persisted subscriptions. * * @param {object} config may include a key 'backoffConfig', wherein any of the parameters * of Backoff.exponential (from npm 'backoff') are valid and will override the defaults. * * @param {Network} must be a viable running Sync Network object, useful for routing requests. */ function Subscriptions(services) { var _this = this; _classCallCheck__default['default'](this, Subscriptions); _defineProperty__default['default'](this, "isConnected", false); _defineProperty__default['default'](this, "maxBatchSize", 100); _defineProperty__default['default'](this, "subscriptionTtlTimer", null); _defineProperty__default['default'](this, "pendingPokeReason", null); this.services = services; this.subscriptions = new Map(); this.persisted = new Map(); this.latestPokeResponseArrivalTimestampByCorrelationId = new Map(); var defaultBackoffConfig = { randomisationFactor: 0.2, initialDelay: 100, maxDelay: 2 * 60 * 1000 }; this.backoff = operationRetrier.Backoff.exponential(Object.assign(defaultBackoffConfig, this.services.config.backoffConfig)); // This block is triggered by #_persist. Every request is executed in a series of (ideally 1) // backoff 'ready' event, at which point a new subscription set is calculated. this.backoff.on('ready', function () { var _this$getSubscription = _this.getSubscriptionUpdateBatch(), action = _this$getSubscription.action, subscriptionRequests = _this$getSubscription.subscriptions; if (action) { _this.applyNewSubscriptionUpdateBatch(action, subscriptionRequests); } else { _this.backoff.reset(); log$1$1.debug('All subscriptions resolved.'); } }); } _createClass__default['default'](Subscriptions, [{ key: "getSubscriptionUpdateBatch", value: function getSubscriptionUpdateBatch() { function subtract(these, those, action, limit) { var result = []; var _iterator = _createForOfIteratorHelper$3(these), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _step$value = _slicedToArray__default['default'](_step.value, 2), thisKey = _step$value[0], thisValue = _step$value[1]; var otherValue = those.get(thisKey); if (!otherValue && action !== thisValue.pendingAction && !thisValue.rejectedWithError) { result.push(thisValue); if (limit && result.length >= limit) { break; } } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return result; } var listToAdd = subtract(this.subscriptions, this.persisted, 'establish', this.maxBatchSize); if (listToAdd.length > 0) { return { action: 'establish', subscriptions: listToAdd }; } var listToRemove = subtract(this.persisted, this.subscriptions, 'cancel', this.maxBatchSize); if (listToRemove.length > 0) { return { action: 'cancel', subscriptions: listToRemove }; } return { action: null, subscriptions: null }; } }, { key: "persist", value: function persist() { this.backoff.backoff(); } }, { key: "applyNewSubscriptionUpdateBatch", value: function () { var _applyNewSubscriptionUpdateBatch = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(action, requests) { var _this2 = this; var correlationId, _iterator2, _step2, subscribed, reason, response, newMaxBatchSize, subscriptionTtlInS, isNumeric, isValidTtl, estimatedDeliveryInMs, _isNumeric, isValidTimeout, _iterator3, _step3, attemptedSubscription; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (this.isConnected) { _context.next = 4; break; } log$1$1.debug("Twilsock connection (required for subscription) not ready; waiting\u2026"); this.backoff.reset(); return _context.abrupt("return"); case 4: // Keeping in mind that events may begin flowing _before_ we receive the response requests = this.processLocalActions(action, requests); correlationId = new Date().getTime(); _iterator2 = _createForOfIteratorHelper$3(requests); try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { subscribed = _step2.value; this.recordActionAttemptOn(subscribed, action, correlationId); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } reason = this.pendingPokeReason; this.pendingPokeReason = null; // Send this batch to the service _context.prev = 10; _context.next = 13; return this.request(action, correlationId, reason, requests); case 13: response = _context.sent; newMaxBatchSize = response.body.max_batch_size; if (!isNaN(parseInt(newMaxBatchSize)) && isFinite(newMaxBatchSize) && newMaxBatchSize > 0) { this.maxBatchSize = newMaxBatchSize; } if (!this.subscriptionTtlTimer) { subscriptionTtlInS = response.body.ttl_in_s; isNumeric = !isNaN(parseFloat(subscriptionTtlInS)) && isFinite(subscriptionTtlInS); isValidTtl = isNumeric && subscriptionTtlInS > 0; if (isValidTtl) { this.subscriptionTtlTimer = setTimeout(function () { return _this2.onSubscriptionTtlElapsed(); }, subscriptionTtlInS * 1000); } } if (action === 'establish') { estimatedDeliveryInMs = response.body.estimated_delivery_in_ms; _isNumeric = !isNaN(parseFloat(estimatedDeliveryInMs)) && isFinite(estimatedDeliveryInMs); isValidTimeout = _isNumeric && estimatedDeliveryInMs > 0; if (isValidTimeout) { setTimeout(function () { return _this2.verifyPokeDelivery(correlationId, estimatedDeliveryInMs, requests); }, estimatedDeliveryInMs); } else { log$1$1.error("Invalid timeout: ".concat(estimatedDeliveryInMs)); } requests.filter(function (r) { return r.pendingCorrelationId === correlationId; }).forEach(function (r) { return r.setSubscriptionState('response_in_flight'); }); } this.backoff.reset(); _context.next = 26; break; case 21: _context.prev = 21; _context.t0 = _context["catch"](10); _iterator3 = _createForOfIteratorHelper$3(requests); try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { attemptedSubscription = _step3.value; this.recordActionFailureOn(attemptedSubscription, action); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } if (_context.t0 instanceof twilsock.TransportUnavailableError) { log$1$1.debug("Twilsock connection (required for subscription) not ready (c:".concat(correlationId, "); waiting\u2026")); this.backoff.reset(); } else { log$1$1.debug("Failed an attempt to ".concat(action, " subscriptions (c:").concat(correlationId, "); retrying"), _context.t0); this.persist(); } case 26: case "end": return _context.stop(); } } }, _callee, this, [[10, 21]]); })); function applyNewSubscriptionUpdateBatch(_x, _x2) { return _applyNewSubscriptionUpdateBatch.apply(this, arguments); } return applyNewSubscriptionUpdateBatch; }() }, { key: "verifyPokeDelivery", value: function verifyPokeDelivery(correlationId, estimatedDeliveryInMs, requests) { var _this3 = this; var lastReceived = this.latestPokeResponseArrivalTimestampByCorrelationId.get(correlationId); var silencePeriod = lastReceived ? new Date().getTime() - lastReceived : estimatedDeliveryInMs; if (silencePeriod >= estimatedDeliveryInMs) { // If we haven't received _any_ responses from that poke request for the duration of estimated_delivery_in_ms, poke again requests.filter(function (r) { return r.pendingCorrelationId === correlationId; }).forEach(function (r) { r.updatePending(null, null); r.retryCount++; _this3.persisted.delete(r.sid); }); this.persist(); this.latestPokeResponseArrivalTimestampByCorrelationId.delete(correlationId); } else { // Otherwise, the poke responses are probably in transit and we should wait for them var timeoutExtension = estimatedDeliveryInMs - silencePeriod; setTimeout(function () { return _this3.verifyPokeDelivery(correlationId, estimatedDeliveryInMs, requests); }, timeoutExtension); } } }, { key: "processLocalActions", value: function processLocalActions(action, requests) { if (action === 'cancel') { return requests.filter(function (request) { return !request.rejectedWithError; }); } return requests; } }, { key: "recordActionAttemptOn", value: function recordActionAttemptOn(attemptedSubscription, action, correlationId) { attemptedSubscription.setSubscriptionState('request_in_flight'); if (action === 'establish') { this.persisted.set(attemptedSubscription.sid, attemptedSubscription); attemptedSubscription.updatePending(action, correlationId); } else { // cancel var persistedSubscription = this.persisted.get(attemptedSubscription.sid); if (persistedSubscription) { persistedSubscription.updatePending(action, correlationId); } } } }, { key: "recordActionFailureOn", value: function recordActionFailureOn(attemptedSubscription, action) { attemptedSubscription.setSubscriptionState('none'); attemptedSubscription.updatePending(null, null); if (action === 'establish') { this.persisted.delete(attemptedSubscription.sid); } } }, { key: "request", value: function request(action, correlationId, reason, objects) { var requests = objects.map(function (object) { return { object_sid: object.sid, object_type: object.type, last_event_id: action === 'establish' ? object.lastEventId : undefined, index_name: action === 'establish' ? object.indexName : undefined, query_string: action === 'establish' ? object.queryString : undefined }; }); var retriedRequests = objects.filter(function (a) { return a.retryCount > 0; }).length; log$1$1.debug("Attempting '".concat(action, "' request (c:").concat(correlationId, "):"), requests); var requestBody = { event_protocol_version: 4, action: action, correlation_id: correlationId, retried_requests: retriedRequests, ttl_in_s: -1, requests: requests }; if (reason === 'ttl') { requestBody.reason = reason; } return this.services.network.post(this.services.config.subscriptionsUri, requestBody); } /** * Establishes intent to be subscribed to this entity. That subscription will be effected * asynchronously. * If subscription to the given sid already exists, it will be overwritten. * * @param {String} sid should be a well-formed SID, uniquely identifying a single instance of a Sync entity. * @param {Object} entity should represent the (singular) local representation of this entity. * Incoming events and modifications to the entity will be directed at the _update() function * of this provided reference. * * @return undefined */ }, { key: "add", value: function add(sid, entity) { log$1$1.debug("Establishing intent to subscribe to ".concat(sid)); var existingSubscription = this.subscriptions.get(sid); if (existingSubscription && entity && existingSubscription.lastEventId === entity.lastEventId) { // If last event id is the same as before - we're fine return; } this.persisted.delete(sid); this.subscriptions.set(sid, new SubscribedEntity(entity)); this.persist(); } /** * Establishes the caller's intent to no longer be subscribed to this entity. Following this * call, no further events shall be routed to the local representation of the entity, even * though a server-side subscription may take more time to actually terminate. * * @param {string} sid should be any well-formed SID, uniquely identifying a Sync entity. * This call only has meaningful effect if that entity is subscribed at the * time of call. Otherwise does nothing. * * @return undefined */ }, { key: "remove", value: function remove(sid) { log$1$1.debug("Establishing intent to unsubscribe from ".concat(sid)); var removed = this.subscriptions.delete(sid); if (removed) { this.persist(); } } /** * The point of ingestion for remote incoming messages (e.g. new data was written to a map * to which we are subscribed). * * @param {object} message is the full, unaltered body of the incoming notification. * * @return undefined */ }, { key: "acceptMessage", value: function acceptMessage(message, isStrictlyOrdered) { log$1$1.trace('Subscriptions received', message); var eventType = message.event_type; var events = typeof message.events !== 'undefined' ? message.events : [message.event]; var correlationId = message.correlation_id; if (correlationId) { this.latestPokeResponseArrivalTimestampByCorrelationId.set(correlationId, new Date().getTime()); } var _iterator4 = _createForOfIteratorHelper$3(events), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var event = _step4.value; var matchedEventType = void 0; switch (message.event_type) { case 'subscription_established': this.applySubscriptionEstablishedMessage(event, correlationId); break; case 'subscription_canceled': this.applySubscriptionCancelledMessage(event, correlationId); break; case 'subscription_failed': this.applySubscriptionFailedMessage(event, correlationId); break; case (matchedEventType = eventType.match(/^(?:map|list|document|stream|live_query)_/) || {}).input: { var typedSid = void 0; switch (matchedEventType[0]) { case 'map_': typedSid = event.map_sid; break; case 'list_': typedSid = event.list_sid; break; case 'document_': typedSid = event.document_sid; break; case 'stream_': typedSid = event.stream_sid; break; case 'live_query_': typedSid = event.query_id; // hack to mark replay events for LiveQuery as strictly ordered, due to lack of special type of notification for them // (normally only replay events would have `twilio.sync.event` type, but LiveQuery non-replay events were also assigned // to this type in legacy clients, which we have to support now; hence a hack) isStrictlyOrdered = false; // explicitly override it due to code in router.ts does not know about LiveQueries if (message.strictly_ordered === true) { isStrictlyOrdered = true; } break; default: typedSid = undefined; } this.applyEventToSubscribedEntity(typedSid, event, eventType, isStrictlyOrdered); break; } default: log$1$1.debug("Dropping unknown message type ".concat(eventType)); break; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } }, { key: "applySubscriptionEstablishedMessage", value: function applySubscriptionEstablishedMessage(message, correlationId) { var sid = message.object_sid; var subscriptionIntent = this.persisted.get(message.object_sid); if (subscriptionIntent && subscriptionIntent.pendingCorrelationId === correlationId) { if (message.replay_status === 'interrupted') { log$1$1.debug("Event Replay for subscription to ".concat(sid, " (c:").concat(correlationId, ") interrupted; continuing eagerly.")); subscriptionIntent.updatePending(null, null); this.persisted.delete(subscriptionIntent.sid); this.backoff.reset(); } else if (message.replay_status === 'completed') { log$1$1.debug("Event Replay for subscription to ".concat(sid, " (c:").concat(correlationId, ") completed. Subscription is ready.")); subscriptionIntent.complete(message.last_event_id); this.persisted.set(message.object_sid, subscriptionIntent); subscriptionIntent.setSubscriptionState('established'); this.backoff.reset(); } } else { log$1$1.debug("Late message for ".concat(message.object_sid, " (c:").concat(correlationId, ") dropped.")); } this.persist(); } }, { key: "applySubscriptionCancelledMessage", value: function applySubscriptionCancelledMessage(message, correlationId) { var persistedSubscription = this.persisted.get(message.object_sid); if (persistedSubscription && persistedSubscription.pendingCorrelationId === correlationId) { persistedSubscription.updatePending(null, null); persistedSubscription.setSubscriptionState('none'); this.persisted.delete(message.object_sid); } else { log$1$1.debug("Late message for ".concat(message.object_sid, " (c:").concat(correlationId, ") dropped.")); } this.persist(); } }, { key: "applySubscriptionFailedMessage", value: function applySubscriptionFailedMessage(message, correlationId) { var sid = message.object_sid; var subscriptionIntent = this.subscriptions.get(sid); var subscription = this.persisted.get(sid); if (subscriptionIntent && subscription) { if (subscription.pendingCorrelationId === correlationId) { log$1$1.error("Failed to subscribe on ".concat(subscription.sid), message.error); subscription.markAsFailed(message); subscription.setSubscriptionState('none'); } } else if (!subscriptionIntent && subscription) { this.persisted.delete(sid); subscription.setSubscriptionState('none'); } this.persist(); } }, { key: "applyEventToSubscribedEntity", value: function applyEventToSubscribedEntity(sid, event, eventType, isStrictlyOrdered) { var _this4 = this; if (!sid) { return; } // Looking for subscription descriptor to check if poke has been completed isStrictlyOrdered = isStrictlyOrdered || function () { var subscription = _this4.persisted.get(sid); return subscription && subscription.isEstablished; }(); // Still searching for subscriptionIntents. User could remove subscription already var subscriptionIntent = this.subscriptions.get(sid); if (subscriptionIntent) { event.type = eventType; subscriptionIntent.update(event, isStrictlyOrdered); } else { log$1$1.debug("Message dropped for SID '".concat(sid, "', for which there is no subscription.")); } } }, { key: "onConnectionStateChanged", value: function onConnectionStateChanged(isConnected) { this.isConnected = isConnected; if (isConnected) { this.poke('reconnect'); } } }, { key: "onSubscriptionTtlElapsed", value: function onSubscriptionTtlElapsed() { if (this.isConnected) { this.poke('ttl'); } } /** * Prompts a playback of any missed changes made to any subscribed object. This method * should be invoked whenever the connectivity layer has experienced cross-cutting * delivery failures that would affect the entire local sync set. Any tangible result * of this operation will result in calls to the _update() function of subscribed * Sync entities. */ }, { key: "poke", value: function poke(reason) { log$1$1.debug("Triggering event replay for all subscriptions, reason=".concat(reason)); this.pendingPokeReason = reason; if (this.subscriptionTtlTimer) { clearTimeout(this.subscriptionTtlTimer); this.subscriptionTtlTimer = null; } var failedSubscriptions = []; var _iterator5 = _createForOfIteratorHelper$3(this.persisted.values()), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var _it = _step5.value; _it.reset(); if (_it.rejectedWithError) { failedSubscriptions.push(_it); } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } this.persisted.clear(); for (var _i = 0, _failedSubscriptions = failedSubscriptions; _i < _failedSubscriptions.length; _i++) { var it = _failedSubscriptions[_i]; this.persisted.set(it.sid, it); } this.persist(); } /** * Stops all communication, clears any subscription intent, and returns. */ }, { key: "shutdown", value: function shutdown() { this.backoff.reset(); this.subscriptions.clear(); } }]); return Subscriptions; }(); var MINIMUM_RETRY_DELAY = 4000; var MAXIMUM_RETRY_DELAY = 60000; var MAXIMUM_ATTEMPTS_TIME = 90000; var RETRY_DELAY_RANDOMNESS = 0.2; function messageFromErrorBody(transportError) { if (transportError.body) { if (transportError.body.message) { return transportError.body.message; } } switch (transportError.status) { case 429: return 'Throttled by server'; case 404: return 'Not found from server'; default: return 'Error from server'; } } function codeFromErrorBody(trasportError) { if (trasportError.body) { return trasportError.body.code; } return 0; } function mapTransportError(transportError) { if (transportError.status === 409) { return new SyncNetworkError(messageFromErrorBody(transportError), transportError.status, codeFromErrorBody(transportError), transportError.body); } else if (transportError.status) { return new SyncError(messageFromErrorBody(transportError), transportError.status, codeFromErrorBody(transportError)); } else if (transportError instanceof twilsock.TransportUnavailableError) { return transportError; } else { return new SyncError(transportError.message, 0, 0); } } /** * @classdesc Incapsulates network operations to make it possible to add some optimization/caching strategies */ var NetworkService = /*#__PURE__*/function () { function NetworkService(clientInfo, config, transport) { _classCallCheck__default['default'](this, NetworkService); this.clientInfo = clientInfo; this.config = config; this.transport = transport; } _createClass__default['default'](NetworkService, [{ key: "createHeaders", value: function createHeaders() { return { 'Content-Type': 'application/json', 'Twilio-Sync-Client-Info': JSON.stringify(this.clientInfo), 'Twilio-Request-Id': 'RQ' + uuid__namespace.v4().replace(/-/g, '') }; } }, { key: "backoffConfig", value: function backoffConfig() { return Object.assign({ min: MINIMUM_RETRY_DELAY, max: MAXIMUM_RETRY_DELAY, maxAttemptsTime: MAXIMUM_ATTEMPTS_TIME, randomness: RETRY_DELAY_RANDOMNESS }, this.config.backoffConfig); } }, { key: "executeWithRetry", value: function executeWithRetry(request) { var _this = this; var retryWhenThrottled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; return new Promise(function (resolve, reject) { var codesToRetryOn = [502, 503, 504]; if (retryWhenThrottled) { codesToRetryOn.push(429); } var retrier = new operationRetrier.Retrier(_this.backoffConfig()); retrier.on('attempt', function () { request().then(function (result) { return retrier.succeeded(result); }).catch(function (err) { if (codesToRetryOn.includes(err.status)) { var delayOverride = parseInt(err.headers ? err.headers['Retry-After'] : null); retrier.failed(mapTransportError(err), isNaN(delayOverride) ? null : delayOverride * 1000); } else if (err.message === 'Twilsock disconnected') { // Ugly hack. We must make a proper exceptions for twilsock retrier.failed(mapTransportError(err)); } else { // Fatal error retrier.removeAllListeners(); retrier.cancel(); reject(mapTransportError(err)); } }); }); retrier.on('succeeded', function (result) { resolve(result); }); retrier.on('cancelled', function (err) { return reject(mapTransportError(err)); }); retrier.on('failed', function (err) { return reject(mapTransportError(err)); }); retrier.start(); }); } /** * Make a GET request by given URI * @Returns Promise Result of successful get request */ }, { key: "get", value: function get(uri) { var _this2 = this; var headers = this.createHeaders(); log$1$1.debug('GET', uri, 'ID:', headers['Twilio-Request-Id']); return this.executeWithRetry(function () { return _this2.transport.get(uri, headers, _this2.config.productId); }, true); } }, { key: "post", value: function post(uri, body, revision) { var _this3 = this; var retryWhenThrottled = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var headers = this.createHeaders(); if (typeof revision !== 'undefined' && revision !== null) { headers['If-Match'] = revision; } log$1$1.debug('POST', uri, 'ID:', headers['Twilio-Request-Id']); return this.executeWithRetry(function () { return _this3.transport.post(uri, headers, body, _this3.config.productId); }, retryWhenThrottled); } }, { key: "put", value: function put(uri, body, revision) { var _this4 = this; var headers = this.createHeaders(); if (typeof revision !== 'undefined' && revision !== null) { headers['If-Match'] = revision; } log$1$1.debug('PUT', uri, 'ID:', headers['Twilio-Request-Id']); return this.executeWithRetry(function () { return _this4.transport.put(uri, headers, body, _this4.config.productId); }, false); } }, { key: "delete", value: function _delete(uri) { var _this5 = this; var headers = this.createHeaders(); log$1$1.debug('DELETE', uri, 'ID:', headers['Twilio-Request-Id']); return this.executeWithRetry(function () { return _this5.transport.delete(uri, headers, _this5.config.productId); }, false); } }]); return NetworkService; }(); var SessionStorage = /*#__PURE__*/function () { function SessionStorage(config, storage) { _classCallCheck__default['default'](this, SessionStorage); this.config = config; this.storageId = null; try { this.storage = storage || sessionStorage; } catch (e) {} } _createClass__default['default'](SessionStorage, [{ key: "storageKey", value: function storageKey(type, key) { return "".concat(this.storageId, "::").concat(type, "::").concat(key); } }, { key: "isReady", get: function get() { return this.config.sessionStorageEnabled && !!this.storageId; } }, { key: "updateStorageId", value: function updateStorageId(storageId) { this.storageId = storageId; } }, { key: "store", value: function store(type, id, value) { if (!this.isReady) { return null; } return this._store(this.storageKey(type, id), value); } }, { key: "read", value: function read(type, id) { if (!this.isReady) { return null; } return this._read(this.storageKey(type, id)); } }, { key: "remove", value: function remove(type, sid, uniqueName) { if (!this.isReady) { return null; } try { this.storage.removeItem(this.storageKey(type, sid)); if (uniqueName) { this.storage.removeItem(this.storageKey(type, uniqueName)); } } catch (e) {} } }, { key: "update", value: function update(type, sid, uniqueName, patch) { if (!this.isReady) { return null; } // Currently cache may have root stored twice - by sid and by uniqueName // Maybe need to create some index if needed this._apply(this.storageKey(type, sid), patch); if (uniqueName) { this._apply(this.storageKey(type, uniqueName), patch); } } }, { key: "_store", value: function _store(key, value) { try { this.storage.setItem(key, JSON.stringify(value)); } catch (e) {} } }, { key: "_read", value: function _read(key) { try { var storedData = this.storage.getItem(key); if (storedData) { return JSON.parse(storedData); } } catch (e) {} return null; } }, { key: "_apply", value: function _apply(key, patch) { var value = this._read(key); if (!value) { return false; } this._store(key, Object.assign(value, patch)); } }]); return SessionStorage; }(); function _createForOfIteratorHelper$2$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$2$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2$1(o, minLen); } function _arrayLikeToArray$2$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var SyncEntity = /*#__PURE__*/function () { function SyncEntity(services, removalHandler) { _classCallCheck__default['default'](this, SyncEntity); this.services = services; this.removalHandler = removalHandler; this.subscriptionState = 'none'; this._attachedListeners = new Map(); } _createClass__default['default'](SyncEntity, [{ key: "_advanceLastEventId", value: function _advanceLastEventId(eventId, revision) {} }, { key: "reportFailure", value: function reportFailure(err) { if (err.status === 404) { // assume that 404 means that entity has been removed while we were away this.onRemoved(false); } else { this.broadcastEventToListeners('failure', err); } } /** * Subscribe to changes of data entity * @private */ }, { key: "_subscribe", value: function _subscribe() { this.services.router._subscribe(this.sid, this); } /** * Unsubscribe from changes of current data entity * @private */ }, { key: "_unsubscribe", value: function _unsubscribe() { this.services.router._unsubscribe(this.sid); } }, { key: "_setSubscriptionState", value: function _setSubscriptionState(newState) { this.subscriptionState = newState; this.broadcastEventToListeners('_subscriptionStateChanged', newState); } /** * @public */ }, { key: "close", value: function close() { this._unsubscribe(); if (this.removalHandler != null) { this.removalHandler(this.type, this.sid, this.uniqueName); } } }, { key: "attach", value: function attach(closeable) { var uuid = closeable.listenerUuid; var existingRecord = this._attachedListeners.get(uuid); if (existingRecord) { return; } if (!this._attachedListeners.size) { // the first one to arrive this._subscribe(); } this._attachedListeners.set(uuid, closeable); } }, { key: "detach", value: function detach(listenerUuid) { this._attachedListeners.delete(listenerUuid); if (!this._attachedListeners.size) { // last one out, turn off lights, shut the door this.close(); // invokes unsubscribe and removal handler } } }, { key: "broadcastEventToListeners", value: function broadcastEventToListeners(eventName, args) { var _iterator = _createForOfIteratorHelper$2$1(this._attachedListeners.values()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var listener = _step.value; listener.emit(eventName, args); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } }]); return SyncEntity; }(); var MergingQueue = /*#__PURE__*/function () { function MergingQueue(inputMergingFunction) { _classCallCheck__default['default'](this, MergingQueue); _defineProperty__default['default'](this, "queuedRequests", []); _defineProperty__default['default'](this, "isRequestInFlight", false); this.inputMergingFunction = inputMergingFunction; } _createClass__default['default'](MergingQueue, [{ key: "add", value: function add(input, requestFunction) { var _this = this; var promise = new Promise(function (resolve, reject) { return _this.queuedRequests.push({ input: input, requestFunction: requestFunction, resolve: resolve, reject: reject }); }); this.wakeupQueue(); return promise; } }, { key: "squashAndAdd", value: function squashAndAdd(input, requestFunction) { var queueToSquash = this.queuedRequests; this.queuedRequests = []; var reducedInput; if (queueToSquash.length > 0) { reducedInput = queueToSquash.map(function (r) { return r.input; }).reduce(this.inputMergingFunction); reducedInput = this.inputMergingFunction(reducedInput, input); } else { reducedInput = input; } var promise = this.add(reducedInput, requestFunction); queueToSquash.forEach(function (request) { return promise.then(request.resolve, request.reject); }); return promise; } }, { key: "isEmpty", value: function isEmpty() { return this.queuedRequests.length === 0 && !this.isRequestInFlight; } }, { key: "wakeupQueue", value: function wakeupQueue() { var _this2 = this; if (this.queuedRequests.length === 0 || this.isRequestInFlight) { return; } else { var requestToExecute = this.queuedRequests.shift(); this.isRequestInFlight = true; requestToExecute.requestFunction(requestToExecute.input).then(requestToExecute.resolve, requestToExecute.reject).then(function (__) { _this2.isRequestInFlight = false; _this2.wakeupQueue(); }); } } }]); return MergingQueue; }(); var NamespacedMergingQueue = /*#__PURE__*/function () { function NamespacedMergingQueue(inputReducer) { _classCallCheck__default['default'](this, NamespacedMergingQueue); _defineProperty__default['default'](this, "queueByNamespaceKey", new Map()); this.inputReducer = inputReducer; } _createClass__default['default'](NamespacedMergingQueue, [{ key: "add", value: function () { var _add = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(namespaceKey, input, requestFunction) { return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", this.invokeQueueMethod(namespaceKey, function (queue) { return queue.add(input, requestFunction); })); case 1: case "end": return _context.stop(); } } }, _callee, this); })); function add(_x, _x2, _x3) { return _add.apply(this, arguments); } return add; }() }, { key: "squashAndAdd", value: function () { var _squashAndAdd = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(namespaceKey, input, requestFunction) { return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: return _context2.abrupt("return", this.invokeQueueMethod(namespaceKey, function (queue) { return queue.squashAndAdd(input, requestFunction); })); case 1: case "end": return _context2.stop(); } } }, _callee2, this); })); function squashAndAdd(_x4, _x5, _x6) { return _squashAndAdd.apply(this, arguments); } return squashAndAdd; }() }, { key: "invokeQueueMethod", value: function () { var _invokeQueueMethod = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(namespaceKey, queueMethodInvoker) { var queue, result; return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!this.queueByNamespaceKey.has(namespaceKey)) { this.queueByNamespaceKey.set(namespaceKey, new MergingQueue(this.inputReducer)); } queue = this.queueByNamespaceKey.get(namespaceKey); result = queueMethodInvoker(queue); if (this.queueByNamespaceKey.get(namespaceKey).isEmpty()) { this.queueByNamespaceKey.delete(namespaceKey); } return _context3.abrupt("return", result); case 5: case "end": return _context3.stop(); } } }, _callee3, this); })); function invokeQueueMethod(_x7, _x8) { return _invokeQueueMethod.apply(this, arguments); } return invokeQueueMethod; }() }]); return NamespacedMergingQueue; }(); function _createSuper$6$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$6$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Closeable = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](Closeable, _EventEmitter); var _super = _createSuper$6$1(Closeable); function Closeable() { var _this; _classCallCheck__default['default'](this, Closeable); _this = _super.call(this); _this.closed = false; _this.uuid = uuid.v4(); return _this; } _createClass__default['default'](Closeable, [{ key: "listenerUuid", get: function get() { return this.uuid; } }, { key: "close", value: function close() { this.removeAllListeners(); this.closed = true; } }, { key: "ensureNotClosed", value: function ensureNotClosed() { if (this.closed) { throw new Error('Invalid operation on closed object'); } } }]); return Closeable; }(EventEmitter); function _createSuper$5$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$5$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var SyncDocumentImpl = /*#__PURE__*/function (_SyncEntity) { _inherits__default['default'](SyncDocumentImpl, _SyncEntity); var _super = _createSuper$5$1(SyncDocumentImpl); /** * @internal */ function SyncDocumentImpl(services, descriptor, removalHandler) { var _this; _classCallCheck__default['default'](this, SyncDocumentImpl); _this = _super.call(this, services, removalHandler); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "isDeleted", false); var updateRequestReducer = function updateRequestReducer(acc, input) { return typeof input.ttl === 'number' ? { ttl: input.ttl } : acc; }; _this.updateMergingQueue = new MergingQueue(updateRequestReducer); _this.descriptor = descriptor; _this.descriptor.data = _this.descriptor.data || {}; _this.descriptor.date_updated = new Date(_this.descriptor.date_updated); return _this; } // private props _createClass__default['default'](SyncDocumentImpl, [{ key: "uri", get: function get() { return this.descriptor.url; } }, { key: "revision", get: function get() { return this.descriptor.revision; } }, { key: "lastEventId", get: function get() { return this.descriptor.last_event_id; } }, { key: "dateExpires", get: function get() { return this.descriptor.date_expires; } }, { key: "type", get: function get() { return 'document'; } // below properties are specific to Insights only }, { key: "indexName", get: function get() { return undefined; } }, { key: "queryString", get: function get() { return undefined; } // public props, documented along with class description }, { key: "sid", get: function get() { return this.descriptor.sid; } }, { key: "data", get: function get() { return this.descriptor.data; } }, { key: "dateUpdated", get: function get() { return this.descriptor.date_updated; } }, { key: "uniqueName", get: function get() { return this.descriptor.unique_name || null; } /** * Update data entity with new data * @private */ }, { key: "_update", value: function _update(update) { update.date_created = new Date(update.date_created); switch (update.type) { case 'document_updated': if (update.id <= this.lastEventId) { log$1$1.trace('Document update skipped, current:', this.lastEventId, ', remote:', update.id); break; } var previousData = this.descriptor.data !== undefined ? deepClone(this.descriptor.data) : null; this.descriptor.last_event_id = update.id; this.descriptor.revision = update.document_revision; this.descriptor.date_updated = update.date_created; this.descriptor.data = update.document_data; this.broadcastEventToListeners('updated', { data: update.document_data, isLocal: false, previousData: previousData }); this.services.storage.update(this.type, this.sid, this.uniqueName, { last_event_id: update.id, revision: update.document_revision, date_updated: update.date_created, data: update.document_data }); break; case 'document_removed': this.onRemoved(false); break; } } }, { key: "set", value: function () { var _set = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(value, metadataUpdates) { var _this2 = this; var input; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: input = metadataUpdates || {}; return _context.abrupt("return", this.updateMergingQueue.squashAndAdd(input, function (input) { return _this2._setUnconditionally(value, input.ttl); })); case 2: case "end": return _context.stop(); } } }, _callee, this); })); function set(_x, _x2) { return _set.apply(this, arguments); } return set; }() }, { key: "mutate", value: function () { var _mutate = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(mutator, metadataUpdates) { var _this3 = this; var input; return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: input = metadataUpdates || {}; return _context2.abrupt("return", this.updateMergingQueue.add(input, function (input) { return _this3._setWithIfMatch(mutator, input.ttl); })); case 2: case "end": return _context2.stop(); } } }, _callee2, this); })); function mutate(_x3, _x4) { return _mutate.apply(this, arguments); } return mutate; }() }, { key: "update", value: function () { var _update2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(obj, metadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: return _context3.abrupt("return", this.mutate(function (remote) { return Object.assign(remote, obj); }, metadataUpdates)); case 1: case "end": return _context3.stop(); } } }, _callee3, this); })); function update(_x5, _x6) { return _update2.apply(this, arguments); } return update; }() }, { key: "setTtl", value: function () { var _setTtl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4(ttl) { var response; return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._postUpdateToServer({ ttl: ttl }); case 2: response = _context4.sent; this.descriptor.date_expires = response.date_expires; case 4: case "end": return _context4.stop(); } } }, _callee4, this); })); function setTtl(_x7) { return _setTtl.apply(this, arguments); } return setTtl; }() /** * @private */ }, { key: "_setUnconditionally", value: function () { var _setUnconditionally2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(value, ttl) { var result; return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this._postUpdateToServer({ data: value, revision: undefined, ttl: ttl }); case 2: result = _context5.sent; this._handleSuccessfulUpdateResult(result); return _context5.abrupt("return", this.descriptor.data); case 5: case "end": return _context5.stop(); } } }, _callee5, this); })); function _setUnconditionally(_x8, _x9) { return _setUnconditionally2.apply(this, arguments); } return _setUnconditionally; }() /** * @private */ }, { key: "_setWithIfMatch", value: function () { var _setWithIfMatch2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(mutatorFunction, ttl) { var data, revision, result; return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: data = mutatorFunction(deepClone(this.descriptor.data)); if (!data) { _context6.next = 22; break; } revision = this.revision; _context6.prev = 3; _context6.next = 6; return this._postUpdateToServer({ data: data, revision: revision, ttl: ttl }); case 6: result = _context6.sent; this._handleSuccessfulUpdateResult(result); return _context6.abrupt("return", this.descriptor.data); case 11: _context6.prev = 11; _context6.t0 = _context6["catch"](3); if (!(_context6.t0.status === 412)) { _context6.next = 19; break; } _context6.next = 16; return this._softSync(); case 16: return _context6.abrupt("return", this._setWithIfMatch(mutatorFunction)); case 19: throw _context6.t0; case 20: _context6.next = 23; break; case 22: return _context6.abrupt("return", this.descriptor.data); case 23: case "end": return _context6.stop(); } } }, _callee6, this, [[3, 11]]); })); function _setWithIfMatch(_x10, _x11) { return _setWithIfMatch2.apply(this, arguments); } return _setWithIfMatch; }() /** * @private */ }, { key: "_handleSuccessfulUpdateResult", value: function _handleSuccessfulUpdateResult(result) { // Ignore returned value if we already got a newer one if (result.last_event_id <= this.descriptor.last_event_id) { return; } var previousData = this.descriptor.data !== undefined ? deepClone(this.descriptor.data) : null; this.descriptor.revision = result.revision; this.descriptor.data = result.data; this.descriptor.last_event_id = result.last_event_id; this.descriptor.date_expires = result.date_expires; this.descriptor.date_updated = new Date(result.date_updated); this.services.storage.update(this.type, this.sid, this.uniqueName, { last_event_id: result.last_event_id, revision: result.revision, date_updated: result.date_updated, data: result.data }); this.broadcastEventToListeners('updated', { data: this.descriptor.data, isLocal: true, previousData: previousData }); } /** * @private */ }, { key: "_postUpdateToServer", value: function () { var _postUpdateToServer2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee7(request) { var requestBody, ifMatch, response; return _regeneratorRuntime__default['default'].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: if (this.isDeleted) { _context7.next = 17; break; } requestBody = { data: request.data }; if (request.ttl !== undefined) { requestBody.ttl = request.ttl; } ifMatch = request.revision; _context7.prev = 4; _context7.next = 7; return this.services.network.post(this.uri, requestBody, ifMatch); case 7: response = _context7.sent; return _context7.abrupt("return", { revision: response.body.revision, data: request.data, last_event_id: response.body.last_event_id, date_updated: response.body.date_updated, date_expires: response.body.date_expires }); case 11: _context7.prev = 11; _context7.t0 = _context7["catch"](4); if (_context7.t0.status === 404) { this.onRemoved(false); } throw _context7.t0; case 15: _context7.next = 18; break; case 17: return _context7.abrupt("return", Promise.reject(new SyncError('The Document has been removed', 404, 54100))); case 18: case "end": return _context7.stop(); } } }, _callee7, this, [[4, 11]]); })); function _postUpdateToServer(_x12) { return _postUpdateToServer2.apply(this, arguments); } return _postUpdateToServer; }() /** * Get new data from server * @private */ }, { key: "_softSync", value: function () { var _softSync2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee8() { var _this4 = this; return _regeneratorRuntime__default['default'].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: return _context8.abrupt("return", this.services.network.get(this.uri).then(function (response) { var event = { type: 'document_updated', id: response.body.last_event_id, document_revision: response.body.revision, document_data: response.body.data, date_created: response.body.date_updated }; _this4._update(event); return _this4; }).catch(function (err) { if (err.status === 404) { _this4.onRemoved(false); } else { log$1$1.error("Can't get updates for ".concat(_this4.sid, ":"), err); } })); case 1: case "end": return _context8.stop(); } } }, _callee8, this); })); function _softSync() { return _softSync2.apply(this, arguments); } return _softSync; }() }, { key: "onRemoved", value: function onRemoved(locally) { if (this.isDeleted) { return; } var previousData = this.descriptor.data !== undefined ? deepClone(this.descriptor.data) : null; this.isDeleted = true; this._unsubscribe(); this.removalHandler(this.type, this.sid, this.uniqueName); this.broadcastEventToListeners('removed', { isLocal: locally, previousData: previousData }); } }, { key: "removeDocument", value: function () { var _removeDocument = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee9() { return _regeneratorRuntime__default['default'].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: if (this.isDeleted) { _context9.next = 6; break; } _context9.next = 3; return this.services.network.delete(this.uri); case 3: this.onRemoved(true); _context9.next = 7; break; case 6: return _context9.abrupt("return", Promise.reject(new SyncError('The Document has been removed', 404, 54100))); case 7: case "end": return _context9.stop(); } } }, _callee9, this); })); function removeDocument() { return _removeDocument.apply(this, arguments); } return removeDocument; }() }], [{ key: "type", get: function get() { return 'document'; } }]); return SyncDocumentImpl; }(SyncEntity); /** * Represents a Sync document, the contents of which is a single JSON object. * Use the {@link SyncClient.document} method to obtain a reference to a Sync document. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ var SyncDocument = /*#__PURE__*/function (_Closeable) { _inherits__default['default'](SyncDocument, _Closeable); var _super2 = _createSuper$5$1(SyncDocument); /** * @internal */ function SyncDocument(syncDocumentImpl) { var _this5; _classCallCheck__default['default'](this, SyncDocument); _this5 = _super2.call(this); _this5.syncDocumentImpl = syncDocumentImpl; _this5.syncDocumentImpl.attach(_assertThisInitialized__default['default'](_this5)); return _this5; } /** * Fired when the document is removed, regardless of whether the remover was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has following properties: * * boolean `isLocal` - is true if document was removed by a local actor, false otherwise * * object `previousData` - contains a snapshot of the document data before removal * @example * ```typescript * document.on('removed', (args) => { * console.log(`Document ${document.sid} was removed`); * console.log('args.isLocal:', args.isLocal); * console.log('args.previousData:', args.previousData); * }); * ``` * @event */ _createClass__default['default'](SyncDocument, [{ key: "uri", get: // private props function get() { return this.syncDocumentImpl.uri; } }, { key: "revision", get: function get() { return this.syncDocumentImpl.revision; } }, { key: "lastEventId", get: function get() { return this.syncDocumentImpl.lastEventId; } }, { key: "dateExpires", get: function get() { return this.syncDocumentImpl.dateExpires; } }, { key: "type", get: function get() { return SyncDocumentImpl.type; } /** * The immutable identifier of this document, assigned by the system. */ }, { key: "sid", get: function get() { return this.syncDocumentImpl.sid; } /** * The contents of this document. */ }, { key: "data", get: function get() { return this.syncDocumentImpl.data; } /** * Date when the document was last updated. */ }, { key: "dateUpdated", get: function get() { return this.syncDocumentImpl.dateUpdated; } /** * An optional immutable identifier that may be assigned by the programmer * to this document during creation. Globally unique among other documents. */ }, { key: "uniqueName", get: function get() { return this.syncDocumentImpl.uniqueName; } }, { key: "set", value: /** * Assign new contents to this document. The current data will be overwritten. * @param data The new contents to assign. * @param metadataUpdates New document metadata. * @return A promise resolving to the new data of the document. * @example * ```typescript * // Say, the Document data is `{ name: 'John Smith', age: 34 }` * document.set({ name: 'Barbara Oaks' }, { ttl: 86400 }) * .then((newValue) => { * // Now the Document data is `{ name: 'Barbara Oaks' }` * console.log('Document set() successful, new data:', newValue); * }) * .catch((error) => { * console.error('Document set() failed', error); * }); * ``` */ function () { var _set2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee10(data, metadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: this.ensureNotClosed(); return _context10.abrupt("return", this.syncDocumentImpl.set(data, metadataUpdates)); case 2: case "end": return _context10.stop(); } } }, _callee10, this); })); function set(_x13, _x14) { return _set2.apply(this, arguments); } return set; }() /** * Schedules a modification to this document that will apply a mutation function. * @param mutator A function that outputs new data based on the existing data. * May be called multiple times, particularly if this document is modified concurrently by remote code. * If the mutation ultimately succeeds, the document will have made the particular transition described * by this function. * @param metadataUpdates New document metadata. * @return Resolves with the most recent Document state, whether the output of a * successful mutation or a state that prompted graceful cancellation (mutator returned `null`). * @example * ```typescript * const mutatorFunction = (currentValue) => { * currentValue.viewCount = (currentValue.viewCount ?? 0) + 1; * return currentValue; * }; * document.mutate(mutatorFunction, { ttl: 86400 })) * .then((newValue) => { * console.log('Document mutate() successful, new data:', newValue); * }) * .catch((error) => { * console.error('Document mutate() failed', error); * }); * ``` */ }, { key: "mutate", value: function () { var _mutate2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee11(mutator, metadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: this.ensureNotClosed(); return _context11.abrupt("return", this.syncDocumentImpl.mutate(mutator, metadataUpdates)); case 2: case "end": return _context11.stop(); } } }, _callee11, this); })); function mutate(_x15, _x16) { return _mutate2.apply(this, arguments); } return mutate; }() /** * Modify a document by appending new fields (or by overwriting existing ones) with the values from the provided Object. * This is equivalent to: * ```typescript * document.mutate((currentValue) => Object.assign(currentValue, obj)); * ``` * @param obj Specifies the particular (top-level) attributes that will receive new values. * @param metadataUpdates New document metadata. * @return A promise resolving to the new data of the document. * @example * ```typescript * // Say, the Document data is `{ name: 'John Smith' }` * document.update({ age: 34 }, { ttl: 86400 }) * .then((newValue) => { * // Now the Document data is `{ name: 'John Smith', age: 34 }` * console.log('Document update() successful, new data:', newValue); * }) * .catch((error) => { * console.error('Document update() failed', error); * }); * ``` */ }, { key: "update", value: function () { var _update3 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee12(obj, metadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: this.ensureNotClosed(); return _context12.abrupt("return", this.syncDocumentImpl.update(obj, metadataUpdates)); case 2: case "end": return _context12.stop(); } } }, _callee12, this); })); function update(_x17, _x18) { return _update3.apply(this, arguments); } return update; }() /** * Update the time-to-live of the document. * @param ttl Specifies the time-to-live in seconds after which the document is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * document.setTtl(3600) * .then(() => { * console.log('Document setTtl() successful'); * }) * .catch((error) => { * console.error('Document setTtl() failed', error); * }); * ``` */ }, { key: "setTtl", value: function () { var _setTtl2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee13(ttl) { return _regeneratorRuntime__default['default'].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: this.ensureNotClosed(); return _context13.abrupt("return", this.syncDocumentImpl.setTtl(ttl)); case 2: case "end": return _context13.stop(); } } }, _callee13, this); })); function setTtl(_x19) { return _setTtl2.apply(this, arguments); } return setTtl; }() /** * Delete a document. * @return A promise which resolves if (and only if) the document is ultimately deleted. * @example * ```typescript * document.removeDocument() * .then(() => { * console.log('Document removeDocument() successful'); * }) * .catch((error) => { * console.error('Document removeDocument() failed', error); * }); * ``` */ }, { key: "removeDocument", value: function () { var _removeDocument2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee14() { return _regeneratorRuntime__default['default'].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: this.ensureNotClosed(); return _context14.abrupt("return", this.syncDocumentImpl.removeDocument()); case 2: case "end": return _context14.stop(); } } }, _callee14, this); })); function removeDocument() { return _removeDocument2.apply(this, arguments); } return removeDocument; }() /** * Conclude work with the document instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this document will continue operating and receiving events normally. * @example * ```typescript * document.close(); * ``` */ }, { key: "close", value: function close() { _get__default['default'](_getPrototypeOf__default['default'](SyncDocument.prototype), "close", this).call(this); this.syncDocumentImpl.detach(this.listenerUuid); } }], [{ key: "type", get: function get() { return SyncDocumentImpl.type; } }]); return SyncDocument; }(Closeable); _defineProperty__default['default'](SyncDocument, "removed", 'removed'); _defineProperty__default['default'](SyncDocument, "updated", 'updated'); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.pureObject, ['undefined', declarativeTypeValidator.objectSchema('document metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise)], SyncDocument.prototype, "set", null); __decorate([declarativeTypeValidator.validateTypesAsync('function', ['undefined', declarativeTypeValidator.objectSchema('document metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Function, Object]), __metadata("design:returntype", Promise)], SyncDocument.prototype, "mutate", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.pureObject, ['undefined', declarativeTypeValidator.objectSchema('document metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise)], SyncDocument.prototype, "update", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", Promise)], SyncDocument.prototype, "setTtl", null); /** * Represents an individual element in a Sync list. */ var SyncListItem = /*#__PURE__*/function () { /** * @param descriptor Item descriptor * @internal */ function SyncListItem(descriptor) { _classCallCheck__default['default'](this, SyncListItem); this.descriptor = descriptor; } _createClass__default['default'](SyncListItem, [{ key: "uri", get: function get() { return this.descriptor.uri; } }, { key: "revision", get: function get() { return this.descriptor.revision; } }, { key: "lastEventId", get: function get() { return this.descriptor.lastEventId; } /** * Date when the list item was last updated. */ }, { key: "dateUpdated", get: function get() { return this.descriptor.dateUpdated; } }, { key: "dateExpires", get: function get() { return this.descriptor.dateExpires; } /** * The index, within the containing list, of this item. This index is stable; * even if lower-indexed items are removed, this index will remain as is. */ }, { key: "index", get: function get() { return this.descriptor.index; } /** * The contents of the item. */ }, { key: "data", get: function get() { return this.descriptor.data; } /** * @internal */ }, { key: "update", value: function update(eventId, revision, data, dateUpdated) { this.descriptor.lastEventId = eventId; this.descriptor.revision = revision; this.descriptor.data = data; this.descriptor.dateUpdated = dateUpdated; return this; } /** * @internal */ }, { key: "updateDateExpires", value: function updateDateExpires(dateExpires) { this.descriptor.dateExpires = dateExpires; } }]); return SyncListItem; }(); /** * Pagination helper class. */ var Paginator = /*#__PURE__*/function () { /** * Array of elements on current page. */ /** * @internal */ function Paginator(items, source, prevToken, nextToken) { _classCallCheck__default['default'](this, Paginator); this.prevToken = prevToken; this.nextToken = nextToken; this.items = items; this.source = source; } /** * Indicates the existence of the next page. */ _createClass__default['default'](Paginator, [{ key: "hasNextPage", get: function get() { return !!this.nextToken; } /** * Indicates the existence of the previous page. */ }, { key: "hasPrevPage", get: function get() { return !!this.prevToken; } /** * Request next page. * Does not modify existing object. */ }, { key: "nextPage", value: function () { var _nextPage = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() { return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (this.hasNextPage) { _context.next = 2; break; } throw new Error('No next page'); case 2: return _context.abrupt("return", this.source(this.nextToken)); case 3: case "end": return _context.stop(); } } }, _callee, this); })); function nextPage() { return _nextPage.apply(this, arguments); } return nextPage; }() /** * Request previous page. * Does not modify existing object. */ }, { key: "prevPage", value: function () { var _prevPage = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2() { return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (this.hasPrevPage) { _context2.next = 2; break; } throw new Error('No previous page'); case 2: return _context2.abrupt("return", this.source(this.prevToken)); case 3: case "end": return _context2.stop(); } } }, _callee2, this); })); function prevPage() { return _prevPage.apply(this, arguments); } return prevPage; }() }]); return Paginator; }(); function _createForOfIteratorHelper$1$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$1$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1$1(o, minLen); } function _arrayLikeToArray$1$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var Node = /*#__PURE__*/function () { function Node(key, value) { _classCallCheck__default['default'](this, Node); this.balanceFactor = 0; this.key = key; this.value = value; this.parent = null; this.left = null; this.right = null; } _createClass__default['default'](Node, [{ key: "isRoot", get: function get() { return this.parent === null; } }, { key: "isLeaf", get: function get() { return this.left === null && this.right === null; } }, { key: "isLeftChild", get: function get() { return this.parent.left === this; } }, { key: "update", value: function update(value) { this.value = value; } }, { key: "replace", value: function replace(target, replacement) { if (!target) { return; } if (this.left === replacement) { this.left = replacement; } else if (this.right === replacement) { this.right = replacement; } } }]); return Node; }(); /** * @property length */ var TreeMap = /*#__PURE__*/function () { function TreeMap(less, equal) { _classCallCheck__default['default'](this, TreeMap); this.isLessThan = less || function (x, y) { return x < y; }; this.isEqual = equal || function (x, y) { return x === y; }; this.root = null; this.count = null; } _createClass__default['default'](TreeMap, [{ key: "size", get: function get() { return this.count; } }, { key: "clear", value: function clear() { this.root = null; this.count = 0; } }, { key: "set", value: function set(key, value) { var node = this.getNode(key); if (node) { node.update(value); } else { this.insert(key, value); } // return node; } }, { key: "insert", value: function insert(key, value) { var node = new Node(key, value); this.count++; if (!this.root) { this.root = node; // return node; return; } var currNode = this.root; for (;;) { if (this.isLessThan(key, currNode.key)) { if (currNode.left) { currNode = currNode.left; } else { currNode.left = node; break; } } else { if (currNode.right) { // eslint-disable-line no-lonely-if currNode = currNode.right; } else { currNode.right = node; break; } } } node.parent = currNode; currNode = node; while (currNode.parent) { var parent = currNode.parent; var prevBalanceFactor = parent.balanceFactor; if (currNode.isLeftChild) { parent.balanceFactor++; } else { parent.balanceFactor--; } if (Math.abs(parent.balanceFactor) < Math.abs(prevBalanceFactor)) { break; } if (parent.balanceFactor < -1 || parent.balanceFactor > 1) { this.rebalance(parent); break; } currNode = parent; } // return node; } }, { key: "get", value: function get(key) { var currentNode = this.root; while (currentNode) { if (this.isEqual(key, currentNode.key)) { return currentNode.value; } if (this.isLessThan(key, currentNode.key)) { currentNode = currentNode.left; } else { currentNode = currentNode.right; } } return null; } }, { key: "delete", value: function _delete(key) { // update this algorithm and remove any var node = this.getNode(key); if (!node || node.key !== key) { return null; } var parent = node.parent; var left = node.left; var right = node.right; if (!!left !== !!right) { // one child var child = left || right; if (!parent && !child) { this.root = null; } else if (parent && !child) { this.root = child; } else { parent.replace(node, null); this.rebalance(parent); } } else { // two children var maxLeft = node.left; while (maxLeft.right) { maxLeft = maxLeft.right; } if (node.left === maxLeft) { if (node.isRoot) { this.root = maxLeft; maxLeft.parent = null; } else { if (node.isLeftChild) { node.parent.left = maxLeft; } else { node.parent.right = maxLeft; } maxLeft.parent = node.parent; } maxLeft.right = node.right; maxLeft.right.parent = maxLeft; maxLeft.balanceFactor = node.balanceFactor; node = { parent: maxLeft, isLeftChild: true }; } else { var mlParent = maxLeft.parent; var mlLeft = maxLeft.left; mlParent.right = mlLeft; if (mlLeft) { mlLeft.parent = mlParent; } if (node.isRoot) { this.root = maxLeft; maxLeft.parent = null; } else { if (node.isLeftChild) { node.parent.left = maxLeft; } else { node.parent.right = maxLeft; } maxLeft.parent = node.parent; } maxLeft.right = node.right; maxLeft.right.parent = maxLeft; maxLeft.left = node.left; maxLeft.left.parent = maxLeft; maxLeft.balanceFactor = node.balanceFactor; node = { parent: mlParent, isLeftChild: false }; } } this.count--; while (node.parent) { var _parent = node.parent; var prevBalanceFactor = _parent.balanceFactor; if (node.isLeftChild) { _parent.balanceFactor -= 1; } else { _parent.balanceFactor += 1; } if (Math.abs(_parent.balanceFactor) > Math.abs(prevBalanceFactor)) { if (_parent.balanceFactor < -1 || _parent.balanceFactor > 1) { this.rebalance(_parent); if (_parent.parent.balanceFactor === 0) { node = _parent.parent; } else { break; } } else { break; } } else { node = _parent; } } return null; } }, { key: "getNode", value: function getNode(key) { var currentNode = this.root; while (currentNode) { if (this.isEqual(key, currentNode.key)) { return currentNode; } if (this.isLessThan(key, currentNode.key)) { currentNode = currentNode.left; } else { currentNode = currentNode.right; } } return null; } }, { key: "rebalance", value: function rebalance(node) { if (node.balanceFactor < 0) { if (node.right.balanceFactor > 0) { this.rotateRight(node.right); this.rotateLeft(node); } else { this.rotateLeft(node); } } else if (node.balanceFactor > 0) { if (node.left.balanceFactor < 0) { this.rotateLeft(node.left); this.rotateRight(node); } else { this.rotateRight(node); } } } }, { key: "rotateLeft", value: function rotateLeft(pivot) { var root = pivot.right; pivot.right = root.left; if (root.left !== null) { root.left.parent = pivot; } root.parent = pivot.parent; if (root.parent === null) { this.root = root; } else if (pivot.isLeftChild) { root.parent.left = root; } else { root.parent.right = root; } root.left = pivot; pivot.parent = root; pivot.balanceFactor = pivot.balanceFactor + 1 - Math.min(root.balanceFactor, 0); root.balanceFactor = root.balanceFactor + 1 - Math.max(pivot.balanceFactor, 0); } }, { key: "rotateRight", value: function rotateRight(pivot) { var root = pivot.left; pivot.left = root.right; if (root.right !== null) { root.right.parent = pivot; } root.parent = pivot.parent; if (root.parent === null) { this.root = root; } else if (pivot.isLeftChild) { root.parent.left = root; } else { root.parent.right = root; } root.right = pivot; pivot.parent = root; pivot.balanceFactor = pivot.balanceFactor - 1 - Math.min(root.balanceFactor, 0); root.balanceFactor = root.balanceFactor - 1 - Math.max(pivot.balanceFactor, 0); } }, { key: Symbol.iterator, value: /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function value() { var _iterator, _step, iter; return _regeneratorRuntime__default['default'].wrap(function value$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _iterator = _createForOfIteratorHelper$1$1(this.getIterator()); _context.prev = 1; _iterator.s(); case 3: if ((_step = _iterator.n()).done) { _context.next = 9; break; } iter = _step.value; _context.next = 7; return iter; case 7: _context.next = 3; break; case 9: _context.next = 14; break; case 11: _context.prev = 11; _context.t0 = _context["catch"](1); _iterator.e(_context.t0); case 14: _context.prev = 14; _iterator.f(); return _context.finish(14); case 17: case "end": return _context.stop(); } } }, value, this, [[1, 11, 14, 17]]); }) }, { key: "getIterator", value: /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function getIterator() { var key, currentNode, fromleft, _args2 = arguments; return _regeneratorRuntime__default['default'].wrap(function getIterator$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: key = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : null; currentNode = this.root; case 2: if (!currentNode) { _context2.next = 8; break; } if (!(this.isEqual(key, currentNode.key) || key === null && !currentNode.left)) { _context2.next = 5; break; } return _context2.abrupt("break", 8); case 5: if (this.isLessThan(key, currentNode.key) || key === null) { currentNode = currentNode.left; } else { currentNode = currentNode.right; } _context2.next = 2; break; case 8: if (currentNode) { _context2.next = 10; break; } return _context2.abrupt("return", null); case 10: fromleft = true; case 11: if (!fromleft) { _context2.next = 29; break; } _context2.next = 14; return [currentNode.key, currentNode.value]; case 14: fromleft = false; if (!currentNode.right) { _context2.next = 21; break; } currentNode = currentNode.right; while (currentNode.left) { currentNode = currentNode.left; } fromleft = true; _context2.next = 27; break; case 21: if (!currentNode.parent) { _context2.next = 26; break; } fromleft = currentNode.parent.left === currentNode; currentNode = currentNode.parent; _context2.next = 27; break; case 26: return _context2.abrupt("break", 37); case 27: _context2.next = 35; break; case 29: if (!currentNode.parent) { _context2.next = 34; break; } fromleft = currentNode.parent.left === currentNode; currentNode = currentNode.parent; _context2.next = 35; break; case 34: return _context2.abrupt("break", 37); case 35: _context2.next = 11; break; case 37: return _context2.abrupt("return", null); case 38: case "end": return _context2.stop(); } } }, getIterator, this); }) }, { key: "getReverseIterator", value: /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function getReverseIterator() { var key, currentNode, fromright, _args3 = arguments; return _regeneratorRuntime__default['default'].wrap(function getReverseIterator$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: key = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : null; currentNode = this.root; case 2: if (!currentNode) { _context3.next = 8; break; } if (!(this.isEqual(key, currentNode.key) || key === null && !currentNode.right)) { _context3.next = 5; break; } return _context3.abrupt("break", 8); case 5: if (!this.isLessThan(key, currentNode.key) || key === null) { currentNode = currentNode.right; } else { currentNode = currentNode.left; } _context3.next = 2; break; case 8: if (currentNode) { _context3.next = 10; break; } return _context3.abrupt("return", null); case 10: fromright = true; case 11: if (!fromright) { _context3.next = 29; break; } _context3.next = 14; return [currentNode.key, currentNode.value]; case 14: fromright = false; if (!currentNode.left) { _context3.next = 21; break; } currentNode = currentNode.left; while (currentNode.right) { currentNode = currentNode.right; } fromright = true; _context3.next = 27; break; case 21: if (!currentNode.parent) { _context3.next = 26; break; } fromright = currentNode.parent.right === currentNode; currentNode = currentNode.parent; _context3.next = 27; break; case 26: return _context3.abrupt("break", 37); case 27: _context3.next = 35; break; case 29: if (!currentNode.parent) { _context3.next = 34; break; } fromright = currentNode.parent.right === currentNode; currentNode = currentNode.parent; _context3.next = 35; break; case 34: return _context3.abrupt("break", 37); case 35: _context3.next = 11; break; case 37: return _context3.abrupt("return", null); case 38: case "end": return _context3.stop(); } } }, getReverseIterator, this); }) }]); return TreeMap; }(); function _createForOfIteratorHelper$4(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$4(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$4(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen); } function _arrayLikeToArray$4(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var Entry = /*#__PURE__*/function () { function Entry(value, revision) { _classCallCheck__default['default'](this, Entry); this.value = value; this.revision = revision || 0; } _createClass__default['default'](Entry, [{ key: "isValid", get: function get() { return true; } }]); return Entry; }(); var Tombstone = /*#__PURE__*/function () { function Tombstone(revision) { _classCallCheck__default['default'](this, Tombstone); this.revision = revision; } _createClass__default['default'](Tombstone, [{ key: "isValid", get: function get() { return false; } }]); return Tombstone; }(); var Cache = /*#__PURE__*/function () { function Cache() { _classCallCheck__default['default'](this, Cache); this.items = new TreeMap(); } _createClass__default['default'](Cache, [{ key: "store", value: function store(key, value, revision) { var entry = this.items.get(key); if (entry && entry.revision > revision) { if (entry.isValid) { return entry.value; } return null; } this.items.set(key, new Entry(value, revision)); return value; } }, { key: "delete", value: function _delete(key, revision) { var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var curr = this.items.get(key); if (!curr || curr.revision < revision || curr && force === true /* forced delete when revision is unknown */ ) { this.items.set(key, new Tombstone(revision)); } } }, { key: "isKnown", value: function isKnown(key, revision) { var curr = this.items.get(key); return curr && curr.revision >= revision; } }, { key: "get", value: function get(key) { var entry = this.items.get(key); if (entry && entry.isValid) { return entry.value; } return null; } }, { key: "has", value: function has(key) { var entry = this.items.get(key); return entry && entry.isValid; } }, { key: "forEach", value: function forEach(callbackfn) { if (this.items) { var _iterator = _createForOfIteratorHelper$4(this.items), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _step$value = _slicedToArray__default['default'](_step.value, 2), key = _step$value[0], entry = _step$value[1]; if (entry.isValid) { callbackfn(key, entry.value); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } } }]); return Cache; }(); function _createSuper$4$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$4$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var SyncListImpl = /*#__PURE__*/function (_SyncEntity) { _inherits__default['default'](SyncListImpl, _SyncEntity); var _super = _createSuper$4$1(SyncListImpl); /** * @private */ function SyncListImpl(services, descriptor, removalHandler) { var _this; _classCallCheck__default['default'](this, SyncListImpl); _this = _super.call(this, services, removalHandler); var updateRequestReducer = function updateRequestReducer(acc, input) { return typeof input.ttl === 'number' ? { ttl: input.ttl } : acc; }; _this.updateMergingQueue = new NamespacedMergingQueue(updateRequestReducer); _this.cache = new Cache(); _this.descriptor = descriptor; _this.descriptor.date_updated = new Date(_this.descriptor.date_updated); return _this; } // private props _createClass__default['default'](SyncListImpl, [{ key: "uri", get: function get() { return this.descriptor.url; } }, { key: "revision", get: function get() { return this.descriptor.revision; } }, { key: "lastEventId", get: function get() { return this.descriptor.last_event_id; } }, { key: "links", get: function get() { return this.descriptor.links; } }, { key: "dateExpires", get: function get() { return this.descriptor.date_expires; } }, { key: "type", get: function get() { return 'list'; } // below properties are specific to Insights only }, { key: "indexName", get: function get() { return undefined; } }, { key: "queryString", get: function get() { return undefined; } // public props, documented along with class description }, { key: "sid", get: function get() { return this.descriptor.sid; } }, { key: "uniqueName", get: function get() { return this.descriptor.unique_name || null; } }, { key: "dateUpdated", get: function get() { return this.descriptor.date_updated; } }, { key: "_addOrUpdateItemOnServer", value: function () { var _addOrUpdateItemOnServer2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(url, data, ifMatch, ttl) { var requestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: requestBody = { data: data }; if (ttl !== undefined) { requestBody.ttl = ttl; } _context.next = 4; return this.services.network.post(url, requestBody, ifMatch); case 4: response = _context.sent; response.body.data = data; response.body.date_updated = new Date(response.body.date_updated); return _context.abrupt("return", response.body); case 8: case "end": return _context.stop(); } } }, _callee, this); })); function _addOrUpdateItemOnServer(_x, _x2, _x3, _x4) { return _addOrUpdateItemOnServer2.apply(this, arguments); } return _addOrUpdateItemOnServer; }() }, { key: "push", value: function () { var _push = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(value, itemMetadata) { var ttl, item, index; return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: ttl = (itemMetadata || {}).ttl; _context2.next = 3; return this._addOrUpdateItemOnServer(this.links.items, value, undefined, ttl); case 3: item = _context2.sent; index = Number(item.index); this._handleItemMutated(index, item.url, item.last_event_id, item.revision, value, item.date_updated, item.date_expires, true, false); return _context2.abrupt("return", this.cache.get(index)); case 7: case "end": return _context2.stop(); } } }, _callee2, this); })); function push(_x5, _x6) { return _push.apply(this, arguments); } return push; }() }, { key: "set", value: function () { var _set = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(index, value, itemMetadataUpdates) { var _this2 = this; var input; return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: input = itemMetadataUpdates || {}; return _context3.abrupt("return", this.updateMergingQueue.squashAndAdd(index, input, function (input) { return _this2._updateItemUnconditionally(index, value, input.ttl); })); case 2: case "end": return _context3.stop(); } } }, _callee3, this); })); function set(_x7, _x8, _x9) { return _set.apply(this, arguments); } return set; }() }, { key: "_updateItemUnconditionally", value: function () { var _updateItemUnconditionally2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4(index, data, ttl) { var existingItem, itemDescriptor; return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this.get(index); case 2: existingItem = _context4.sent; _context4.next = 5; return this._addOrUpdateItemOnServer(existingItem.uri, data, undefined, ttl); case 5: itemDescriptor = _context4.sent; this._handleItemMutated(index, itemDescriptor.url, itemDescriptor.last_event_id, itemDescriptor.revision, itemDescriptor.data, itemDescriptor.date_updated, itemDescriptor.date_expires, false, false); return _context4.abrupt("return", this.cache.get(index)); case 8: case "end": return _context4.stop(); } } }, _callee4, this); })); function _updateItemUnconditionally(_x10, _x11, _x12) { return _updateItemUnconditionally2.apply(this, arguments); } return _updateItemUnconditionally; }() }, { key: "_updateItemWithIfMatch", value: function () { var _updateItemWithIfMatch2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(index, mutatorFunction, ttl) { var existingItem, data, ifMatch, itemDescriptor; return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this.get(index); case 2: existingItem = _context5.sent; data = mutatorFunction(deepClone(existingItem.data)); if (!data) { _context5.next = 25; break; } ifMatch = existingItem.revision; _context5.prev = 6; _context5.next = 9; return this._addOrUpdateItemOnServer(existingItem.uri, data, ifMatch, ttl); case 9: itemDescriptor = _context5.sent; this._handleItemMutated(index, itemDescriptor.url, itemDescriptor.last_event_id, itemDescriptor.revision, itemDescriptor.data, itemDescriptor.date_updated, itemDescriptor.date_expires, false, false); return _context5.abrupt("return", this.cache.get(index)); case 14: _context5.prev = 14; _context5.t0 = _context5["catch"](6); if (!(_context5.t0.status === 412)) { _context5.next = 22; break; } _context5.next = 19; return this._getItemFromServer(index); case 19: return _context5.abrupt("return", this._updateItemWithIfMatch(index, mutatorFunction, ttl)); case 22: throw _context5.t0; case 23: _context5.next = 26; break; case 25: return _context5.abrupt("return", existingItem); case 26: case "end": return _context5.stop(); } } }, _callee5, this, [[6, 14]]); })); function _updateItemWithIfMatch(_x13, _x14, _x15) { return _updateItemWithIfMatch2.apply(this, arguments); } return _updateItemWithIfMatch; }() }, { key: "mutate", value: function () { var _mutate = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(index, mutator, itemMetadataUpdates) { var _this3 = this; var input; return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: input = itemMetadataUpdates || {}; return _context6.abrupt("return", this.updateMergingQueue.add(index, input, function (input) { return _this3._updateItemWithIfMatch(index, mutator, input.ttl); })); case 2: case "end": return _context6.stop(); } } }, _callee6, this); })); function mutate(_x16, _x17, _x18) { return _mutate.apply(this, arguments); } return mutate; }() }, { key: "update", value: function () { var _update2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee7(index, obj, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: return _context7.abrupt("return", this.mutate(index, function (remote) { return Object.assign(remote, obj); }, itemMetadataUpdates)); case 1: case "end": return _context7.stop(); } } }, _callee7, this); })); function update(_x19, _x20, _x21) { return _update2.apply(this, arguments); } return update; }() }, { key: "remove", value: function () { var _remove = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee8(index) { var item, previousItemData, response; return _regeneratorRuntime__default['default'].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; return this.get(index); case 2: item = _context8.sent; previousItemData = deepClone(item.data); _context8.next = 6; return this.services.network.delete(item.uri); case 6: response = _context8.sent; this._handleItemRemoved(index, response.body.last_event_id, previousItemData, new Date(response.body.date_updated), false); case 8: case "end": return _context8.stop(); } } }, _callee8, this); })); function remove(_x22) { return _remove.apply(this, arguments); } return remove; }() }, { key: "get", value: function () { var _get = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee9(index) { var cachedItem; return _regeneratorRuntime__default['default'].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: cachedItem = this.cache.get(index); if (!cachedItem) { _context9.next = 5; break; } return _context9.abrupt("return", cachedItem); case 5: return _context9.abrupt("return", this._getItemFromServer(index)); case 6: case "end": return _context9.stop(); } } }, _callee9, this); })); function get(_x23) { return _get.apply(this, arguments); } return get; }() }, { key: "_getItemFromServer", value: function () { var _getItemFromServer2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee10(index) { var result; return _regeneratorRuntime__default['default'].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return this.queryItems({ index: index }); case 2: result = _context10.sent; if (!(result.items.length < 1)) { _context10.next = 7; break; } throw new SyncError("No item with index ".concat(index, " found"), 404, 54151); case 7: return _context10.abrupt("return", result.items[0]); case 8: case "end": return _context10.stop(); } } }, _callee10, this); })); function _getItemFromServer(_x24) { return _getItemFromServer2.apply(this, arguments); } return _getItemFromServer; }() /** * Query items from the List * @private */ }, { key: "queryItems", value: function () { var _queryItems = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee11(arg) { var _this4 = this; var url, response, items, meta; return _regeneratorRuntime__default['default'].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: arg = arg || {}; url = new UriBuilder(this.links.items).queryParam('From', arg.from).queryParam('PageSize', arg.limit).queryParam('Index', arg.index).queryParam('PageToken', arg.pageToken).queryParam('Order', arg.order).build(); _context11.next = 4; return this.services.network.get(url); case 4: response = _context11.sent; items = response.body.items.map(function (el) { el.date_updated = new Date(el.date_updated); var itemInCache = _this4.cache.get(el.index); if (itemInCache) { _this4._handleItemMutated(el.index, el.url, el.last_event_id, el.revision, el.data, el.date_updated, el.date_expires, false, true); } else { _this4.cache.store(Number(el.index), new SyncListItem({ index: Number(el.index), uri: el.url, revision: el.revision, lastEventId: el.last_event_id, dateUpdated: el.date_updated, dateExpires: el.date_expires, data: el.data }), el.last_event_id); } return _this4.cache.get(el.index); }); meta = response.body.meta; return _context11.abrupt("return", new Paginator(items, function (pageToken) { return _this4.queryItems({ pageToken: pageToken }); }, meta.previous_token, meta.next_token)); case 8: case "end": return _context11.stop(); } } }, _callee11, this); })); function queryItems(_x25) { return _queryItems.apply(this, arguments); } return queryItems; }() }, { key: "getItems", value: function () { var _getItems = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee12(args) { return _regeneratorRuntime__default['default'].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: args = args || {}; validatePageSize(args.pageSize); args.limit = args.pageSize || args.limit || 50; args.order = args.order || 'asc'; return _context12.abrupt("return", this.queryItems(args)); case 5: case "end": return _context12.stop(); } } }, _callee12, this); })); function getItems(_x26) { return _getItems.apply(this, arguments); } return getItems; }() /** * @return {Promise} Context of List * @private */ }, { key: "getContext", value: function () { var _getContext = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee13() { var response; return _regeneratorRuntime__default['default'].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: if (this.context) { _context13.next = 5; break; } _context13.next = 3; return this.services.network.get(this.links.context); case 3: response = _context13.sent; // store fetched context if we have't received any newer update this._updateContextIfRequired(response.body.data, response.body.last_event_id); case 5: return _context13.abrupt("return", this.context); case 6: case "end": return _context13.stop(); } } }, _callee13, this); })); function getContext() { return _getContext.apply(this, arguments); } return getContext; }() }, { key: "setTtl", value: function () { var _setTtl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee14(ttl) { var requestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.prev = 0; requestBody = { ttl: ttl }; _context14.next = 4; return this.services.network.post(this.uri, requestBody); case 4: response = _context14.sent; this.descriptor.date_expires = response.body.date_expires; _context14.next = 12; break; case 8: _context14.prev = 8; _context14.t0 = _context14["catch"](0); if (_context14.t0.status === 404) { this.onRemoved(false); } throw _context14.t0; case 12: case "end": return _context14.stop(); } } }, _callee14, this, [[0, 8]]); })); function setTtl(_x27) { return _setTtl.apply(this, arguments); } return setTtl; }() }, { key: "setItemTtl", value: function () { var _setItemTtl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee15(index, ttl) { var existingItem, requestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: _context15.next = 2; return this.get(index); case 2: existingItem = _context15.sent; requestBody = { ttl: ttl }; _context15.next = 6; return this.services.network.post(existingItem.uri, requestBody); case 6: response = _context15.sent; existingItem.updateDateExpires(response.body.date_expires); case 8: case "end": return _context15.stop(); } } }, _callee15, this); })); function setItemTtl(_x28, _x29) { return _setItemTtl.apply(this, arguments); } return setItemTtl; }() }, { key: "removeList", value: function () { var _removeList = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee16() { return _regeneratorRuntime__default['default'].wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: _context16.next = 2; return this.services.network.delete(this.uri); case 2: this.onRemoved(true); case 3: case "end": return _context16.stop(); } } }, _callee16, this); })); function removeList() { return _removeList.apply(this, arguments); } return removeList; }() }, { key: "onRemoved", value: function onRemoved(locally) { this._unsubscribe(); this.removalHandler(this.type, this.sid, this.uniqueName); this.broadcastEventToListeners('removed', { isLocal: locally }); } }, { key: "shouldIgnoreEvent", value: function shouldIgnoreEvent(key, eventId) { return this.cache.isKnown(key, eventId); } /** * Handle update, which came from the server. * @private */ }, { key: "_update", value: function _update(update, isStrictlyOrdered) { var itemIndex = Number(update.item_index); update.date_created = new Date(update.date_created); switch (update.type) { case 'list_item_added': case 'list_item_updated': { this._handleItemMutated(itemIndex, update.item_url, update.id, update.item_revision, update.item_data, update.date_created, undefined, // orchestration does not include date_expires -- @todo it does now? update.type === 'list_item_added', true); } break; case 'list_item_removed': { this._handleItemRemoved(itemIndex, update.id, update.item_data, update.date_created, true); } break; case 'list_context_updated': { this._handleContextUpdate(update.context_data, update.id, update.date_created); } break; case 'list_removed': { this.onRemoved(false); } break; } if (isStrictlyOrdered) { this._advanceLastEventId(update.id, update.list_revision); } } }, { key: "_advanceLastEventId", value: function _advanceLastEventId(eventId, revision) { if (this.lastEventId < eventId) { this.descriptor.last_event_id = eventId; if (revision) { this.descriptor.revision = revision; } } } }, { key: "_updateRootDateUpdated", value: function _updateRootDateUpdated(dateUpdated) { if (!this.descriptor.date_updated || dateUpdated.getTime() > this.descriptor.date_updated.getTime()) { this.descriptor.date_updated = dateUpdated; this.services.storage.update(this.type, this.sid, this.uniqueName, { date_updated: dateUpdated }); } } }, { key: "_handleItemMutated", value: function _handleItemMutated(index, uri, lastEventId, revision, data, dateUpdated, dateExpires, added, remote) { if (this.shouldIgnoreEvent(index, lastEventId)) { log$1$1.trace("Item ".concat(index, " update skipped, current: ").concat(this.lastEventId, ", remote: ").concat(lastEventId)); return; } this._updateRootDateUpdated(dateUpdated); var item = this.cache.get(index); if (!item) { var newItem = new SyncListItem({ index: index, uri: uri, lastEventId: lastEventId, revision: revision, data: data, dateUpdated: dateUpdated, dateExpires: dateExpires }); this.cache.store(index, newItem, lastEventId); this.emitItemMutationEvent(newItem, remote, added); return; } var previousItemData = deepClone(item.data); item.update(lastEventId, revision, data, dateUpdated); this.cache.store(index, item, lastEventId); if (dateExpires !== undefined) { item.updateDateExpires(dateExpires); } this.emitItemMutationEvent(item, remote, false, previousItemData); } /** * @private */ }, { key: "emitItemMutationEvent", value: function emitItemMutationEvent(item, remote, added) { var previousItemData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var eventName = added ? 'itemAdded' : 'itemUpdated'; var args = { item: item, isLocal: !remote }; if (!added) { args.previousItemData = previousItemData; } this.broadcastEventToListeners(eventName, args); } /** * @private */ }, { key: "_handleItemRemoved", value: function _handleItemRemoved(index, eventId, oldData, dateUpdated, remote) { this._updateRootDateUpdated(dateUpdated); this.cache.delete(index, eventId); this.broadcastEventToListeners('itemRemoved', { index: index, isLocal: !remote, previousItemData: oldData }); } /** * @private */ }, { key: "_handleContextUpdate", value: function _handleContextUpdate(data, eventId, dateUpdated) { this._updateRootDateUpdated(dateUpdated); if (this._updateContextIfRequired(data, eventId)) { this.broadcastEventToListeners('contextUpdated', { context: data, isLocal: false }); } } /** * @private */ }, { key: "_updateContextIfRequired", value: function _updateContextIfRequired(data, eventId) { if (!this.contextEventId || eventId > this.contextEventId) { this.context = data; this.contextEventId = eventId; return true; } else { log$1$1.trace('Context update skipped, current:', this.lastEventId, ', remote:', eventId); return false; } } }], [{ key: "type", get: function get() { return 'list'; } }]); return SyncListImpl; }(SyncEntity); /** * Represents a Sync list, which stores an ordered list of values. * Use the {@link SyncClient.list} method to obtain a reference to a Sync list. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ var SyncList = /*#__PURE__*/function (_Closeable) { _inherits__default['default'](SyncList, _Closeable); var _super2 = _createSuper$4$1(SyncList); /** * @internal */ function SyncList(syncListImpl) { var _this5; _classCallCheck__default['default'](this, SyncList); _this5 = _super2.call(this); _this5.syncListImpl = syncListImpl; _this5.syncListImpl.attach(_assertThisInitialized__default['default'](_this5)); return _this5; } /** * Fired when a new item appears in the list, regardless of whether its creator was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncListItem} `item` - added item * * boolean `isLocal` - equals true if the item was added by a local actor, false otherwise * @example * ```typescript * list.on('itemAdded', (args) => { * console.log(`List item ${args.item.index} was added`); * console.log('args.item.data:', args.item.data); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ _createClass__default['default'](SyncList, [{ key: "uri", get: // private props function get() { return this.syncListImpl.uri; } }, { key: "revision", get: function get() { return this.syncListImpl.revision; } }, { key: "lastEventId", get: function get() { return this.syncListImpl.lastEventId; } }, { key: "links", get: function get() { return this.syncListImpl.links; } }, { key: "dateExpires", get: function get() { return this.syncListImpl.dateExpires; } }, { key: "type", get: function get() { return SyncListImpl.type; } /** * Unique ID of the list, immutable identifier assigned by the system. */ }, { key: "sid", get: function get() { return this.syncListImpl.sid; } /** * Unique name of the list, immutable identifier that can be assigned to the list during creation. */ }, { key: "uniqueName", get: function get() { return this.syncListImpl.uniqueName; } /** * Date when the list was last updated, given in UTC ISO 8601 format (e.g., '2018-04-26T15:23:19.732Z'). */ }, { key: "dateUpdated", get: function get() { return this.syncListImpl.dateUpdated; } }, { key: "push", value: /** * Add a new item to the list. * @param data Data to be added. * @param itemMetadata Item metadata. * @return The newly added item. * @example * ```typescript * list.push({ name: 'John Smith' }, { ttl: 86400 }) * .then((item) => { * console.log(`List Item push() successful, item index: ${item.index}, data:`, item.data) * }) * .catch((error) => { * console.error('List Item push() failed', error); * }); * ``` */ function () { var _push2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee17(data, itemMetadata) { return _regeneratorRuntime__default['default'].wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: this.ensureNotClosed(); return _context17.abrupt("return", this.syncListImpl.push(data, itemMetadata)); case 2: case "end": return _context17.stop(); } } }, _callee17, this); })); function push(_x30, _x31) { return _push2.apply(this, arguments); } return push; }() /** * Assign new data to an existing item, given its index. * @param index Index of the item to be updated. * @param value New data to be assigned to an item. * @param itemMetadataUpdates New item metadata. * @return A promise with the updated item containing latest known data. * The promise will be rejected if the item does not exist. * @example * ```typescript * list.set(42, { name: 'John Smith' }, { ttl: 86400 }) * .then((item) => { * console.log('List Item set() successful, item data:', item.data) * }) * .catch((error) => { * console.error('List Item set() failed', error); * }); * ``` */ }, { key: "set", value: function () { var _set2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee18(index, value, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: this.ensureNotClosed(); return _context18.abrupt("return", this.syncListImpl.set(index, value, itemMetadataUpdates)); case 2: case "end": return _context18.stop(); } } }, _callee18, this); })); function set(_x32, _x33, _x34) { return _set2.apply(this, arguments); } return set; }() /** * Modify an existing item by applying a mutation function to it. * @param index Index of the item to be changed. * @param mutator A function that outputs a new data based on the existing data. * @param itemMetadataUpdates New item metadata. * @return Resolves with the most recent item state, the output of a successful * mutation or a state that prompted graceful cancellation (mutator returned `null`). This promise * will be rejected if the indicated item does not already exist. * @example * ```typescript * const mutatorFunction = (currentValue) => { * currentValue.viewCount = (currentValue.viewCount || 0) + 1; * return currentValue; * }; * list.mutate(42, mutatorFunction, { ttl: 86400 }) * .then((item) => { * console.log('List Item mutate() successful, new data:', item.data) * }) * .catch((error) => { * console.error('List Item mutate() failed', error); * }); * ``` */ }, { key: "mutate", value: function () { var _mutate2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee19(index, mutator, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: this.ensureNotClosed(); return _context19.abrupt("return", this.syncListImpl.mutate(index, mutator, itemMetadataUpdates)); case 2: case "end": return _context19.stop(); } } }, _callee19, this); })); function mutate(_x35, _x36, _x37) { return _mutate2.apply(this, arguments); } return mutate; }() /** * Modify an existing item by appending new fields (or overwriting existing ones) with the values from the object. * This is equivalent to * ```typescript * list.mutate(42, (currentValue) => Object.assign(currentValue, obj)); * ``` * @param index Index of an item to be changed. * @param obj Set of fields to update. * @param itemMetadataUpdates New item metadata. * @return A promise with a modified item containing latest known data. * The promise will be rejected if the item was not found. * @example * ```typescript * // Say, the List Item (index: 42) data is `{ name: 'John Smith' }` * list.update(42, { age: 34 }, { ttl: 86400 }) * .then((item) => { * // Now the List Item data is `{ name: 'John Smith', age: 34 }` * console.log('List Item update() successful, new data:', item.data); * }) * .catch((error) => { * console.error('List Item update() failed', error); * }); * ``` */ }, { key: "update", value: function () { var _update3 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee20(index, obj, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: this.ensureNotClosed(); return _context20.abrupt("return", this.syncListImpl.update(index, obj, itemMetadataUpdates)); case 2: case "end": return _context20.stop(); } } }, _callee20, this); })); function update(_x38, _x39, _x40) { return _update3.apply(this, arguments); } return update; }() /** * Delete an item given its index. * @param index Index of the item to be removed. * @return A promise to remove the item. * The promise will be rejected if the item was not found. * @example * ```typescript * list.remove(42) * .then(() => { * console.log('List Item remove() successful'); * }) * .catch((error) => { * console.error('List Item remove() failed', error); * }); * ``` */ }, { key: "remove", value: function () { var _remove2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee21(index) { return _regeneratorRuntime__default['default'].wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: this.ensureNotClosed(); return _context21.abrupt("return", this.syncListImpl.remove(index)); case 2: case "end": return _context21.stop(); } } }, _callee21, this); })); function remove(_x41) { return _remove2.apply(this, arguments); } return remove; }() /** * Retrieve an item by List index. * @param index Item index in the list. * @return A promise with the item containing latest known data. * The promise will be rejected if the item was not found. * @example * ```typescript * list.get(42) * .then((item) => { * console.log('List Item get() successful, item data:', item.data) * }) * .catch((error) => { * console.error('List Item get() failed', error); * }); * ``` */ }, { key: "get", value: function () { var _get3 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee22(index) { return _regeneratorRuntime__default['default'].wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: this.ensureNotClosed(); return _context22.abrupt("return", this.syncListImpl.get(index)); case 2: case "end": return _context22.stop(); } } }, _callee22, this); })); function get(_x42) { return _get3.apply(this, arguments); } return get; }() /** * Retrieve a list context * @return A promise with the list's context * @internal */ }, { key: "getContext", value: function () { var _getContext2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee23() { return _regeneratorRuntime__default['default'].wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: this.ensureNotClosed(); return _context23.abrupt("return", this.syncListImpl.getContext()); case 2: case "end": return _context23.stop(); } } }, _callee23, this); })); function getContext() { return _getContext2.apply(this, arguments); } return getContext; }() /** * Query a list of items from collection. * Information about the query limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. * @param queryOptions Query options. * @example * ```typescript * const pageHandler = (paginator) => { * paginator.items.forEach((item) => { * console.log(`Item ${item.index}:`, item.data); * }); * return paginator.hasNextPage * ? paginator.nextPage().then(pageHandler) * : null; * }; * list.getItems({ from: 0, order: 'asc' }) * .then(pageHandler) * .catch((error) => { * console.error('List getItems() failed', error); * }); * ``` */ }, { key: "getItems", value: function () { var _getItems2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee24(queryOptions) { return _regeneratorRuntime__default['default'].wrap(function _callee24$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: this.ensureNotClosed(); return _context24.abrupt("return", this.syncListImpl.getItems(queryOptions)); case 2: case "end": return _context24.stop(); } } }, _callee24, this); })); function getItems(_x43) { return _getItems2.apply(this, arguments); } return getItems; }() /** * Update the time-to-live of the list. * @param ttl Specifies the TTL in seconds after which the list is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * list.setTtl(3600) * .then(() => { * console.log('List setTtl() successful'); * }) * .catch((error) => { * console.error('List setTtl() failed', error); * }); * ``` */ }, { key: "setTtl", value: function () { var _setTtl2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee25(ttl) { return _regeneratorRuntime__default['default'].wrap(function _callee25$(_context25) { while (1) { switch (_context25.prev = _context25.next) { case 0: this.ensureNotClosed(); return _context25.abrupt("return", this.syncListImpl.setTtl(ttl)); case 2: case "end": return _context25.stop(); } } }, _callee25, this); })); function setTtl(_x44) { return _setTtl2.apply(this, arguments); } return setTtl; }() /** * Update the time-to-live of a list item. * @param index Item index. * @param ttl Specifies the TTL in seconds after which the list item is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * list.setItemTtl(42, 86400) * .then(() => { * console.log('List setItemTtl() successful'); * }) * .catch((error) => { * console.error('List setItemTtl() failed', error); * }); * ``` */ }, { key: "setItemTtl", value: function () { var _setItemTtl2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee26(index, ttl) { return _regeneratorRuntime__default['default'].wrap(function _callee26$(_context26) { while (1) { switch (_context26.prev = _context26.next) { case 0: this.ensureNotClosed(); return _context26.abrupt("return", this.syncListImpl.setItemTtl(index, ttl)); case 2: case "end": return _context26.stop(); } } }, _callee26, this); })); function setItemTtl(_x45, _x46) { return _setItemTtl2.apply(this, arguments); } return setItemTtl; }() /** * Delete this list. It will be impossible to restore it. * @return A promise that resolves when the list has been deleted. * @example * list.removeList() * .then(() => { * console.log('List removeList() successful'); * }) * .catch((error) => { * console.error('List removeList() failed', error); * }); */ }, { key: "removeList", value: function () { var _removeList2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee27() { return _regeneratorRuntime__default['default'].wrap(function _callee27$(_context27) { while (1) { switch (_context27.prev = _context27.next) { case 0: this.ensureNotClosed(); return _context27.abrupt("return", this.syncListImpl.removeList()); case 2: case "end": return _context27.stop(); } } }, _callee27, this); })); function removeList() { return _removeList2.apply(this, arguments); } return removeList; }() /** * Conclude work with the list instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this list will continue operating and receiving events normally. * @example * ```typescript * list.close(); * ``` */ }, { key: "close", value: function close() { _get__default['default'](_getPrototypeOf__default['default'](SyncList.prototype), "close", this).call(this); this.syncListImpl.detach(this.listenerUuid); } }], [{ key: "type", get: function get() { return SyncListImpl.type; } }]); return SyncList; }(Closeable); _defineProperty__default['default'](SyncList, "itemAdded", 'itemAdded'); _defineProperty__default['default'](SyncList, "itemUpdated", 'itemUpdated'); _defineProperty__default['default'](SyncList, "itemRemoved", 'itemRemoved'); _defineProperty__default['default'](SyncList, "removed", 'removed'); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.pureObject, ['undefined', declarativeTypeValidator.objectSchema('item metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise)], SyncList.prototype, "push", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger, declarativeTypeValidator.pureObject, ['undefined', declarativeTypeValidator.objectSchema('item metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Number, Object, Object]), __metadata("design:returntype", Promise)], SyncList.prototype, "set", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger, 'function', ['undefined', declarativeTypeValidator.objectSchema('item metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Number, Function, Object]), __metadata("design:returntype", Promise)], SyncList.prototype, "mutate", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger, declarativeTypeValidator.pureObject, ['undefined', declarativeTypeValidator.objectSchema('item metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Number, Object, Object]), __metadata("design:returntype", Promise)], SyncList.prototype, "update", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", Promise)], SyncList.prototype, "remove", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", Promise)], SyncList.prototype, "get", null); __decorate([declarativeTypeValidator.validateTypesAsync(['undefined', declarativeTypeValidator.objectSchema('query options', { from: [declarativeTypeValidator.nonNegativeInteger, 'undefined'], pageSize: [declarativeTypeValidator.custom(function (value) { return [isPositiveInteger(value), 'a positive integer']; }), 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], SyncList.prototype, "getItems", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", Promise)], SyncList.prototype, "setTtl", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger, declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number, Number]), __metadata("design:returntype", Promise)], SyncList.prototype, "setItemTtl", null); /** * Represents an individual element in a Sync map. */ var SyncMapItem = /*#__PURE__*/function () { /** * @internal */ function SyncMapItem(descriptor) { _classCallCheck__default['default'](this, SyncMapItem); this.descriptor = descriptor; } _createClass__default['default'](SyncMapItem, [{ key: "uri", get: function get() { return this.descriptor.url; } }, { key: "revision", get: function get() { return this.descriptor.revision; } }, { key: "lastEventId", get: function get() { return this.descriptor.last_event_id; } }, { key: "dateExpires", get: function get() { return this.descriptor.date_expires; } /** * The identifier that maps to this item within the containing Map. */ }, { key: "key", get: function get() { return this.descriptor.key; } /** * The contents of the item. */ }, { key: "data", get: function get() { return this.descriptor.data; } /** * Date when the map item was last updated. */ }, { key: "dateUpdated", get: function get() { return this.descriptor.date_updated; } /** * @internal */ }, { key: "update", value: function update(eventId, revision, value, dateUpdated) { this.descriptor.last_event_id = eventId; this.descriptor.revision = revision; this.descriptor.data = value; this.descriptor.date_updated = dateUpdated; return this; } /** * @internal */ }, { key: "updateDateExpires", value: function updateDateExpires(dateExpires) { this.descriptor.date_expires = dateExpires; } }]); return SyncMapItem; }(); function _createSuper$3$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$3$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var SyncMapImpl = /*#__PURE__*/function (_SyncEntity) { _inherits__default['default'](SyncMapImpl, _SyncEntity); var _super = _createSuper$3$1(SyncMapImpl); /** * @private */ function SyncMapImpl(services, descriptor, removalHandler) { var _this; _classCallCheck__default['default'](this, SyncMapImpl); _this = _super.call(this, services, removalHandler); var updateRequestReducer = function updateRequestReducer(acc, input) { return typeof input.ttl === 'number' ? { ttl: input.ttl } : acc; }; _this.updateMergingQueue = new NamespacedMergingQueue(updateRequestReducer); _this.cache = new Cache(); _this.descriptor = descriptor; _this.descriptor.date_updated = new Date(_this.descriptor.date_updated); if (descriptor.items) { descriptor.items.forEach(function (itemDescriptor) { itemDescriptor.date_updated = new Date(itemDescriptor.date_updated); _this.cache.store(itemDescriptor.key, new SyncMapItem(itemDescriptor), itemDescriptor.last_event_id); }); } return _this; } // private props _createClass__default['default'](SyncMapImpl, [{ key: "uri", get: function get() { return this.descriptor.url; } }, { key: "links", get: function get() { return this.descriptor.links; } }, { key: "revision", get: function get() { return this.descriptor.revision; } }, { key: "lastEventId", get: function get() { return this.descriptor.last_event_id; } }, { key: "dateExpires", get: function get() { return this.descriptor.date_expires; } }, { key: "type", get: function get() { return 'map'; } // below properties are specific to Insights only }, { key: "indexName", get: function get() { return undefined; } }, { key: "queryString", get: function get() { return undefined; } // public props, documented along with class description }, { key: "sid", get: function get() { return this.descriptor.sid; } }, { key: "uniqueName", get: function get() { return this.descriptor.unique_name || null; } }, { key: "dateUpdated", get: function get() { return this.descriptor.date_updated; } }, { key: "set", value: function () { var _set = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(key, value, itemMetadataUpdates) { var _this2 = this; var input; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: input = itemMetadataUpdates || {}; return _context.abrupt("return", this.updateMergingQueue.squashAndAdd(key, input, function (input) { return _this2._putItemUnconditionally(key, value, input.ttl); })); case 2: case "end": return _context.stop(); } } }, _callee, this); })); function set(_x, _x2, _x3) { return _set.apply(this, arguments); } return set; }() }, { key: "get", value: function () { var _get = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(key) { return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(key === null || key === undefined)) { _context2.next = 2; break; } throw new SyncError('SyncMapItem key may not be empty', 400, 54209); case 2: if (!this.cache.has(key)) { _context2.next = 6; break; } return _context2.abrupt("return", this.cache.get(key)); case 6: return _context2.abrupt("return", this._getItemFromServer(key)); case 7: case "end": return _context2.stop(); } } }, _callee2, this); })); function get(_x4) { return _get.apply(this, arguments); } return get; }() }, { key: "_getItemFromServer", value: function () { var _getItemFromServer2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(key) { var result; return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.queryItems({ key: key }); case 2: result = _context3.sent; if (!(result.items.length < 1)) { _context3.next = 7; break; } throw new SyncError("The specified Map Item does not exist", 404, 54201); case 7: return _context3.abrupt("return", result.items[0]); case 8: case "end": return _context3.stop(); } } }, _callee3, this); })); function _getItemFromServer(_x5) { return _getItemFromServer2.apply(this, arguments); } return _getItemFromServer; }() }, { key: "mutate", value: function () { var _mutate = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4(key, mutator, itemMetadataUpdates) { var _this3 = this; var input; return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: input = itemMetadataUpdates || {}; return _context4.abrupt("return", this.updateMergingQueue.add(key, input, function (input) { return _this3._putItemWithIfMatch(key, mutator, input.ttl); })); case 2: case "end": return _context4.stop(); } } }, _callee4, this); })); function mutate(_x6, _x7, _x8) { return _mutate.apply(this, arguments); } return mutate; }() }, { key: "update", value: function () { var _update2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(key, obj, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: return _context5.abrupt("return", this.mutate(key, function (remote) { return Object.assign(remote, obj); }, itemMetadataUpdates)); case 1: case "end": return _context5.stop(); } } }, _callee5, this); })); function update(_x9, _x10, _x11) { return _update2.apply(this, arguments); } return update; }() }, { key: "_putItemUnconditionally", value: function () { var _putItemUnconditionally2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(key, data, ttl) { var result, item; return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return this._putItemToServer(key, data, undefined, ttl); case 2: result = _context6.sent; item = result.item; this._handleItemMutated(item.key, item.url, item.last_event_id, item.revision, item.data, item.date_updated, item.date_expires, result.added, false); return _context6.abrupt("return", this.cache.get(item.key)); case 6: case "end": return _context6.stop(); } } }, _callee6, this); })); function _putItemUnconditionally(_x12, _x13, _x14) { return _putItemUnconditionally2.apply(this, arguments); } return _putItemUnconditionally; }() }, { key: "_putItemWithIfMatch", value: function () { var _putItemWithIfMatch2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee7(key, mutatorFunction, ttl) { var currentItem, data, ifMatch, result, item; return _regeneratorRuntime__default['default'].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return this.get(key).catch(function (error) { if (error.status === 404) { // PUT /Items/myKey with `If-Match: -1` acts as "put if not exists" return new SyncMapItem({ key: key, data: {}, last_event_id: -1, revision: '-1', url: null, date_updated: null, date_expires: null }); } else { throw error; } }); case 2: currentItem = _context7.sent; data = mutatorFunction(deepClone(currentItem.data)); if (!data) { _context7.next = 26; break; } ifMatch = currentItem.revision; _context7.prev = 6; _context7.next = 9; return this._putItemToServer(key, data, ifMatch, ttl); case 9: result = _context7.sent; item = result.item; this._handleItemMutated(item.key, item.url, item.last_event_id, item.revision, item.data, item.date_updated, item.date_expires, result.added, false); return _context7.abrupt("return", this.cache.get(item.key)); case 15: _context7.prev = 15; _context7.t0 = _context7["catch"](6); if (!(_context7.t0.status === 412)) { _context7.next = 23; break; } _context7.next = 20; return this._getItemFromServer(key); case 20: return _context7.abrupt("return", this._putItemWithIfMatch(key, mutatorFunction, ttl)); case 23: throw _context7.t0; case 24: _context7.next = 27; break; case 26: return _context7.abrupt("return", currentItem); case 27: case "end": return _context7.stop(); } } }, _callee7, this, [[6, 15]]); })); function _putItemWithIfMatch(_x15, _x16, _x17) { return _putItemWithIfMatch2.apply(this, arguments); } return _putItemWithIfMatch; }() }, { key: "_putItemToServer", value: function () { var _putItemToServer2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee8(key, data, ifMatch, ttl) { var url, requestBody, response, mapItemDescriptor, added; return _regeneratorRuntime__default['default'].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: url = new UriBuilder(this.links.items).pathSegment(key).build(); requestBody = { data: data }; if (ttl !== undefined) { requestBody.ttl = ttl; } _context8.prev = 3; _context8.next = 6; return this.services.network.put(url, requestBody, ifMatch); case 6: response = _context8.sent; mapItemDescriptor = response.body; mapItemDescriptor.data = data; // The server does not return the data in the response mapItemDescriptor.date_updated = new Date(mapItemDescriptor.date_updated); added = response.status.code === 201; return _context8.abrupt("return", { added: added, item: mapItemDescriptor }); case 14: _context8.prev = 14; _context8.t0 = _context8["catch"](3); if (_context8.t0.status === 404) { this.onRemoved(false); } throw _context8.t0; case 18: case "end": return _context8.stop(); } } }, _callee8, this, [[3, 14]]); })); function _putItemToServer(_x18, _x19, _x20, _x21) { return _putItemToServer2.apply(this, arguments); } return _putItemToServer; }() }, { key: "remove", value: function () { var _remove = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee9(key) { var item, previousItemData, response; return _regeneratorRuntime__default['default'].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return this.get(key); case 2: item = _context9.sent; previousItemData = deepClone(item.data); _context9.next = 6; return this.services.network.delete(item.uri); case 6: response = _context9.sent; this._handleItemRemoved(key, response.body.last_event_id, previousItemData, new Date(response.body.date_updated), false); case 8: case "end": return _context9.stop(); } } }, _callee9, this); })); function remove(_x22) { return _remove.apply(this, arguments); } return remove; }() /** * @private */ }, { key: "queryItems", value: function () { var _queryItems = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee10(args) { var _this4 = this; var uri, response, items, meta; return _regeneratorRuntime__default['default'].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: args = args || {}; uri = new UriBuilder(this.links.items).queryParam('From', args.from).queryParam('PageSize', args.limit).queryParam('Key', args.key).queryParam('PageToken', args.pageToken).queryParam('Order', args.order).build(); _context10.next = 4; return this.services.network.get(uri); case 4: response = _context10.sent; items = response.body.items.map(function (el) { el.date_updated = new Date(el.date_updated); var itemInCache = _this4.cache.get(el.key); if (itemInCache) { _this4._handleItemMutated(el.key, el.url, el.last_event_id, el.revision, el.data, el.date_updated, el.date_expires, false, true); } else { _this4.cache.store(el.key, new SyncMapItem(el), el.last_event_id); } return _this4.cache.get(el.key); }); meta = response.body.meta; return _context10.abrupt("return", new Paginator(items, function (pageToken) { return _this4.queryItems({ pageToken: pageToken }); }, meta.previous_token, meta.next_token)); case 8: case "end": return _context10.stop(); } } }, _callee10, this); })); function queryItems(_x23) { return _queryItems.apply(this, arguments); } return queryItems; }() }, { key: "getItems", value: function () { var _getItems = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee11(args) { return _regeneratorRuntime__default['default'].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: args = args || {}; validatePageSize(args.pageSize); args.limit = args.pageSize || args.limit || 50; args.order = args.order || 'asc'; return _context11.abrupt("return", this.queryItems(args)); case 5: case "end": return _context11.stop(); } } }, _callee11, this); })); function getItems(_x24) { return _getItems.apply(this, arguments); } return getItems; }() }, { key: "shouldIgnoreEvent", value: function shouldIgnoreEvent(key, eventId) { return this.cache.isKnown(key, eventId); } /** * Handle update from the server * @private */ }, { key: "_update", value: function _update(update, isStrictlyOrdered) { update.date_created = new Date(update.date_created); switch (update.type) { case 'map_item_added': case 'map_item_updated': { this._handleItemMutated(update.item_key, update.item_url, update.id, update.item_revision, update.item_data, update.date_created, undefined, // orchestration events do not include date_expires update.type === 'map_item_added', true); } break; case 'map_item_removed': { this._handleItemRemoved(update.item_key, update.id, update.item_data, update.date_created, true); } break; case 'map_removed': { this.onRemoved(false); } break; } if (isStrictlyOrdered) { this._advanceLastEventId(update.id, update.map_revision); } } }, { key: "_advanceLastEventId", value: function _advanceLastEventId(eventId, revision) { if (this.lastEventId < eventId) { this.descriptor.last_event_id = eventId; if (revision) { this.descriptor.revision = revision; } } } }, { key: "_updateRootDateUpdated", value: function _updateRootDateUpdated(dateUpdated) { if (!this.descriptor.date_updated || dateUpdated.getTime() > this.descriptor.date_updated.getTime()) { this.descriptor.date_updated = dateUpdated; this.services.storage.update(this.type, this.sid, this.uniqueName, { date_updated: dateUpdated }); } } }, { key: "_handleItemMutated", value: function _handleItemMutated(key, url, lastEventId, revision, data, dateUpdated, dateExpires, added, remote) { if (this.shouldIgnoreEvent(key, lastEventId)) { log$1$1.trace('SyncMapItem ', key, ' update skipped, current:', this.lastEventId, ', remote:', lastEventId); return; } this._updateRootDateUpdated(dateUpdated); var item = this.cache.get(key); if (!item) { var newItem = new SyncMapItem({ key: key, url: url, last_event_id: lastEventId, revision: revision, data: data, date_updated: dateUpdated, date_expires: dateExpires }); this.cache.store(key, newItem, lastEventId); this.emitItemMutationEvent(newItem, remote, added); return; } var previousItemData = deepClone(item.data); item.update(lastEventId, revision, data, dateUpdated); this.cache.store(key, item, lastEventId); if (dateExpires !== undefined) { item.updateDateExpires(dateExpires); } this.emitItemMutationEvent(item, remote, false, previousItemData); } }, { key: "emitItemMutationEvent", value: function emitItemMutationEvent(item, remote, added) { var previousItemData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var eventName = added ? 'itemAdded' : 'itemUpdated'; var args = { item: item, isLocal: !remote }; if (!added) { args.previousItemData = previousItemData; } this.broadcastEventToListeners(eventName, args); } /** * @private */ }, { key: "_handleItemRemoved", value: function _handleItemRemoved(key, eventId, oldData, dateUpdated, remote) { this._updateRootDateUpdated(dateUpdated); this.cache.delete(key, eventId); this.broadcastEventToListeners('itemRemoved', { key: key, isLocal: !remote, previousItemData: oldData }); } }, { key: "onRemoved", value: function onRemoved(locally) { this._unsubscribe(); this.removalHandler(this.type, this.sid, this.uniqueName); this.broadcastEventToListeners('removed', { isLocal: locally }); } }, { key: "setTtl", value: function () { var _setTtl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee12(ttl) { var requestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.prev = 0; requestBody = { ttl: ttl }; _context12.next = 4; return this.services.network.post(this.uri, requestBody); case 4: response = _context12.sent; this.descriptor.date_expires = response.body.date_expires; _context12.next = 12; break; case 8: _context12.prev = 8; _context12.t0 = _context12["catch"](0); if (_context12.t0.status === 404) { this.onRemoved(false); } throw _context12.t0; case 12: case "end": return _context12.stop(); } } }, _callee12, this, [[0, 8]]); })); function setTtl(_x25) { return _setTtl.apply(this, arguments); } return setTtl; }() }, { key: "setItemTtl", value: function () { var _setItemTtl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee13(key, ttl) { var existingItem, requestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: _context13.next = 2; return this.get(key); case 2: existingItem = _context13.sent; requestBody = { ttl: ttl }; _context13.next = 6; return this.services.network.post(existingItem.uri, requestBody); case 6: response = _context13.sent; existingItem.updateDateExpires(response.body.date_expires); case 8: case "end": return _context13.stop(); } } }, _callee13, this); })); function setItemTtl(_x26, _x27) { return _setItemTtl.apply(this, arguments); } return setItemTtl; }() }, { key: "removeMap", value: function () { var _removeMap = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee14() { return _regeneratorRuntime__default['default'].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return this.services.network.delete(this.uri); case 2: this.onRemoved(true); case 3: case "end": return _context14.stop(); } } }, _callee14, this); })); function removeMap() { return _removeMap.apply(this, arguments); } return removeMap; }() }], [{ key: "type", get: function get() { return 'map'; } }]); return SyncMapImpl; }(SyncEntity); /** * Represents a Sync map, which is a data structure that stores an unordered set of key-value pairs. * Use the {@link SyncClient.map} method to obtain a reference to a Sync map. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ var SyncMap = /*#__PURE__*/function (_Closeable) { _inherits__default['default'](SyncMap, _Closeable); var _super2 = _createSuper$3$1(SyncMap); /** * @internal */ function SyncMap(syncMapImpl) { var _this5; _classCallCheck__default['default'](this, SyncMap); _this5 = _super2.call(this); _this5.syncMapImpl = syncMapImpl; _this5.syncMapImpl.attach(_assertThisInitialized__default['default'](_this5)); return _this5; } /** * Fired when a new item appears in the map, regardless of whether its creator was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncMapItem} `item` - added item * * boolean `isLocal` - equals true if the item was added by a local actor, false otherwise * @example * ```typescript * map.on('itemAdded', (args) => { * console.log(`Map item ${args.item.key} was added`); * console.log('args.item.data:', args.item.data); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ _createClass__default['default'](SyncMap, [{ key: "uri", get: // private props function get() { return this.syncMapImpl.uri; } }, { key: "links", get: function get() { return this.syncMapImpl.links; } }, { key: "revision", get: function get() { return this.syncMapImpl.revision; } }, { key: "lastEventId", get: function get() { return this.syncMapImpl.lastEventId; } }, { key: "dateExpires", get: function get() { return this.syncMapImpl.dateExpires; } }, { key: "type", get: function get() { return SyncMapImpl.type; } /** * An immutable identifier (a SID) assigned by the system on creation. */ }, { key: "sid", get: function get() { return this.syncMapImpl.sid; } /** * An optional immutable identifier that may be assigned by the * programmer to this map on creation. Unique among other Maps. */ }, { key: "uniqueName", get: function get() { return this.syncMapImpl.uniqueName; } /** * Date when the map was last updated. */ }, { key: "dateUpdated", get: function get() { return this.syncMapImpl.dateUpdated; } }, { key: "set", value: /** * Add a new item to the map with the given key-value pair. Overwrites any data that might already exist with that key. * @param key Unique item identifier. * @param data Data to be set. * @param itemMetadataUpdates New item metadata. * @return Newly added item, or modified one if already exists, with the latest known data. * @example * ```typescript * map.set('myKey', { name: 'John Smith' }, { ttl: 86400 }) * .then((item) => { * console.log('Map SyncMapItem set() successful, item data:', item.data); * }) * .catch((error) => { * console.error('Map SyncMapItem set() failed', error); * }); * ``` */ function () { var _set2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee15(key, data, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: this.ensureNotClosed(); return _context15.abrupt("return", this.syncMapImpl.set(key, data, itemMetadataUpdates)); case 2: case "end": return _context15.stop(); } } }, _callee15, this); })); function set(_x28, _x29, _x30) { return _set2.apply(this, arguments); } return set; }() /** * Retrieve an item by key. * @param key Identifies the desired item. * @return A promise that resolves when the item has been fetched. * This promise will be rejected if item was not found. * @example * ```typescript * map.get('myKey') * .then((item) => { * console.log('Map SyncMapItem get() successful, item data:', item.data) * }) * .catch((error) => { * console.error('Map SyncMapItem get() failed', error); * }); * ``` */ }, { key: "get", value: function () { var _get3 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee16(key) { return _regeneratorRuntime__default['default'].wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: this.ensureNotClosed(); return _context16.abrupt("return", this.syncMapImpl.get(key)); case 2: case "end": return _context16.stop(); } } }, _callee16, this); })); function get(_x31) { return _get3.apply(this, arguments); } return get; }() /** * Schedules a modification to this Map SyncMapItem that will apply a mutation function. * If no SyncMapItem with the given key exists, it will first be created, having the default data (`{}`). * @param key Selects the map item to be mutated. * @param mutator A function that outputs a new data based on the existing data. * May be called multiple times, particularly if this Map SyncMapItem is modified concurrently by remote code. * If the mutation ultimately succeeds, the Map SyncMapItem will have made the particular transition described * by this function. * @param itemMetadataUpdates New item metadata. * @return Resolves with the most recent item state, the output of a successful * mutation or a state that prompted graceful cancellation (mutator returned `null`). * @example * ```typescript * const mutatorFunction = (currentData) => { * currentData.viewCount = (currentData.viewCount || 0) + 1; * return currentData; * }; * map.mutate('myKey', mutatorFunction, { ttl: 86400 }) * .then((item) => { * console.log('Map SyncMapItem mutate() successful, new data:', item.data) * }) * .catch((error) => { * console.error('Map SyncMapItem mutate() failed', error); * }); * ``` */ }, { key: "mutate", value: function () { var _mutate2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee17(key, mutator, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: this.ensureNotClosed(); return _context17.abrupt("return", this.syncMapImpl.mutate(key, mutator, itemMetadataUpdates)); case 2: case "end": return _context17.stop(); } } }, _callee17, this); })); function mutate(_x32, _x33, _x34) { return _mutate2.apply(this, arguments); } return mutate; }() /** * Modify a map item by appending new fields (or by overwriting existing ones) with the values from * the provided Object. Creates a new item if no item by this key exists, copying all given fields and values * into it. * This is equivalent to * ```typescript * map.mutate('myKey', (currentData) => Object.assign(currentData, obj)); * ``` * @param key Selects the map item to update. * @param obj Specifies the particular (top-level) attributes that will receive new values. * @param itemMetadataUpdates New item metadata. * @return A promise resolving to the modified item in its new state. * @example * ```typescript * // Say, the Map SyncMapItem (key: `'myKey'`) data is `{ name: 'John Smith' }` * map.update('myKey', { age: 34 }, { ttl: 86400 }) * .then((item) => { * // Now the Map SyncMapItem data is `{ name: 'John Smith', age: 34 }` * console.log('Map SyncMapItem update() successful, new data:', item.data); * }) * .catch((error) => { * console.error('Map SyncMapItem update() failed', error); * }); * ``` */ }, { key: "update", value: function () { var _update3 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee18(key, obj, itemMetadataUpdates) { return _regeneratorRuntime__default['default'].wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: this.ensureNotClosed(); return _context18.abrupt("return", this.syncMapImpl.update(key, obj, itemMetadataUpdates)); case 2: case "end": return _context18.stop(); } } }, _callee18, this); })); function update(_x35, _x36, _x37) { return _update3.apply(this, arguments); } return update; }() /** * Delete an item, given its key. * @param key Selects the item to delete. * @return A promise to remove an item. * The promise will be rejected if 'key' is undefined or an item was not found. * @example * ```typescript * map.remove('myKey') * .then(() => { * console.log('Map SyncMapItem remove() successful'); * }) * .catch((error) => { * console.error('Map SyncMapItem remove() failed', error); * }); * ``` */ }, { key: "remove", value: function () { var _remove2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee19(key) { return _regeneratorRuntime__default['default'].wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: this.ensureNotClosed(); return _context19.abrupt("return", this.syncMapImpl.remove(key)); case 2: case "end": return _context19.stop(); } } }, _callee19, this); })); function remove(_x38) { return _remove2.apply(this, arguments); } return remove; }() /** * Get a complete list of items from the map. * Information about the query limits can be found [here](https://www.twilio.com/docs/sync/limits). * @param queryOptions Query options. * @example * ```typescript * const pageHandler = (paginator) => { * paginator.items.forEach((item) => { * console.log(`SyncMapItem ${item.key}: `, item.data); * }); * return paginator.hasNextPage * ? paginator.nextPage().then(pageHandler) * : null; * }; * map.getItems({ from: 'myKey', order: 'asc' }) * .then(pageHandler) * .catch((error) => { * console.error('Map getItems() failed', error); * }); * ``` */ }, { key: "getItems", value: function () { var _getItems2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee20(queryOptions) { return _regeneratorRuntime__default['default'].wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: this.ensureNotClosed(); return _context20.abrupt("return", this.syncMapImpl.getItems(queryOptions)); case 2: case "end": return _context20.stop(); } } }, _callee20, this); })); function getItems(_x39) { return _getItems2.apply(this, arguments); } return getItems; }() /** * Update the time-to-live of the map. * @param ttl Specifies the TTL in seconds after which the map is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * map.setTtl(3600) * .then(() => { * console.log('Map setTtl() successful'); * }) * .catch((error) => { * console.error('Map setTtl() failed', error); * }); * ``` */ }, { key: "setTtl", value: function () { var _setTtl2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee21(ttl) { return _regeneratorRuntime__default['default'].wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: this.ensureNotClosed(); return _context21.abrupt("return", this.syncMapImpl.setTtl(ttl)); case 2: case "end": return _context21.stop(); } } }, _callee21, this); })); function setTtl(_x40) { return _setTtl2.apply(this, arguments); } return setTtl; }() /** * Update the time-to-live of a map item. * @param key SyncMapItem key. * @param ttl Specifies the TTL in seconds after which the map item is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * map.setItemTtl('myKey', 86400) * .then(() => { * console.log('Map setItemTtl() successful'); * }) * .catch((error) => { * console.error('Map setItemTtl() failed', error); * }); * ``` */ }, { key: "setItemTtl", value: function () { var _setItemTtl2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee22(key, ttl) { return _regeneratorRuntime__default['default'].wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: this.ensureNotClosed(); return _context22.abrupt("return", this.syncMapImpl.setItemTtl(key, ttl)); case 2: case "end": return _context22.stop(); } } }, _callee22, this); })); function setItemTtl(_x41, _x42) { return _setItemTtl2.apply(this, arguments); } return setItemTtl; }() /** * Delete this map. It will be impossible to restore it. * @return A promise that resolves when the map has been deleted. * @example * ```typescript * map.removeMap() * .then(() => { * console.log('Map removeMap() successful'); * }) * .catch((error) => { * console.error('Map removeMap() failed', error); * }); * ``` */ }, { key: "removeMap", value: function () { var _removeMap2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee23() { return _regeneratorRuntime__default['default'].wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: this.ensureNotClosed(); _context23.next = 3; return this.syncMapImpl.removeMap(); case 3: case "end": return _context23.stop(); } } }, _callee23, this); })); function removeMap() { return _removeMap2.apply(this, arguments); } return removeMap; }() /** * Conclude work with the map instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this map will continue operating and receiving events normally. * @example * ```typescript * map.close(); * ```` */ }, { key: "close", value: function close() { _get__default['default'](_getPrototypeOf__default['default'](SyncMap.prototype), "close", this).call(this); this.syncMapImpl.detach(this.listenerUuid); } }], [{ key: "type", get: function get() { return SyncMapImpl.type; } }]); return SyncMap; }(Closeable); _defineProperty__default['default'](SyncMap, "itemAdded", 'itemAdded'); _defineProperty__default['default'](SyncMap, "itemUpdated", 'itemUpdated'); _defineProperty__default['default'](SyncMap, "itemRemoved", 'itemRemoved'); _defineProperty__default['default'](SyncMap, "removed", 'removed'); __decorate([declarativeTypeValidator.validateTypesAsync('string', declarativeTypeValidator.pureObject, ['undefined', declarativeTypeValidator.objectSchema('item metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object]), __metadata("design:returntype", Promise)], SyncMap.prototype, "set", null); __decorate([declarativeTypeValidator.validateTypesAsync('string'), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], SyncMap.prototype, "get", null); __decorate([declarativeTypeValidator.validateTypesAsync('string', 'function', ['undefined', declarativeTypeValidator.objectSchema('item metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Function, Object]), __metadata("design:returntype", Promise)], SyncMap.prototype, "mutate", null); __decorate([declarativeTypeValidator.validateTypesAsync('string', declarativeTypeValidator.pureObject, ['undefined', declarativeTypeValidator.objectSchema('item metadata', { ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object]), __metadata("design:returntype", Promise)], SyncMap.prototype, "update", null); __decorate([declarativeTypeValidator.validateTypesAsync('string'), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], SyncMap.prototype, "remove", null); __decorate([declarativeTypeValidator.validateTypesAsync(['undefined', declarativeTypeValidator.objectSchema('query options', { from: ['string', 'undefined'], pageSize: [declarativeTypeValidator.custom(function (value) { return [isPositiveInteger(value), 'a positive integer']; }), 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], SyncMap.prototype, "getItems", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", Promise)], SyncMap.prototype, "setTtl", null); __decorate([declarativeTypeValidator.validateTypesAsync('string', declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Number]), __metadata("design:returntype", Promise)], SyncMap.prototype, "setItemTtl", null); function _createSuper$2$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$2$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var SyncStreamImpl = /*#__PURE__*/function (_SyncEntity) { _inherits__default['default'](SyncStreamImpl, _SyncEntity); var _super = _createSuper$2$1(SyncStreamImpl); /** * @internal */ function SyncStreamImpl(services, descriptor, removalHandler) { var _this; _classCallCheck__default['default'](this, SyncStreamImpl); _this = _super.call(this, services, removalHandler); _this.descriptor = descriptor; return _this; } // private props _createClass__default['default'](SyncStreamImpl, [{ key: "uri", get: function get() { return this.descriptor.url; } }, { key: "links", get: function get() { return this.descriptor.links; } }, { key: "dateExpires", get: function get() { return this.descriptor.date_expires; } }, { key: "type", get: function get() { return 'stream'; } }, { key: "lastEventId", get: function get() { return null; } // below properties are specific to Insights only }, { key: "indexName", get: function get() { return undefined; } }, { key: "queryString", get: function get() { return undefined; } // public props, documented along with class description }, { key: "sid", get: function get() { return this.descriptor.sid; } }, { key: "uniqueName", get: function get() { return this.descriptor.unique_name || null; } }, { key: "publishMessage", value: function () { var _publishMessage = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(data) { var requestBody, response, responseBody, event; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: requestBody = { data: data }; _context.next = 3; return this.services.network.post(this.links.messages, requestBody); case 3: response = _context.sent; responseBody = response.body; event = this._handleMessagePublished(responseBody.sid, data, false); return _context.abrupt("return", event); case 7: case "end": return _context.stop(); } } }, _callee, this); })); function publishMessage(_x) { return _publishMessage.apply(this, arguments); } return publishMessage; }() }, { key: "setTtl", value: function () { var _setTtl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(ttl) { var requestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; requestBody = { ttl: ttl }; _context2.next = 4; return this.services.network.post(this.uri, requestBody); case 4: response = _context2.sent; this.descriptor.date_expires = response.body.date_expires; _context2.next = 12; break; case 8: _context2.prev = 8; _context2.t0 = _context2["catch"](0); if (_context2.t0.status === 404) { this.onRemoved(false); } throw _context2.t0; case 12: case "end": return _context2.stop(); } } }, _callee2, this, [[0, 8]]); })); function setTtl(_x2) { return _setTtl.apply(this, arguments); } return setTtl; }() }, { key: "removeStream", value: function () { var _removeStream = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3() { return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.services.network.delete(this.uri); case 2: this.onRemoved(true); case 3: case "end": return _context3.stop(); } } }, _callee3, this); })); function removeStream() { return _removeStream.apply(this, arguments); } return removeStream; }() /** * Handle event from the server * @private */ }, { key: "_update", value: function _update(update) { switch (update.type) { case 'stream_message_published': { this._handleMessagePublished(update.message_sid, update.message_data, true); break; } case 'stream_removed': { this.onRemoved(false); break; } } } }, { key: "_handleMessagePublished", value: function _handleMessagePublished(sid, data, remote) { var event = { sid: sid, data: data }; this.broadcastEventToListeners('messagePublished', { message: event, isLocal: !remote }); return event; } }, { key: "onRemoved", value: function onRemoved(isLocal) { this._unsubscribe(); this.removalHandler(this.type, this.sid, this.uniqueName); this.broadcastEventToListeners('removed', { isLocal: isLocal }); } }], [{ key: "type", get: function get() { return 'stream'; } }]); return SyncStreamImpl; }(SyncEntity); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.pureObject), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], SyncStreamImpl.prototype, "publishMessage", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", Promise)], SyncStreamImpl.prototype, "setTtl", null); /** * A Sync primitive for pub-sub messaging. Stream Messages are not persisted, exist * only in transit, and will be dropped if (due to congestion or network anomalies) they * cannot be delivered promptly. Use the {@link SyncClient.stream} method to obtain a reference to a Sync Message Stream. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ var SyncStream = /*#__PURE__*/function (_Closeable) { _inherits__default['default'](SyncStream, _Closeable); var _super2 = _createSuper$2$1(SyncStream); /** * @internal */ function SyncStream(syncStreamImpl) { var _this2; _classCallCheck__default['default'](this, SyncStream); _this2 = _super2.call(this); _this2.syncStreamImpl = syncStreamImpl; _this2.syncStreamImpl.attach(_assertThisInitialized__default['default'](_this2)); return _this2; } /** * Fired when a message is published to the stream either locally or by a remote actor. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncStreamMessage} `message` - Published message * * boolean `isLocal` - equals true if the message was published by a local actor, false otherwise * @example * ```typescript * stream.on('messagePublished', (args) => { * console.log('Stream message published'); * console.log('Message SID:', args.message.sid); * console.log('Message data: ', args.message.data); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ _createClass__default['default'](SyncStream, [{ key: "uri", get: // private props function get() { return this.syncStreamImpl.uri; } }, { key: "links", get: function get() { return this.syncStreamImpl.links; } }, { key: "dateExpires", get: function get() { return this.syncStreamImpl.dateExpires; } }, { key: "type", get: function get() { return SyncStreamImpl.type; } }, { key: "lastEventId", get: function get() { return null; } /** * The immutable system-assigned identifier of this stream. Never null. */ }, { key: "sid", get: function get() { return this.syncStreamImpl.sid; } /** * A unique identifier optionally assigned to the stream on creation. */ }, { key: "uniqueName", get: function get() { return this.syncStreamImpl.uniqueName; } }, { key: "publishMessage", value: /** * Publish a message to the stream. The system will attempt delivery to all online subscribers. * @param data The body of the dispatched message. Maximum size in serialized JSON: 4KB. * A rate limit applies to this operation, refer to the [Sync API documentation](https://www.twilio.com/docs/api/sync) for details. * @return A promise which resolves after the message is successfully published * to the Sync service. Resolves irrespective of ultimate delivery to any subscribers. * @example * ```typescript * stream.publishMessage({ x: 42, y: 123 }) * .then((message) => { * console.log('Stream publishMessage() successful, message SID:', message.sid); * }) * .catch((error) => { * console.error('Stream publishMessage() failed', error); * }); * ``` */ function () { var _publishMessage2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4(data) { return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: this.ensureNotClosed(); return _context4.abrupt("return", this.syncStreamImpl.publishMessage(data)); case 2: case "end": return _context4.stop(); } } }, _callee4, this); })); function publishMessage(_x3) { return _publishMessage2.apply(this, arguments); } return publishMessage; }() /** * Update the time-to-live of the stream. * @param ttl Specifies the TTL in seconds after which the stream is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * stream.setTtl(3600) * .then(() => { * console.log('Stream setTtl() successful'); * }) * .catch((error) => { * console.error('Stream setTtl() failed', error); * }); * ``` */ }, { key: "setTtl", value: function () { var _setTtl2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(ttl) { return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: this.ensureNotClosed(); return _context5.abrupt("return", this.syncStreamImpl.setTtl(ttl)); case 2: case "end": return _context5.stop(); } } }, _callee5, this); })); function setTtl(_x4) { return _setTtl2.apply(this, arguments); } return setTtl; }() /** * Permanently delete this Stream. * @return A promise which resolves after the Stream is successfully deleted. * @example * ```typescript * stream.removeStream() * .then(() => { * console.log('Stream removeStream() successful'); * }) * .catch((error) => { * console.error('Stream removeStream() failed', error); * }); * ``` */ }, { key: "removeStream", value: function () { var _removeStream2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6() { return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: this.ensureNotClosed(); return _context6.abrupt("return", this.syncStreamImpl.removeStream()); case 2: case "end": return _context6.stop(); } } }, _callee6, this); })); function removeStream() { return _removeStream2.apply(this, arguments); } return removeStream; }() /** * Conclude work with the stream instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this stream will continue operating and receiving events normally. * @example * ```typescript * stream.close(); * ``` */ }, { key: "close", value: function close() { _get__default['default'](_getPrototypeOf__default['default'](SyncStream.prototype), "close", this).call(this); this.syncStreamImpl.detach(this.listenerUuid); } }], [{ key: "type", get: function get() { return SyncStreamImpl.type; } }]); return SyncStream; }(Closeable); _defineProperty__default['default'](SyncStream, "messagePublished", 'messagePublished'); _defineProperty__default['default'](SyncStream, "removed", 'removed'); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.pureObject), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], SyncStream.prototype, "publishMessage", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", Promise)], SyncStream.prototype, "setTtl", null); var ClientInfo = function ClientInfo(version) { _classCallCheck__default['default'](this, ClientInfo); this.sdk = 'js'; this.sdkVer = version; this.os = platform__namespace.os.family; this.osVer = platform__namespace.os.version; this.pl = platform__namespace.name; this.plVer = platform__namespace.version; }; /** * Container for entities which are known by the client * It's needed for deduplication when client obtain the same object several times */ var EntitiesCache = /*#__PURE__*/function () { function EntitiesCache() { _classCallCheck__default['default'](this, EntitiesCache); this.names = new Map(); this.entities = new Map(); } _createClass__default['default'](EntitiesCache, [{ key: "store", value: function store(entity) { var stored = this.entities.get(entity.sid); if (stored) { return stored; } this.entities.set(entity.sid, entity); if (entity.uniqueName) { this.names.set(entity.type + '::' + entity.uniqueName, entity.sid); } return entity; } }, { key: "getResolved", value: function getResolved(id, type) { var resolvedSid = this.names.get(type + '::' + id); return resolvedSid ? this.entities.get(resolvedSid) : null; } }, { key: "get", value: function get(id, type) { return this.entities.get(id) || this.getResolved(id, type) || null; } }, { key: "remove", value: function remove(sid) { var cached = this.entities.get(sid); if (cached) { this.entities.delete(sid); if (cached.uniqueName) { this.names.delete(cached.type + '::' + cached.uniqueName); } } } }]); return EntitiesCache; }(); function _createSuper$1$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$1$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * An individual result from a LiveQuery or InstantQuery result set. */ var InsightsItem = /** * @internal */ function InsightsItem() { _classCallCheck__default['default'](this, InsightsItem); } /** * The identifier that maps to this item within the search result. */ ; var LiveQueryImpl = /*#__PURE__*/function (_SyncEntity) { _inherits__default['default'](LiveQueryImpl, _SyncEntity); var _super = _createSuper$1$1(LiveQueryImpl); function LiveQueryImpl(descriptor, services, removalHandler, items) { var _this; _classCallCheck__default['default'](this, LiveQueryImpl); _this = _super.call(this, services, removalHandler); _this.descriptor = descriptor; _this.cache = new Cache(); if (items) { items.forEach(function (item) { _this.cache.store(item.key, { key: item.key, value: item.data }, item.revision); }); } return _this; } // public _createClass__default['default'](LiveQueryImpl, [{ key: "sid", get: function get() { return this.descriptor.sid; } // private extension of SyncEntity }, { key: "uniqueName", get: function get() { return null; } }, { key: "type", get: function get() { return LiveQueryImpl.type; } }, { key: "lastEventId", get: function get() { return this.descriptor.last_event_id; } }, { key: "indexName", get: function get() { return this.descriptor.indexName; } }, { key: "queryString", get: function get() { return this.descriptor.queryExpression; } // custom private props }, { key: "queryUri", get: function get() { return this.descriptor.queryUri; } }, { key: "liveQueryDescriptor", get: function get() { return this.descriptor; } // dummy stub from iface }, { key: "onRemoved", value: function onRemoved() {} }, { key: "getItems", value: function getItems() { var dataByKey = {}; this.cache.forEach(function (key, item) { dataByKey[key] = item.value; }); return dataByKey; } /** * @internal */ }, { key: "_update", value: function _update(message, isStrictlyOrdered) { switch (message.type) { case 'live_query_item_updated': this.handleItemMutated(message.item_key, message.item_data, message.item_revision); break; case 'live_query_item_removed': this.handleItemRemoved(message.item_key, message.item_revision); break; case 'live_query_updated': this.handleBatchUpdate(message.items); break; } if (isStrictlyOrdered) { this._advanceLastEventId(message.last_event_id); } } }, { key: "handleItemMutated", value: function handleItemMutated(key, value, revision) { if (this.shouldIgnoreEvent(key, revision)) { log$1$1.trace("Item ".concat(key, " update skipped, revision: ").concat(revision)); } else { var newItem = { key: key, value: value }; this.cache.store(key, newItem, revision); this.broadcastEventToListeners('itemUpdated', newItem); } } }, { key: "handleItemRemoved", value: function handleItemRemoved(key, revision) { var force = revision === null; if (this.shouldIgnoreEvent(key, revision)) { log$1$1.trace("Item ".concat(key, " delete skipped, revision: ").concat(revision)); } else { this.cache.delete(key, revision, force); this.broadcastEventToListeners('itemRemoved', { key: key }); } } }, { key: "handleBatchUpdate", value: function handleBatchUpdate(items) { var _this2 = this; // preprocess item set for easy key-based access (it's a one-time constant time operation) var newItems = {}; if (items != null) { items.forEach(function (item) { newItems[item.key] = { data: item.data, revision: item.revision }; }); } // go through existing items and generate update/remove events for them this.cache.forEach(function (key, item) { var newItem = newItems[key]; if (newItem != null) { _this2.handleItemMutated(key, newItem.data, newItem.revision); } else { _this2.handleItemRemoved(key, null); // force deletion w/o revision } // once item is handled, remove it from incoming array delete newItems[key]; }); // once we handled all the known items, handle remaining pack for (var key in newItems) { this.handleItemMutated(key, newItems[key].data, newItems[key].revision); } } }, { key: "shouldIgnoreEvent", value: function shouldIgnoreEvent(key, eventId) { return key != null && eventId != null && this.cache.isKnown(key, eventId); } /** * @internal */ }, { key: "_advanceLastEventId", value: function _advanceLastEventId(eventId, revision) { // LiveQuery is not revisioned in any way, so simply ignore second param and act upon lastEventId only if (this.lastEventId < eventId) { this.descriptor.last_event_id = eventId; } } }], [{ key: "type", get: function get() { return 'live_query'; } }]); return LiveQueryImpl; }(SyncEntity); function queryItems(_x) { return _queryItems.apply(this, arguments); } /** * Represents a long-running query against Flex data wherein the returned result set * subsequently receives pushed updates whenever new (or updated) records would match the * given expression. Updated results are presented row-by-row until this query is explicitly * closed. * * Use the {@link SyncClient.liveQuery} method to create a live query. */ function _queryItems() { _queryItems = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(params) { var network, queryString, uri, type, liveQueryRequestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: network = params.network, queryString = params.queryString, uri = params.uri, type = params.type; if (!(queryString == null)) { _context3.next = 3; break; } throw new SyncError("Invalid query", 400, 54507); case 3: liveQueryRequestBody = { query_string: queryString // raw query string (like `key == "value" AND key2 != "value2"`) }; if (type === LiveQuery.type) { liveQueryRequestBody.type = type; } _context3.next = 7; return network.post(uri, liveQueryRequestBody, undefined, true); case 7: response = _context3.sent; return _context3.abrupt("return", response.body); case 9: case "end": return _context3.stop(); } } }, _callee3); })); return _queryItems.apply(this, arguments); } var LiveQuery = /*#__PURE__*/function (_Closeable) { _inherits__default['default'](LiveQuery, _Closeable); var _super2 = _createSuper$1$1(LiveQuery); /** * @internal */ function LiveQuery(liveQueryImpl) { var _this3; _classCallCheck__default['default'](this, LiveQuery); _this3 = _super2.call(this); _this3.liveQueryImpl = liveQueryImpl; _this3.liveQueryImpl.attach(_assertThisInitialized__default['default'](_this3)); return _this3; } /** * Fired when an item has been added or updated. * * Parameters: * 1. {@link InsightsItem} `item` - updated item * @example * ```typescript * liveQuery.on('itemUpdated', (item) => { * console.log(`Item ${item.key} was updated`'`); * console.log('Item value:', item.value); * }); * ``` * @event */ _createClass__default['default'](LiveQuery, [{ key: "type", get: function get() { return LiveQueryImpl.type; } }, { key: "lastEventId", get: function get() { return this.liveQueryImpl.lastEventId; } /** * The immutable identifier of this query object, assigned by the system. */ }, { key: "sid", get: function get() { return this.liveQueryImpl.sid; } }, { key: "close", value: /** * Closes this query instance and unsubscribes from further service events. * This will eventually stop the physical inflow of updates over the network, when all other instances of this query are closed as well. */ function close() { _get__default['default'](_getPrototypeOf__default['default'](LiveQuery.prototype), "close", this).call(this); this.liveQueryImpl.detach(this.listenerUuid); } /** * @return A snapshot of items matching the current query expression. */ }, { key: "getItems", value: function getItems() { this.ensureNotClosed(); return this.liveQueryImpl.getItems(); } }], [{ key: "type", get: // private props function get() { return LiveQueryImpl.type; } }]); return LiveQuery; }(Closeable); /** * Allows repetitive quick searches against a specific Flex data. Unlike a * LiveQuery, this result set does not subscribe to any updates and therefore receives no events * beyond the initial result set. * * Use the {@link SyncClient.instantQuery} method to create an Instant Query. */ _defineProperty__default['default'](LiveQuery, "itemUpdated", 'itemUpdated'); _defineProperty__default['default'](LiveQuery, "itemRemoved", 'itemRemoved'); var InstantQuery = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](InstantQuery, _EventEmitter); var _super3 = _createSuper$1$1(InstantQuery); /** * @internal */ function InstantQuery(params) { var _this4; _classCallCheck__default['default'](this, InstantQuery); _this4 = _super3.call(this); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this4), "queryExpression", null); _defineProperty__default['default'](_assertThisInitialized__default['default'](_this4), "items", {}); Object.assign(_assertThisInitialized__default['default'](_this4), params); _this4.updateIndexName(params.indexName); return _this4; } /** * Fired when a search result is ready. * * Parameters: * 1. {@link ItemsSnapshot} `items` - a snapshot of items matching current query expression. * @example * ```typescript * instantQuery.on('searchResult', (items) => { * Object.entries(items).forEach(([key, value]) => { * console.log('Search result item key:', key); * console.log('Search result item value:', value); * }); * }); * ``` * @event */ _createClass__default['default'](InstantQuery, [{ key: "type", get: function get() { return InstantQuery.type; } }, { key: "search", value: /** * Spawns a new search request. The result will be provided asynchronously via the {@link InstantQuery.searchResult} * event. * @param queryExpression A query expression to be executed against the given data index. For more information * on the syntax read {@link SyncClient.liveQuery}. * @return A promise that resolves when query result has been received. */ function () { var _search = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(queryExpression) { var _this5 = this; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: this.items = {}; return _context.abrupt("return", queryItems({ network: this.network, uri: this.queryUri, queryString: queryExpression }).then(function (response) { _this5.queryExpression = queryExpression; if (response.items) { response.items.forEach(function (item) { _this5.items[item.key] = item.data; }); } _this5.emit('searchResult', _this5.getItems()); }).catch(function (err) { log$1$1.error("Error '".concat(err.message, "' while executing query '").concat(queryExpression, "'")); _this5.queryExpression = null; throw err; })); case 2: case "end": return _context.stop(); } } }, _callee, this); })); function search(_x2) { return _search.apply(this, arguments); } return search; }() /** * Instantiates a LiveQuery object based on the last known query expression that was passed to the * {@link InstantQuery.search} method. This LiveQuery will start receiving updates with new results, * while current object can be still used to execute repetitive searches. * @return A promise which resolves when the LiveQuery object is ready. */ }, { key: "subscribe", value: function () { var _subscribe = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2() { return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(this.queryExpression == null)) { _context2.next = 2; break; } return _context2.abrupt("return", Promise.reject(new SyncError("Invalid query", 400, 54507))); case 2: return _context2.abrupt("return", this.liveQueryCreator(this.indexName, this.queryExpression)); case 3: case "end": return _context2.stop(); } } }, _callee2, this); })); function subscribe() { return _subscribe.apply(this, arguments); } return subscribe; }() /** * @return A snapshot of items matching current query expression. */ }, { key: "getItems", value: function getItems() { return this.items; } /** * Set new index name * @param indexName New index name to set */ }, { key: "updateIndexName", value: function updateIndexName(indexName) { this.indexName = indexName; this.queryUri = this.generateQueryUri(this.indexName); } }, { key: "generateQueryUri", value: function generateQueryUri(indexName) { return new UriBuilder(this.insightsUri).pathSegment(indexName).pathSegment('Items').build(); } }], [{ key: "type", get: // private props function get() { return 'instant_query'; } }]); return InstantQuery; }(EventEmitter); _defineProperty__default['default'](InstantQuery, "searchResult", 'searchResult'); __decorate([declarativeTypeValidator.validateTypesAsync('string'), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], InstantQuery.prototype, "search", null); __decorate([declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", void 0)], InstantQuery.prototype, "updateIndexName", null); var version$1 = "3.1.0"; function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var SYNC_PRODUCT_ID = 'data_sync'; var SDK_VERSION = version$1; function decompose(arg) { if (!arg) { return { mode: 'create_new' }; } else if (typeof arg === 'string') { return { id: arg, mode: 'open_or_create' }; } else { var mode = arg.mode || (arg.id ? 'open_or_create' : 'create_new'); return _objectSpread$5(_objectSpread$5({}, arg), {}, { mode: mode }); } } var SYNC_DOCUMENT_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.document'; var SYNC_LIST_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.list'; var SYNC_MAP_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.map'; var SYNC_NOTIFICATION_TYPE = 'twilio.sync.event'; /** * Client for the Twilio Sync service. * * @example * ```typescript * // Using NPM resolution * const SyncClient = require('twilio-sync'); * const syncClient = new SyncClient(token, { loglevel: 'debug' }); * * // Using CDN * const syncClient = new Twilio.Sync.Client(token, { logLevel: 'debug' }); * ``` */ var Client = /*#__PURE__*/function (_EventEmitter) { _inherits__default['default'](Client, _EventEmitter); var _super = _createSuper$8(Client); /** * @param fpaToken Twilio access token. * @param options Options to customize the client. */ function Client(fpaToken) { var _this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck__default['default'](this, Client); _this = _super.call(this); if (!fpaToken) { throw new Error('Sync library needs a valid Twilio token to be passed'); } if (options.hasOwnProperty('logLevel')) { log$1$1.setLevel(options.logLevel); } else { log$1$1.setLevel('silent'); } var productId = options.productId = options.productId || SYNC_PRODUCT_ID; // Fill ClientMetadata options.clientMetadata = options.clientMetadata || {}; if (!options.clientMetadata.hasOwnProperty('type')) { options.clientMetadata.type = 'sync'; } if (!options.clientMetadata.hasOwnProperty('sdk')) { options.clientMetadata.sdk = 'JS'; options.clientMetadata.sdkv = SDK_VERSION; } var startTwilsock = !options.twilsockClient; // Create default init registrations if none were provided. // Otherwise, the outside party have to list all the init registrations they need, including Sync ones. if (!options.initRegistrations) { var initRegistration = new twilsock.InitRegistration(productId); Client.populateInitRegistrations(initRegistration); options.initRegistrations = [initRegistration]; } var twilsock$1 = options.twilsockClient = options.twilsockClient || new twilsock.Twilsock(fpaToken, productId, options); twilsock$1.on('tokenAboutToExpire', function (ttl) { return _this.emit('tokenAboutToExpire', ttl); }); twilsock$1.on('tokenExpired', function () { return _this.emit('tokenExpired'); }); twilsock$1.on('connectionError', function (err) { return _this.emit('connectionError', err); }); twilsock$1.on('stateChanged', function (state) { _this.emit('connectionStateChanged', state); /** * Handle transport establishing event * If we have any subscriptions - we should check object for modifications */ _this.services.subscriptions.onConnectionStateChanged(state === 'connected'); }); twilsock$1.on('message', function (messageType, payload) { return _this._routeMessage(messageType, payload); }); var config = new Configuration(options); var network = new NetworkService(new ClientInfo(SDK_VERSION), config, twilsock$1); var storage = new SessionStorage(config); _this.services = { config: config, twilsock: twilsock$1, network: network, storage: storage, router: _assertThisInitialized__default['default'](_this), subscriptions: null }; _this.services.subscriptions = new Subscriptions(_this.services); _this.entities = new EntitiesCache(); // Start only if we created twilsock locally, // otherwise it's the responsibility of whoever created the Twilsock client. if (startTwilsock) { twilsock$1.connect(); } return _this; } /** * Fired when connection state has been changed. * * Parameters: * 1. {@link ConnectionState} `connectionState` - contains current service connection state. * @example * ```typescript * syncClient.on('connectionStateChanged', (newState) => { * console.log('Received a new connection state:', newState); * }); * ``` * @event */ _createClass__default['default'](Client, [{ key: "_routeMessage", value: /** * Entry point for all the incoming messages (Router). * * @param type Type of the incoming message * @param message Message to route * @internal */ function _routeMessage(type, message) { log$1$1.trace('Notification type:', type, 'content:', message); switch (type) { case SYNC_DOCUMENT_NOTIFICATION_TYPE: case SYNC_LIST_NOTIFICATION_TYPE: case SYNC_MAP_NOTIFICATION_TYPE: this.services.subscriptions.acceptMessage(message, false); break; case SYNC_NOTIFICATION_TYPE: this.services.subscriptions.acceptMessage(message, true); break; } } /** * Subscribe for events (Router) * * @internal */ }, { key: "_subscribe", value: function _subscribe(sid, entity) { this.services.subscriptions.add(sid, entity); } /** * Unsubscribe from events (Router) * * @internal */ }, { key: "_unsubscribe", value: function _unsubscribe(sid) { this.services.subscriptions.remove(sid); } /** * Current version of the Sync client. */ }, { key: "connectionState", get: /** * Current service connection state. */ function get() { return this.services.twilsock.state; } /** * Returns a promise which resolves when library is correctly initialized * Or throws if initialization is impossible * * @internal */ }, { key: "ensureReady", value: function () { var _ensureReady = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() { var storageSettings; return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (this.services.config.sessionStorageEnabled) { _context.next = 2; break; } return _context.abrupt("return"); case 2: _context.prev = 2; _context.next = 5; return this.services.twilsock.storageId(); case 5: storageSettings = _context.sent; this.services.storage.updateStorageId(storageSettings.id); _context.next = 12; break; case 9: _context.prev = 9; _context.t0 = _context["catch"](2); log$1$1.warn('Failed to initialize storage', _context.t0); case 12: case "end": return _context.stop(); } } }, _callee, this, [[2, 9]]); })); function ensureReady() { return _ensureReady.apply(this, arguments); } return ensureReady; }() }, { key: "storeRootInSessionCache", value: function storeRootInSessionCache(type, id, value) { // can't store without id if (!this.services.config.sessionStorageEnabled || !id) { return; } var valueToStore = deepClone(value); if (type === SyncList.type || type === SyncMap.type) { valueToStore['last_event_id'] = null; delete valueToStore['items']; } this.services.storage.store(type, id, valueToStore); } }, { key: "readRootFromSessionCache", value: function readRootFromSessionCache(type, id) { if (!this.services.config.sessionStorageEnabled || !id) { return null; } return this.services.storage.read(type, id); } }, { key: "_get", value: function () { var _get2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(baseUri, id) { var optimistic, uri, response, _args2 = arguments; return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: optimistic = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; if (id) { _context2.next = 3; break; } throw new SyncError("Cannot get entity without id", 404); case 3: uri = new UriBuilder(baseUri).pathSegment(id).queryParam('Include', optimistic ? 'items' : undefined).build(); _context2.next = 6; return this.services.network.get(uri); case 6: response = _context2.sent; return _context2.abrupt("return", response.body); case 8: case "end": return _context2.stop(); } } }, _callee2, this); })); function _get(_x, _x2) { return _get2.apply(this, arguments); } return _get; }() }, { key: "_createDocument", value: function _createDocument(id, data, ttl) { var requestBody = { unique_name: id, data: data || {} }; if (ttl !== undefined) { requestBody.ttl = ttl; } return this.services.network.post(this.services.config.documentsUri, requestBody).then(function (response) { response.body.data = requestBody.data; return response.body; }); } }, { key: "_getDocument", value: function () { var _getDocument2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(id) { return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: return _context3.abrupt("return", this.readRootFromSessionCache(SyncDocument.type, id) || this._get(this.services.config.documentsUri, id)); case 1: case "end": return _context3.stop(); } } }, _callee3, this); })); function _getDocument(_x3) { return _getDocument2.apply(this, arguments); } return _getDocument; }() }, { key: "_createList", value: function _createList(id, purpose, context, ttl) { var requestBody = { unique_name: id, purpose: purpose, context: context }; if (ttl !== undefined) { requestBody.ttl = ttl; } return this.services.network.post(this.services.config.listsUri, requestBody).then(function (response) { return response.body; }); } }, { key: "_getList", value: function () { var _getList2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4(id) { return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: return _context4.abrupt("return", this.readRootFromSessionCache(SyncList.type, id) || this._get(this.services.config.listsUri, id)); case 1: case "end": return _context4.stop(); } } }, _callee4, this); })); function _getList(_x4) { return _getList2.apply(this, arguments); } return _getList; }() }, { key: "_createMap", value: function _createMap(id, ttl) { var requestBody = { unique_name: id }; if (ttl !== undefined) { requestBody.ttl = ttl; } return this.services.network.post(this.services.config.mapsUri, requestBody).then(function (response) { return response.body; }); } }, { key: "_getMap", value: function () { var _getMap2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(id) { var optimistic, _args5 = arguments; return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: optimistic = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : false; return _context5.abrupt("return", this.readRootFromSessionCache(SyncMap.type, id) || this._get(this.services.config.mapsUri, id, optimistic)); case 2: case "end": return _context5.stop(); } } }, _callee5, this); })); function _getMap(_x5) { return _getMap2.apply(this, arguments); } return _getMap; }() }, { key: "_getStream", value: function () { var _getStream2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(id) { return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: return _context6.abrupt("return", this.readRootFromSessionCache(SyncStream.type, id) || this._get(this.services.config.streamsUri, id, false)); case 1: case "end": return _context6.stop(); } } }, _callee6, this); })); function _getStream(_x6) { return _getStream2.apply(this, arguments); } return _getStream; }() }, { key: "_createStream", value: function () { var _createStream2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee7(id, ttl) { var requestBody, response; return _regeneratorRuntime__default['default'].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: requestBody = { unique_name: id }; if (ttl !== undefined) { requestBody.ttl = ttl; } _context7.next = 4; return this.services.network.post(this.services.config.streamsUri, requestBody); case 4: response = _context7.sent; return _context7.abrupt("return", response.body); case 6: case "end": return _context7.stop(); } } }, _callee7, this); })); function _createStream(_x7, _x8) { return _createStream2.apply(this, arguments); } return _createStream; }() }, { key: "_getLiveQuery", value: function _getLiveQuery(sid) { return this.readRootFromSessionCache(LiveQuery.type, sid); } }, { key: "getCached", value: function getCached(id, type) { if (id) { return this.entities.get(id, type) || null; } return null; } }, { key: "removeFromCacheAndSession", value: function removeFromCacheAndSession(type, sid, uniqueName) { this.entities.remove(sid); if (this.services.config.sessionStorageEnabled) { this.services.storage.remove(type, sid, uniqueName); } } /** * Read or create a Sync document. * @param arg Could be any of the following: * * Unique name or SID identifying the Sync document - opens the document with the given identifier or creates one if it does not exist. * * none - creates a new document with a randomly assigned SID and no unique name. * * {@link OpenDocumentOptions} object for more granular control. * @return A promise which resolves after the document is successfully read (or created). * This promise may reject if the document could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.document('MyDocument') * .then((document) => { * console.log('Successfully opened a document. SID:', document.sid); * document.on('updated', (event) => { * console.log('Received an "updated" event: ', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ }, { key: "document", value: function () { var _document = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee8(arg) { var _this2 = this; var opts, docDescriptor, docFromInMemoryCache, syncDocumentImpl; return _regeneratorRuntime__default['default'].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; return this.ensureReady(); case 2: opts = decompose(arg); if (!(opts.mode === 'create_new')) { _context8.next = 9; break; } _context8.next = 6; return this._createDocument(opts.id, opts.data, opts.ttl); case 6: docDescriptor = _context8.sent; _context8.next = 39; break; case 9: docFromInMemoryCache = this.getCached(opts.id, SyncDocument.type); if (!docFromInMemoryCache) { _context8.next = 14; break; } return _context8.abrupt("return", new SyncDocument(docFromInMemoryCache)); case 14: _context8.prev = 14; _context8.next = 17; return this._getDocument(opts.id); case 17: docDescriptor = _context8.sent; _context8.next = 39; break; case 20: _context8.prev = 20; _context8.t0 = _context8["catch"](14); if (!(_context8.t0.status !== 404 || opts.mode === 'open_existing')) { _context8.next = 26; break; } throw _context8.t0; case 26: _context8.prev = 26; _context8.next = 29; return this._createDocument(opts.id, opts.data, opts.ttl); case 29: docDescriptor = _context8.sent; _context8.next = 39; break; case 32: _context8.prev = 32; _context8.t1 = _context8["catch"](26); if (!(_context8.t1.status === 409)) { _context8.next = 38; break; } return _context8.abrupt("return", this.document(arg)); case 38: throw _context8.t1; case 39: this.storeRootInSessionCache(SyncDocument.type, opts.id, docDescriptor); syncDocumentImpl = new SyncDocumentImpl(this.services, docDescriptor, function (type, sid, uniqueName) { return _this2.removeFromCacheAndSession(type, sid, uniqueName); }); syncDocumentImpl = this.entities.store(syncDocumentImpl); return _context8.abrupt("return", new SyncDocument(syncDocumentImpl)); case 43: case "end": return _context8.stop(); } } }, _callee8, this, [[14, 20], [26, 32]]); })); function document(_x9) { return _document.apply(this, arguments); } return document; }() /** * Read or create a Sync map. * @param arg Could be any of the following: * * Unique name or SID identifying the Sync map - opens the map with the given identifier or creates one if it does not exist. * * none - creates a new map with a randomly assigned SID and no unique name. * * {@link OpenMapOptions} object for more granular control. * @return A promise which resolves after the map is successfully read (or created). * This promise may reject if the map could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.map('MyMap') * .then((map) => { * console.log('Successfully opened a map. SID:', map.sid); * map.on('itemUpdated', (event) => { * console.log('Received an "itemUpdated" event:', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ }, { key: "map", value: function () { var _map = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee9(arg) { var _this3 = this; var opts, mapDescriptor, mapFromInMemoryCache, syncMapImpl; return _regeneratorRuntime__default['default'].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return this.ensureReady(); case 2: opts = decompose(arg); if (!(opts.mode === 'create_new')) { _context9.next = 9; break; } _context9.next = 6; return this._createMap(opts.id, opts.ttl); case 6: mapDescriptor = _context9.sent; _context9.next = 39; break; case 9: mapFromInMemoryCache = this.getCached(opts.id, SyncMap.type); if (!mapFromInMemoryCache) { _context9.next = 14; break; } return _context9.abrupt("return", new SyncMap(mapFromInMemoryCache)); case 14: _context9.prev = 14; _context9.next = 17; return this._getMap(opts.id, opts.includeItems); case 17: mapDescriptor = _context9.sent; _context9.next = 39; break; case 20: _context9.prev = 20; _context9.t0 = _context9["catch"](14); if (!(_context9.t0.status !== 404 || opts.mode === 'open_existing')) { _context9.next = 26; break; } throw _context9.t0; case 26: _context9.prev = 26; _context9.next = 29; return this._createMap(opts.id, opts.ttl); case 29: mapDescriptor = _context9.sent; _context9.next = 39; break; case 32: _context9.prev = 32; _context9.t1 = _context9["catch"](26); if (!(_context9.t1.status === 409)) { _context9.next = 38; break; } return _context9.abrupt("return", this.map(arg)); case 38: throw _context9.t1; case 39: this.storeRootInSessionCache(SyncMap.type, opts.id, mapDescriptor); syncMapImpl = new SyncMapImpl(this.services, mapDescriptor, function (type, sid, uniqueName) { return _this3.removeFromCacheAndSession(type, sid, uniqueName); }); syncMapImpl = this.entities.store(syncMapImpl); return _context9.abrupt("return", new SyncMap(syncMapImpl)); case 43: case "end": return _context9.stop(); } } }, _callee9, this, [[14, 20], [26, 32]]); })); function map(_x10) { return _map.apply(this, arguments); } return map; }() /** * Read or create a Sync list. * @param arg Could be any of the following: * * Unique name or SID identifying a Sync list - opens the list with the given identifier or creates one if it does not exist. * * none - creates a new list with a randomly assigned SID and no unique name. * * {@link OpenListOptions} object for more granular control. * @return A promise which resolves after the list is successfully read (or created). * This promise may reject if the list could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.list('MyList') * .then((list) => { * console.log('Successfully opened a List. SID:', list.sid); * list.on('itemAdded', (event) => { * console.log('Received an "itemAdded" event:', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ }, { key: "list", value: function () { var _list = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee10(arg) { var _this4 = this; var opts, listDescriptor, listFromInMemoryCache, syncListImpl; return _regeneratorRuntime__default['default'].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return this.ensureReady(); case 2: opts = decompose(arg); if (!(opts.mode === 'create_new')) { _context10.next = 9; break; } _context10.next = 6; return this._createList(opts.id, opts.purpose, opts.context, opts.ttl); case 6: listDescriptor = _context10.sent; _context10.next = 39; break; case 9: listFromInMemoryCache = this.getCached(opts.id, SyncList.type); if (!listFromInMemoryCache) { _context10.next = 14; break; } return _context10.abrupt("return", new SyncList(listFromInMemoryCache)); case 14: _context10.prev = 14; _context10.next = 17; return this._getList(opts.id); case 17: listDescriptor = _context10.sent; _context10.next = 39; break; case 20: _context10.prev = 20; _context10.t0 = _context10["catch"](14); if (!(_context10.t0.status !== 404 || opts.mode === 'open_existing')) { _context10.next = 26; break; } throw _context10.t0; case 26: _context10.prev = 26; _context10.next = 29; return this._createList(opts.id, opts.purpose, opts.context, opts.ttl); case 29: listDescriptor = _context10.sent; _context10.next = 39; break; case 32: _context10.prev = 32; _context10.t1 = _context10["catch"](26); if (!(_context10.t1.status === 409)) { _context10.next = 38; break; } return _context10.abrupt("return", this.list(arg)); case 38: throw _context10.t1; case 39: this.storeRootInSessionCache(SyncList.type, opts.id, listDescriptor); syncListImpl = new SyncListImpl(this.services, listDescriptor, function (type, sid, uniqueName) { return _this4.removeFromCacheAndSession(type, sid, uniqueName); }); syncListImpl = this.entities.store(syncListImpl); return _context10.abrupt("return", new SyncList(syncListImpl)); case 43: case "end": return _context10.stop(); } } }, _callee10, this, [[14, 20], [26, 32]]); })); function list(_x11) { return _list.apply(this, arguments); } return list; }() /** * Read or create a Sync message stream. * @param arg Could be any of the following: * * Unique name or SID identifying a stream - opens the stream with the given identifier or creates one if it does not exist. * * none - creates a new stream with a randomly assigned SID and no unique name. * * {@link OpenStreamOptions} object for more granular control. * @return A promise which resolves after the stream is successfully read (or created). * The flow of messages will begin imminently (but not necessarily immediately) upon resolution. * This promise may reject if the stream could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.stream('MyStream') * .then((stream) => { * console.log('Successfully opened a message stream. SID:', stream.sid); * stream.on('messagePublished', (event) => { * console.log('Received a "messagePublished" event:', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ }, { key: "stream", value: function () { var _stream = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee11(arg) { var _this5 = this; var opts, streamDescriptor, streamFromInMemoryCache, streamRemovalHandler, syncStreamImpl; return _regeneratorRuntime__default['default'].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: _context11.next = 2; return this.ensureReady(); case 2: opts = decompose(arg); if (!(opts.mode === 'create_new')) { _context11.next = 9; break; } _context11.next = 6; return this._createStream(opts.id, opts.ttl); case 6: streamDescriptor = _context11.sent; _context11.next = 39; break; case 9: streamFromInMemoryCache = this.getCached(opts.id, SyncStream.type); if (!streamFromInMemoryCache) { _context11.next = 14; break; } return _context11.abrupt("return", new SyncStream(streamFromInMemoryCache)); case 14: _context11.prev = 14; _context11.next = 17; return this._getStream(opts.id); case 17: streamDescriptor = _context11.sent; _context11.next = 39; break; case 20: _context11.prev = 20; _context11.t0 = _context11["catch"](14); if (!(_context11.t0.status !== 404 || opts.mode === 'open_existing')) { _context11.next = 26; break; } throw _context11.t0; case 26: _context11.prev = 26; _context11.next = 29; return this._createStream(opts.id, opts.ttl); case 29: streamDescriptor = _context11.sent; _context11.next = 39; break; case 32: _context11.prev = 32; _context11.t1 = _context11["catch"](26); if (!(_context11.t1.status === 409)) { _context11.next = 38; break; } return _context11.abrupt("return", this.stream(arg)); case 38: throw _context11.t1; case 39: this.storeRootInSessionCache(SyncStream.type, opts.id, streamDescriptor); streamRemovalHandler = function streamRemovalHandler(type, sid, uniqueName) { return _this5.removeFromCacheAndSession(type, sid, uniqueName); }; syncStreamImpl = new SyncStreamImpl(this.services, streamDescriptor, streamRemovalHandler); syncStreamImpl = this.entities.store(syncStreamImpl); return _context11.abrupt("return", new SyncStream(syncStreamImpl)); case 44: case "end": return _context11.stop(); } } }, _callee11, this, [[14, 20], [26, 32]]); })); function stream(_x12) { return _stream.apply(this, arguments); } return stream; }() /** * Gracefully shuts the Sync client down. */ }, { key: "shutdown", value: function () { var _shutdown = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee12() { return _regeneratorRuntime__default['default'].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return this.services.subscriptions.shutdown(); case 2: _context12.next = 4; return this.services.twilsock.disconnect(); case 4: case "end": return _context12.stop(); } } }, _callee12, this); })); function shutdown() { return _shutdown.apply(this, arguments); } return shutdown; }() /** * Set the authentication token. * @param token New token to set. */ }, { key: "updateToken", value: function () { var _updateToken = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee13(token) { return _regeneratorRuntime__default['default'].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: return _context13.abrupt("return", this.services.twilsock.updateToken(token).catch(function (error) { var _error$reply; var status = error === null || error === void 0 ? void 0 : (_error$reply = error.reply) === null || _error$reply === void 0 ? void 0 : _error$reply.status; if ((status === null || status === void 0 ? void 0 : status.code) === 401 && (status === null || status === void 0 ? void 0 : status.status) === 'UNAUTHORIZED') { throw new SyncError('Updated token was rejected by server', 400, 51130); } throw error; })); case 1: case "end": return _context13.stop(); } } }, _callee13, this); })); function updateToken(_x13) { return _updateToken.apply(this, arguments); } return updateToken; }() /** * For Flex customers only. Establishes a long-running query against Flex data wherein the returned * result set is updated whenever new (or updated) records match the given expression. Updated results * are presented row-by-row according to the lifetime of the returned LiveQuery object. * * @param indexName Must specify one of the Flex data classes for which Live Queries are available. * @param queryExpression A query expression to be executed against the given data index. * Please review the [Live Query Language](https://www.twilio.com/docs/sync/live-query) * page for Sync client limits and a full list of operators currently supported in query expressions. * * @return A promise that resolves when the query has been successfully executed. * @example * ```typescript * syncClient.liveQuery('tr-worker', 'data.attributes.worker_name == "Bob"') * .then((args) => { * console.log('Subscribed to live data updates for worker Bob'); * const items = args.getItems(); * Object.entries(items).forEach(([key, value]) => { * console.log('Search result item key:', key); * console.log('Search result item value:', value); * }); * }) * .catch((err) => { * console.error('Error when subscribing to live updates for worker Bob', err); * }); * ``` */ }, { key: "liveQuery", value: function () { var _liveQuery = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee14(indexName, queryExpression) { var _this6 = this; var queryUri, response, liveQueryImpl, descriptor, liveQueryRemovalHandler; return _regeneratorRuntime__default['default'].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return this.ensureReady(); case 2: queryUri = new UriBuilder(this.services.config.insightsUri).pathSegment(indexName).pathSegment('Items').build(); // send query to CDS to get server-generated sid and item list _context14.next = 5; return queryItems({ network: this.services.network, uri: queryUri, queryString: queryExpression, type: LiveQuery.type }); case 5: response = _context14.sent; liveQueryImpl = this.getCached(response.query_id, LiveQuery.type); if (!liveQueryImpl) { descriptor = this._getLiveQuery(response.query_id); if (!descriptor) { descriptor = { indexName: indexName, queryExpression: queryExpression, sid: response.query_id, queryUri: queryUri, last_event_id: response.last_event_id }; } liveQueryRemovalHandler = function liveQueryRemovalHandler(type, sid, uniqueName) { return _this6.removeFromCacheAndSession(type, sid, uniqueName); }; liveQueryImpl = new LiveQueryImpl(descriptor, this.services, liveQueryRemovalHandler, response.items); } this.storeRootInSessionCache(LiveQuery.type, response.query_id, liveQueryImpl.liveQueryDescriptor); liveQueryImpl = this.entities.store(liveQueryImpl); return _context14.abrupt("return", new LiveQuery(liveQueryImpl)); case 11: case "end": return _context14.stop(); } } }, _callee14, this); })); function liveQuery(_x14, _x15) { return _liveQuery.apply(this, arguments); } return liveQuery; }() /** * For Flex customers only. Creates a query object that can be used to issue one-time queries repeatedly * against the target index. * * @param indexName Must specify one of the Flex data classes for which live queries are available. * @return A promise which resolves after the instance of InstantQuery is successfully created. * @example * ```typescript * syncClient.instantQuery('tr-worker') * .then((q) => { * q.on('searchResult', (items) => { * Object.entries(items).forEach(([key, value]) => { * console.log('Search result item key:', key); * console.log('Search result item value:', value); * }); * }); * }); * ``` */ }, { key: "instantQuery", value: function () { var _instantQuery = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee15(indexName) { var _this7 = this; var liveQueryCreator; return _regeneratorRuntime__default['default'].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: _context15.next = 2; return this.ensureReady(); case 2: liveQueryCreator = function liveQueryCreator(indexName, queryExpression) { return _this7.liveQuery(indexName, queryExpression); }; return _context15.abrupt("return", new InstantQuery({ indexName: indexName, network: this.services.network, insightsUri: this.services.config.insightsUri, liveQueryCreator: liveQueryCreator })); case 4: case "end": return _context15.stop(); } } }, _callee15, this); })); function instantQuery(_x16) { return _instantQuery.apply(this, arguments); } return instantQuery; }() }], [{ key: "populateInitRegistrations", value: function populateInitRegistrations(reg) { reg.populateInitRegistrations([SYNC_NOTIFICATION_TYPE, SYNC_DOCUMENT_NOTIFICATION_TYPE, SYNC_LIST_NOTIFICATION_TYPE, SYNC_MAP_NOTIFICATION_TYPE]); } }, { key: "version", get: function get() { return SDK_VERSION; } }]); return Client; }(EventEmitter); _defineProperty__default['default'](Client, "connectionStateChanged", 'connectionStateChanged'); _defineProperty__default['default'](Client, "connectionError", 'connectionError'); _defineProperty__default['default'](Client, "tokenAboutToExpire", 'tokenAboutToExpire'); _defineProperty__default['default'](Client, "tokenExpired", 'tokenExpired'); __decorate([declarativeTypeValidator.validateTypesAsync(['undefined', 'string', declarativeTypeValidator.objectSchema('open document options', { id: ['string', 'undefined'], mode: [declarativeTypeValidator.literal('open_or_create', 'open_existing', 'create_new'), 'undefined'], ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'], data: [declarativeTypeValidator.pureObject, 'undefined', declarativeTypeValidator.literal(null)] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], Client.prototype, "document", null); __decorate([declarativeTypeValidator.validateTypesAsync(['undefined', 'string', declarativeTypeValidator.objectSchema('open map options', { id: ['string', 'undefined'], mode: [declarativeTypeValidator.literal('open_or_create', 'open_existing', 'create_new'), 'undefined'], ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'], data: [declarativeTypeValidator.pureObject, 'undefined', declarativeTypeValidator.literal(null)], includeItems: ['boolean', 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], Client.prototype, "map", null); __decorate([declarativeTypeValidator.validateTypesAsync(['undefined', 'string', declarativeTypeValidator.objectSchema('open list options', { id: ['string', 'undefined'], mode: [declarativeTypeValidator.literal('open_or_create', 'open_existing', 'create_new'), 'undefined'], ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'], data: [declarativeTypeValidator.pureObject, 'undefined', declarativeTypeValidator.literal(null)], purpose: ['string', 'undefined'], context: [declarativeTypeValidator.pureObject, 'undefined'], includeItems: ['boolean', 'undefined'] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], Client.prototype, "list", null); __decorate([declarativeTypeValidator.validateTypesAsync(['undefined', 'string', declarativeTypeValidator.objectSchema('open stream options', { id: ['string', 'undefined'], mode: [declarativeTypeValidator.literal('open_or_create', 'open_existing', 'create_new'), 'undefined'], ttl: [declarativeTypeValidator.nonNegativeInteger, 'undefined'], data: [declarativeTypeValidator.pureObject, 'undefined', declarativeTypeValidator.literal(null)] })]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], Client.prototype, "stream", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], Client.prototype, "updateToken", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString, 'string'), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", Promise)], Client.prototype, "liveQuery", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], Client.prototype, "instantQuery", null); browser$2.Client = Client; browser$2.InsightsItem = InsightsItem; browser$2.InstantQuery = InstantQuery; browser$2.LiveQuery = LiveQuery; browser$2.Paginator = Paginator; var SyncClient = browser$2.SyncClient = Client; browser$2.SyncDocument = SyncDocument; browser$2.SyncList = SyncList; browser$2.SyncListItem = SyncListItem; browser$2.SyncMap = SyncMap; browser$2.SyncMapItem = SyncMapItem; browser$2.SyncStream = SyncStream; var browser$1 = {}; var isRegExp = isRegexp; var notARegexp = function (it) { if (isRegExp(it)) { throw TypeError("The method doesn't accept regular expressions"); } return it; }; var wellKnownSymbol$2 = wellKnownSymbol$s; var MATCH = wellKnownSymbol$2('match'); var correctIsRegexpLogic = function (METHOD_NAME) { var regexp = /./; try { '/./'[METHOD_NAME](regexp); } catch (error1) { try { regexp[MATCH] = false; return '/./'[METHOD_NAME](regexp); } catch (error2) { /* empty */ } } return false; }; var $$7 = _export; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; var toLength$2 = toLength$o; var toString$2 = toString$d; var notARegExp$1 = notARegexp; var requireObjectCoercible$1 = requireObjectCoercible$a; var correctIsRegExpLogic$1 = correctIsRegexpLogic; // eslint-disable-next-line es/no-string-prototype-startswith -- safe var $startsWith = ''.startsWith; var min = Math.min; var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic$1('startsWith'); // https://github.com/zloirock/core-js/pull/702 var MDN_POLYFILL_BUG = !CORRECT_IS_REGEXP_LOGIC && !!function () { var descriptor = getOwnPropertyDescriptor(String.prototype, 'startsWith'); return descriptor && !descriptor.writable; }(); // `String.prototype.startsWith` method // https://tc39.es/ecma262/#sec-string.prototype.startswith $$7({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, { startsWith: function startsWith(searchString /* , position = 0 */) { var that = toString$2(requireObjectCoercible$1(this)); notARegExp$1(searchString); var index = toLength$2(min(arguments.length > 1 ? arguments[1] : undefined, that.length)); var search = toString$2(searchString); return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); var fails$2 = fails$B; var wellKnownSymbol$1 = wellKnownSymbol$s; var IS_PURE = isPure; var ITERATOR$1 = wellKnownSymbol$1('iterator'); var nativeUrl = !fails$2(function () { var url = new URL('b?a=1&b=2&c=3', 'http://a'); var searchParams = url.searchParams; var result = ''; url.pathname = 'c%20d'; searchParams.forEach(function (value, key) { searchParams['delete']('b'); result += key + value; }); return (IS_PURE && !url.toJSON) || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR$1] // throws in Edge || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- || result !== 'a1c3' // throws in Safari || new URL('http://x', undefined).host !== 'x'; }); // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 var base = 36; var tMin = 1; var tMax = 26; var skew = 38; var damp = 700; var initialBias = 72; var initialN = 128; // 0x80 var delimiter = '-'; // '\x2D' var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process'; var baseMinusTMin = base - tMin; var floor$1 = Math.floor; var stringFromCharCode = String.fromCharCode; /** * 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. */ var ucs2decode = function (string) { var output = []; var counter = 0; var length = string.length; while (counter < length) { var value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // It's a high surrogate, and there is a next character. var extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // It's an 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; }; /** * Converts a digit/integer into a basic code point. */ var digitToBasic = function (digit) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26); }; /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 */ var adapt = function (delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor$1(delta / damp) : delta >> 1; delta += floor$1(delta / numPoints); for (; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor$1(delta / baseMinusTMin); } return floor$1(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. */ // eslint-disable-next-line max-statements -- TODO var encode = function (input) { var output = []; // Convert the input in UCS-2 to an array of Unicode code points. input = ucs2decode(input); // Cache the length. var inputLength = input.length; // Initialize the state. var n = initialN; var delta = 0; var bias = initialBias; var i, currentValue; // Handle the basic code points. for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } var basicLength = output.length; // number of basic code points. var handledCPCount = basicLength; // number of code points that have been handled; // Finish the basic string with a delimiter unless it's empty. 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: var m = maxInt; for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , but guard against overflow. var handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor$1((maxInt - delta) / handledCPCountPlusOne)) { throw RangeError(OVERFLOW_ERROR); } delta += (m - n) * handledCPCountPlusOne; n = m; for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue < n && ++delta > maxInt) { throw RangeError(OVERFLOW_ERROR); } if (currentValue == n) { // Represent delta as a generalized variable-length integer. var q = delta; for (var k = base; /* no condition */; k += base) { var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) break; var qMinusT = q - t; var baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT))); q = floor$1(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); }; var stringPunycodeToAscii = function (input) { var encoded = []; var labels = input.toLowerCase().replace(regexSeparators, '\u002E').split('.'); var i, label; for (i = 0; i < labels.length; i++) { label = labels[i]; encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label); } return encoded.join('.'); }; // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` var $$6 = _export; var getBuiltIn = getBuiltIn$a; var USE_NATIVE_URL$1 = nativeUrl; var redefine$1 = redefine$d.exports; var redefineAll = redefineAll$4; var setToStringTag$1 = setToStringTag$9; var createIteratorConstructor = createIteratorConstructor$2; var InternalStateModule$1 = internalState; var anInstance$1 = anInstance$7; var hasOwn = has$g; var bind = functionBindContext; var classof = classof$9; var anObject = anObject$k; var isObject$1 = isObject$p; var $toString$1 = toString$d; var create = objectCreate; var createPropertyDescriptor = createPropertyDescriptor$7; var getIterator = getIterator$4; var getIteratorMethod = getIteratorMethod$5; var wellKnownSymbol = wellKnownSymbol$s; var nativeFetch = getBuiltIn('fetch'); var NativeRequest = getBuiltIn('Request'); var RequestPrototype = NativeRequest && NativeRequest.prototype; var Headers = getBuiltIn('Headers'); var ITERATOR = wellKnownSymbol('iterator'); var URL_SEARCH_PARAMS = 'URLSearchParams'; var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator'; var setInternalState$1 = InternalStateModule$1.set; var getInternalParamsState = InternalStateModule$1.getterFor(URL_SEARCH_PARAMS); var getInternalIteratorState = InternalStateModule$1.getterFor(URL_SEARCH_PARAMS_ITERATOR); var plus = /\+/g; var sequences = Array(4); var percentSequence = function (bytes) { return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi')); }; var percentDecode = function (sequence) { try { return decodeURIComponent(sequence); } catch (error) { return sequence; } }; var deserialize = function (it) { var result = it.replace(plus, ' '); var bytes = 4; try { return decodeURIComponent(result); } catch (error) { while (bytes) { result = result.replace(percentSequence(bytes--), percentDecode); } return result; } }; var find = /[!'()~]|%20/g; var replace = { '!': '%21', "'": '%27', '(': '%28', ')': '%29', '~': '%7E', '%20': '+' }; var replacer = function (match) { return replace[match]; }; var serialize = function (it) { return encodeURIComponent(it).replace(find, replacer); }; var parseSearchParams = function (result, query) { if (query) { var attributes = query.split('&'); var index = 0; var attribute, entry; while (index < attributes.length) { attribute = attributes[index++]; if (attribute.length) { entry = attribute.split('='); result.push({ key: deserialize(entry.shift()), value: deserialize(entry.join('=')) }); } } } }; var updateSearchParams = function (query) { this.entries.length = 0; parseSearchParams(this.entries, query); }; var validateArgumentsLength = function (passed, required) { if (passed < required) throw TypeError('Not enough arguments'); }; var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) { setInternalState$1(this, { type: URL_SEARCH_PARAMS_ITERATOR, iterator: getIterator(getInternalParamsState(params).entries), kind: kind }); }, 'Iterator', function next() { var state = getInternalIteratorState(this); var kind = state.kind; var step = state.iterator.next(); var entry = step.value; if (!step.done) { step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value]; } return step; }); // `URLSearchParams` constructor // https://url.spec.whatwg.org/#interface-urlsearchparams var URLSearchParamsConstructor = function URLSearchParams(/* init */) { anInstance$1(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS); var init = arguments.length > 0 ? arguments[0] : undefined; var that = this; var entries = []; var iteratorMethod, iterator, next, step, entryIterator, entryNext, first, second, key; setInternalState$1(that, { type: URL_SEARCH_PARAMS, entries: entries, updateURL: function () { /* empty */ }, updateSearchParams: updateSearchParams }); if (init !== undefined) { if (isObject$1(init)) { iteratorMethod = getIteratorMethod(init); if (typeof iteratorMethod === 'function') { iterator = getIterator(init, iteratorMethod); next = iterator.next; while (!(step = next.call(iterator)).done) { entryIterator = getIterator(anObject(step.value)); entryNext = entryIterator.next; if ( (first = entryNext.call(entryIterator)).done || (second = entryNext.call(entryIterator)).done || !entryNext.call(entryIterator).done ) throw TypeError('Expected sequence with length 2'); entries.push({ key: $toString$1(first.value), value: $toString$1(second.value) }); } } else for (key in init) if (hasOwn(init, key)) entries.push({ key: key, value: $toString$1(init[key]) }); } else { parseSearchParams( entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : $toString$1(init) ); } } }; var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype; redefineAll(URLSearchParamsPrototype, { // `URLSearchParams.prototype.append` method // https://url.spec.whatwg.org/#dom-urlsearchparams-append append: function append(name, value) { validateArgumentsLength(arguments.length, 2); var state = getInternalParamsState(this); state.entries.push({ key: $toString$1(name), value: $toString$1(value) }); state.updateURL(); }, // `URLSearchParams.prototype.delete` method // https://url.spec.whatwg.org/#dom-urlsearchparams-delete 'delete': function (name) { validateArgumentsLength(arguments.length, 1); var state = getInternalParamsState(this); var entries = state.entries; var key = $toString$1(name); var index = 0; while (index < entries.length) { if (entries[index].key === key) entries.splice(index, 1); else index++; } state.updateURL(); }, // `URLSearchParams.prototype.get` method // https://url.spec.whatwg.org/#dom-urlsearchparams-get get: function get(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = $toString$1(name); var index = 0; for (; index < entries.length; index++) { if (entries[index].key === key) return entries[index].value; } return null; }, // `URLSearchParams.prototype.getAll` method // https://url.spec.whatwg.org/#dom-urlsearchparams-getall getAll: function getAll(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = $toString$1(name); var result = []; var index = 0; for (; index < entries.length; index++) { if (entries[index].key === key) result.push(entries[index].value); } return result; }, // `URLSearchParams.prototype.has` method // https://url.spec.whatwg.org/#dom-urlsearchparams-has has: function has(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = $toString$1(name); var index = 0; while (index < entries.length) { if (entries[index++].key === key) return true; } return false; }, // `URLSearchParams.prototype.set` method // https://url.spec.whatwg.org/#dom-urlsearchparams-set set: function set(name, value) { validateArgumentsLength(arguments.length, 1); var state = getInternalParamsState(this); var entries = state.entries; var found = false; var key = $toString$1(name); var val = $toString$1(value); var index = 0; var entry; for (; index < entries.length; index++) { entry = entries[index]; if (entry.key === key) { if (found) entries.splice(index--, 1); else { found = true; entry.value = val; } } } if (!found) entries.push({ key: key, value: val }); state.updateURL(); }, // `URLSearchParams.prototype.sort` method // https://url.spec.whatwg.org/#dom-urlsearchparams-sort sort: function sort() { var state = getInternalParamsState(this); var entries = state.entries; // Array#sort is not stable in some engines var slice = entries.slice(); var entry, entriesIndex, sliceIndex; entries.length = 0; for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) { entry = slice[sliceIndex]; for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) { if (entries[entriesIndex].key > entry.key) { entries.splice(entriesIndex, 0, entry); break; } } if (entriesIndex === sliceIndex) entries.push(entry); } state.updateURL(); }, // `URLSearchParams.prototype.forEach` method forEach: function forEach(callback /* , thisArg */) { var entries = getInternalParamsState(this).entries; var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3); var index = 0; var entry; while (index < entries.length) { entry = entries[index++]; boundFunction(entry.value, entry.key, this); } }, // `URLSearchParams.prototype.keys` method keys: function keys() { return new URLSearchParamsIterator(this, 'keys'); }, // `URLSearchParams.prototype.values` method values: function values() { return new URLSearchParamsIterator(this, 'values'); }, // `URLSearchParams.prototype.entries` method entries: function entries() { return new URLSearchParamsIterator(this, 'entries'); } }, { enumerable: true }); // `URLSearchParams.prototype[@@iterator]` method redefine$1(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries); // `URLSearchParams.prototype.toString` method // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior redefine$1(URLSearchParamsPrototype, 'toString', function toString() { var entries = getInternalParamsState(this).entries; var result = []; var index = 0; var entry; while (index < entries.length) { entry = entries[index++]; result.push(serialize(entry.key) + '=' + serialize(entry.value)); } return result.join('&'); }, { enumerable: true }); setToStringTag$1(URLSearchParamsConstructor, URL_SEARCH_PARAMS); $$6({ global: true, forced: !USE_NATIVE_URL$1 }, { URLSearchParams: URLSearchParamsConstructor }); // Wrap `fetch` and `Request` for correct work with polyfilled `URLSearchParams` if (!USE_NATIVE_URL$1 && typeof Headers == 'function') { var wrapRequestOptions = function (init) { if (isObject$1(init)) { var body = init.body; var headers; if (classof(body) === URL_SEARCH_PARAMS) { headers = init.headers ? new Headers(init.headers) : new Headers(); if (!headers.has('content-type')) { headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); } return create(init, { body: createPropertyDescriptor(0, String(body)), headers: createPropertyDescriptor(0, headers) }); } } return init; }; if (typeof nativeFetch == 'function') { $$6({ global: true, enumerable: true, forced: true }, { fetch: function fetch(input /* , init */) { return nativeFetch(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {}); } }); } if (typeof NativeRequest == 'function') { var RequestConstructor = function Request(input /* , init */) { anInstance$1(this, RequestConstructor, 'Request'); return new NativeRequest(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {}); }; RequestPrototype.constructor = RequestConstructor; RequestConstructor.prototype = RequestPrototype; $$6({ global: true, forced: true }, { Request: RequestConstructor }); } } var web_urlSearchParams = { URLSearchParams: URLSearchParamsConstructor, getState: getInternalParamsState }; // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` var $$5 = _export; var DESCRIPTORS = descriptors; var USE_NATIVE_URL = nativeUrl; var global$2 = global$D; var defineProperties = objectDefineProperties; var redefine = redefine$d.exports; var anInstance = anInstance$7; var has = has$g; var assign = objectAssign; var arrayFrom = arrayFrom$1; var codeAt = stringMultibyte.codeAt; var toASCII = stringPunycodeToAscii; var $toString = toString$d; var setToStringTag = setToStringTag$9; var URLSearchParamsModule = web_urlSearchParams; var InternalStateModule = internalState; var NativeURL = global$2.URL; var URLSearchParams$1 = URLSearchParamsModule.URLSearchParams; var getInternalSearchParamsState = URLSearchParamsModule.getState; var setInternalState = InternalStateModule.set; var getInternalURLState = InternalStateModule.getterFor('URL'); var floor = Math.floor; var pow = Math.pow; var INVALID_AUTHORITY = 'Invalid authority'; var INVALID_SCHEME = 'Invalid scheme'; var INVALID_HOST = 'Invalid host'; var INVALID_PORT = 'Invalid port'; var ALPHA = /[A-Za-z]/; // eslint-disable-next-line regexp/no-obscure-range -- safe var ALPHANUMERIC = /[\d+-.A-Za-z]/; var DIGIT = /\d/; var HEX_START = /^0x/i; var OCT = /^[0-7]+$/; var DEC = /^\d+$/; var HEX = /^[\dA-Fa-f]+$/; /* eslint-disable no-control-regex -- safe */ var FORBIDDEN_HOST_CODE_POINT = /[\0\t\n\r #%/:<>?@[\\\]^|]/; var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\0\t\n\r #/:<>?@[\\\]^|]/; var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u0020]+|[\u0000-\u0020]+$/g; var TAB_AND_NEW_LINE = /[\t\n\r]/g; /* eslint-enable no-control-regex -- safe */ var EOF; var parseHost = function (url, input) { var result, codePoints, index; if (input.charAt(0) == '[') { if (input.charAt(input.length - 1) != ']') return INVALID_HOST; result = parseIPv6(input.slice(1, -1)); if (!result) return INVALID_HOST; url.host = result; // opaque host } else if (!isSpecial(url)) { if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST; result = ''; codePoints = arrayFrom(input); for (index = 0; index < codePoints.length; index++) { result += percentEncode(codePoints[index], C0ControlPercentEncodeSet); } url.host = result; } else { input = toASCII(input); if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST; result = parseIPv4(input); if (result === null) return INVALID_HOST; url.host = result; } }; var parseIPv4 = function (input) { var parts = input.split('.'); var partsLength, numbers, index, part, radix, number, ipv4; if (parts.length && parts[parts.length - 1] == '') { parts.pop(); } partsLength = parts.length; if (partsLength > 4) return input; numbers = []; for (index = 0; index < partsLength; index++) { part = parts[index]; if (part == '') return input; radix = 10; if (part.length > 1 && part.charAt(0) == '0') { radix = HEX_START.test(part) ? 16 : 8; part = part.slice(radix == 8 ? 1 : 2); } if (part === '') { number = 0; } else { if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input; number = parseInt(part, radix); } numbers.push(number); } for (index = 0; index < partsLength; index++) { number = numbers[index]; if (index == partsLength - 1) { if (number >= pow(256, 5 - partsLength)) return null; } else if (number > 255) return null; } ipv4 = numbers.pop(); for (index = 0; index < numbers.length; index++) { ipv4 += numbers[index] * pow(256, 3 - index); } return ipv4; }; // eslint-disable-next-line max-statements -- TODO var parseIPv6 = function (input) { var address = [0, 0, 0, 0, 0, 0, 0, 0]; var pieceIndex = 0; var compress = null; var pointer = 0; var value, length, numbersSeen, ipv4Piece, number, swaps, swap; var chr = function () { return input.charAt(pointer); }; if (chr() == ':') { if (input.charAt(1) != ':') return; pointer += 2; pieceIndex++; compress = pieceIndex; } while (chr()) { if (pieceIndex == 8) return; if (chr() == ':') { if (compress !== null) return; pointer++; pieceIndex++; compress = pieceIndex; continue; } value = length = 0; while (length < 4 && HEX.test(chr())) { value = value * 16 + parseInt(chr(), 16); pointer++; length++; } if (chr() == '.') { if (length == 0) return; pointer -= length; if (pieceIndex > 6) return; numbersSeen = 0; while (chr()) { ipv4Piece = null; if (numbersSeen > 0) { if (chr() == '.' && numbersSeen < 4) pointer++; else return; } if (!DIGIT.test(chr())) return; while (DIGIT.test(chr())) { number = parseInt(chr(), 10); if (ipv4Piece === null) ipv4Piece = number; else if (ipv4Piece == 0) return; else ipv4Piece = ipv4Piece * 10 + number; if (ipv4Piece > 255) return; pointer++; } address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece; numbersSeen++; if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++; } if (numbersSeen != 4) return; break; } else if (chr() == ':') { pointer++; if (!chr()) return; } else if (chr()) return; address[pieceIndex++] = value; } if (compress !== null) { swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex != 0 && swaps > 0) { swap = address[pieceIndex]; address[pieceIndex--] = address[compress + swaps - 1]; address[compress + --swaps] = swap; } } else if (pieceIndex != 8) return; return address; }; var findLongestZeroSequence = function (ipv6) { var maxIndex = null; var maxLength = 1; var currStart = null; var currLength = 0; var index = 0; for (; index < 8; index++) { if (ipv6[index] !== 0) { if (currLength > maxLength) { maxIndex = currStart; maxLength = currLength; } currStart = null; currLength = 0; } else { if (currStart === null) currStart = index; ++currLength; } } if (currLength > maxLength) { maxIndex = currStart; maxLength = currLength; } return maxIndex; }; var serializeHost = function (host) { var result, index, compress, ignore0; // ipv4 if (typeof host == 'number') { result = []; for (index = 0; index < 4; index++) { result.unshift(host % 256); host = floor(host / 256); } return result.join('.'); // ipv6 } else if (typeof host == 'object') { result = ''; compress = findLongestZeroSequence(host); for (index = 0; index < 8; index++) { if (ignore0 && host[index] === 0) continue; if (ignore0) ignore0 = false; if (compress === index) { result += index ? ':' : '::'; ignore0 = true; } else { result += host[index].toString(16); if (index < 7) result += ':'; } } return '[' + result + ']'; } return host; }; var C0ControlPercentEncodeSet = {}; var fragmentPercentEncodeSet = assign({}, C0ControlPercentEncodeSet, { ' ': 1, '"': 1, '<': 1, '>': 1, '`': 1 }); var pathPercentEncodeSet = assign({}, fragmentPercentEncodeSet, { '#': 1, '?': 1, '{': 1, '}': 1 }); var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, { '/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1 }); var percentEncode = function (chr, set) { var code = codeAt(chr, 0); return code > 0x20 && code < 0x7F && !has(set, chr) ? chr : encodeURIComponent(chr); }; var specialSchemes = { ftp: 21, file: null, http: 80, https: 443, ws: 80, wss: 443 }; var isSpecial = function (url) { return has(specialSchemes, url.scheme); }; var includesCredentials = function (url) { return url.username != '' || url.password != ''; }; var cannotHaveUsernamePasswordPort = function (url) { return !url.host || url.cannotBeABaseURL || url.scheme == 'file'; }; var isWindowsDriveLetter = function (string, normalized) { var second; return string.length == 2 && ALPHA.test(string.charAt(0)) && ((second = string.charAt(1)) == ':' || (!normalized && second == '|')); }; var startsWithWindowsDriveLetter = function (string) { var third; return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && ( string.length == 2 || ((third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#') ); }; var shortenURLsPath = function (url) { var path = url.path; var pathSize = path.length; if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) { path.pop(); } }; var isSingleDot = function (segment) { return segment === '.' || segment.toLowerCase() === '%2e'; }; var isDoubleDot = function (segment) { segment = segment.toLowerCase(); return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e'; }; // States: var SCHEME_START = {}; var SCHEME = {}; var NO_SCHEME = {}; var SPECIAL_RELATIVE_OR_AUTHORITY = {}; var PATH_OR_AUTHORITY = {}; var RELATIVE = {}; var RELATIVE_SLASH = {}; var SPECIAL_AUTHORITY_SLASHES = {}; var SPECIAL_AUTHORITY_IGNORE_SLASHES = {}; var AUTHORITY = {}; var HOST = {}; var HOSTNAME = {}; var PORT = {}; var FILE = {}; var FILE_SLASH = {}; var FILE_HOST = {}; var PATH_START = {}; var PATH = {}; var CANNOT_BE_A_BASE_URL_PATH = {}; var QUERY = {}; var FRAGMENT = {}; // eslint-disable-next-line max-statements -- TODO var parseURL = function (url, input, stateOverride, base) { var state = stateOverride || SCHEME_START; var pointer = 0; var buffer = ''; var seenAt = false; var seenBracket = false; var seenPasswordToken = false; var codePoints, chr, bufferCodePoints, failure; if (!stateOverride) { url.scheme = ''; url.username = ''; url.password = ''; url.host = null; url.port = null; url.path = []; url.query = null; url.fragment = null; url.cannotBeABaseURL = false; input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, ''); } input = input.replace(TAB_AND_NEW_LINE, ''); codePoints = arrayFrom(input); while (pointer <= codePoints.length) { chr = codePoints[pointer]; switch (state) { case SCHEME_START: if (chr && ALPHA.test(chr)) { buffer += chr.toLowerCase(); state = SCHEME; } else if (!stateOverride) { state = NO_SCHEME; continue; } else return INVALID_SCHEME; break; case SCHEME: if (chr && (ALPHANUMERIC.test(chr) || chr == '+' || chr == '-' || chr == '.')) { buffer += chr.toLowerCase(); } else if (chr == ':') { if (stateOverride && ( (isSpecial(url) != has(specialSchemes, buffer)) || (buffer == 'file' && (includesCredentials(url) || url.port !== null)) || (url.scheme == 'file' && !url.host) )) return; url.scheme = buffer; if (stateOverride) { if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null; return; } buffer = ''; if (url.scheme == 'file') { state = FILE; } else if (isSpecial(url) && base && base.scheme == url.scheme) { state = SPECIAL_RELATIVE_OR_AUTHORITY; } else if (isSpecial(url)) { state = SPECIAL_AUTHORITY_SLASHES; } else if (codePoints[pointer + 1] == '/') { state = PATH_OR_AUTHORITY; pointer++; } else { url.cannotBeABaseURL = true; url.path.push(''); state = CANNOT_BE_A_BASE_URL_PATH; } } else if (!stateOverride) { buffer = ''; state = NO_SCHEME; pointer = 0; continue; } else return INVALID_SCHEME; break; case NO_SCHEME: if (!base || (base.cannotBeABaseURL && chr != '#')) return INVALID_SCHEME; if (base.cannotBeABaseURL && chr == '#') { url.scheme = base.scheme; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; url.cannotBeABaseURL = true; state = FRAGMENT; break; } state = base.scheme == 'file' ? FILE : RELATIVE; continue; case SPECIAL_RELATIVE_OR_AUTHORITY: if (chr == '/' && codePoints[pointer + 1] == '/') { state = SPECIAL_AUTHORITY_IGNORE_SLASHES; pointer++; } else { state = RELATIVE; continue; } break; case PATH_OR_AUTHORITY: if (chr == '/') { state = AUTHORITY; break; } else { state = PATH; continue; } case RELATIVE: url.scheme = base.scheme; if (chr == EOF) { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = base.query; } else if (chr == '/' || (chr == '\\' && isSpecial(url))) { state = RELATIVE_SLASH; } else if (chr == '?') { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = ''; state = QUERY; } else if (chr == '#') { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; state = FRAGMENT; } else { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.path.pop(); state = PATH; continue; } break; case RELATIVE_SLASH: if (isSpecial(url) && (chr == '/' || chr == '\\')) { state = SPECIAL_AUTHORITY_IGNORE_SLASHES; } else if (chr == '/') { state = AUTHORITY; } else { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; state = PATH; continue; } break; case SPECIAL_AUTHORITY_SLASHES: state = SPECIAL_AUTHORITY_IGNORE_SLASHES; if (chr != '/' || buffer.charAt(pointer + 1) != '/') continue; pointer++; break; case SPECIAL_AUTHORITY_IGNORE_SLASHES: if (chr != '/' && chr != '\\') { state = AUTHORITY; continue; } break; case AUTHORITY: if (chr == '@') { if (seenAt) buffer = '%40' + buffer; seenAt = true; bufferCodePoints = arrayFrom(buffer); for (var i = 0; i < bufferCodePoints.length; i++) { var codePoint = bufferCodePoints[i]; if (codePoint == ':' && !seenPasswordToken) { seenPasswordToken = true; continue; } var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet); if (seenPasswordToken) url.password += encodedCodePoints; else url.username += encodedCodePoints; } buffer = ''; } else if ( chr == EOF || chr == '/' || chr == '?' || chr == '#' || (chr == '\\' && isSpecial(url)) ) { if (seenAt && buffer == '') return INVALID_AUTHORITY; pointer -= arrayFrom(buffer).length + 1; buffer = ''; state = HOST; } else buffer += chr; break; case HOST: case HOSTNAME: if (stateOverride && url.scheme == 'file') { state = FILE_HOST; continue; } else if (chr == ':' && !seenBracket) { if (buffer == '') return INVALID_HOST; failure = parseHost(url, buffer); if (failure) return failure; buffer = ''; state = PORT; if (stateOverride == HOSTNAME) return; } else if ( chr == EOF || chr == '/' || chr == '?' || chr == '#' || (chr == '\\' && isSpecial(url)) ) { if (isSpecial(url) && buffer == '') return INVALID_HOST; if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return; failure = parseHost(url, buffer); if (failure) return failure; buffer = ''; state = PATH_START; if (stateOverride) return; continue; } else { if (chr == '[') seenBracket = true; else if (chr == ']') seenBracket = false; buffer += chr; } break; case PORT: if (DIGIT.test(chr)) { buffer += chr; } else if ( chr == EOF || chr == '/' || chr == '?' || chr == '#' || (chr == '\\' && isSpecial(url)) || stateOverride ) { if (buffer != '') { var port = parseInt(buffer, 10); if (port > 0xFFFF) return INVALID_PORT; url.port = (isSpecial(url) && port === specialSchemes[url.scheme]) ? null : port; buffer = ''; } if (stateOverride) return; state = PATH_START; continue; } else return INVALID_PORT; break; case FILE: url.scheme = 'file'; if (chr == '/' || chr == '\\') state = FILE_SLASH; else if (base && base.scheme == 'file') { if (chr == EOF) { url.host = base.host; url.path = base.path.slice(); url.query = base.query; } else if (chr == '?') { url.host = base.host; url.path = base.path.slice(); url.query = ''; state = QUERY; } else if (chr == '#') { url.host = base.host; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; state = FRAGMENT; } else { if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { url.host = base.host; url.path = base.path.slice(); shortenURLsPath(url); } state = PATH; continue; } } else { state = PATH; continue; } break; case FILE_SLASH: if (chr == '/' || chr == '\\') { state = FILE_HOST; break; } if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]); else url.host = base.host; } state = PATH; continue; case FILE_HOST: if (chr == EOF || chr == '/' || chr == '\\' || chr == '?' || chr == '#') { if (!stateOverride && isWindowsDriveLetter(buffer)) { state = PATH; } else if (buffer == '') { url.host = ''; if (stateOverride) return; state = PATH_START; } else { failure = parseHost(url, buffer); if (failure) return failure; if (url.host == 'localhost') url.host = ''; if (stateOverride) return; buffer = ''; state = PATH_START; } continue; } else buffer += chr; break; case PATH_START: if (isSpecial(url)) { state = PATH; if (chr != '/' && chr != '\\') continue; } else if (!stateOverride && chr == '?') { url.query = ''; state = QUERY; } else if (!stateOverride && chr == '#') { url.fragment = ''; state = FRAGMENT; } else if (chr != EOF) { state = PATH; if (chr != '/') continue; } break; case PATH: if ( chr == EOF || chr == '/' || (chr == '\\' && isSpecial(url)) || (!stateOverride && (chr == '?' || chr == '#')) ) { if (isDoubleDot(buffer)) { shortenURLsPath(url); if (chr != '/' && !(chr == '\\' && isSpecial(url))) { url.path.push(''); } } else if (isSingleDot(buffer)) { if (chr != '/' && !(chr == '\\' && isSpecial(url))) { url.path.push(''); } } else { if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) { if (url.host) url.host = ''; buffer = buffer.charAt(0) + ':'; // normalize windows drive letter } url.path.push(buffer); } buffer = ''; if (url.scheme == 'file' && (chr == EOF || chr == '?' || chr == '#')) { while (url.path.length > 1 && url.path[0] === '') { url.path.shift(); } } if (chr == '?') { url.query = ''; state = QUERY; } else if (chr == '#') { url.fragment = ''; state = FRAGMENT; } } else { buffer += percentEncode(chr, pathPercentEncodeSet); } break; case CANNOT_BE_A_BASE_URL_PATH: if (chr == '?') { url.query = ''; state = QUERY; } else if (chr == '#') { url.fragment = ''; state = FRAGMENT; } else if (chr != EOF) { url.path[0] += percentEncode(chr, C0ControlPercentEncodeSet); } break; case QUERY: if (!stateOverride && chr == '#') { url.fragment = ''; state = FRAGMENT; } else if (chr != EOF) { if (chr == "'" && isSpecial(url)) url.query += '%27'; else if (chr == '#') url.query += '%23'; else url.query += percentEncode(chr, C0ControlPercentEncodeSet); } break; case FRAGMENT: if (chr != EOF) url.fragment += percentEncode(chr, fragmentPercentEncodeSet); break; } pointer++; } }; // `URL` constructor // https://url.spec.whatwg.org/#url-class var URLConstructor = function URL(url /* , base */) { var that = anInstance(this, URLConstructor, 'URL'); var base = arguments.length > 1 ? arguments[1] : undefined; var urlString = $toString(url); var state = setInternalState(that, { type: 'URL' }); var baseState, failure; if (base !== undefined) { if (base instanceof URLConstructor) baseState = getInternalURLState(base); else { failure = parseURL(baseState = {}, $toString(base)); if (failure) throw TypeError(failure); } } failure = parseURL(state, urlString, null, baseState); if (failure) throw TypeError(failure); var searchParams = state.searchParams = new URLSearchParams$1(); var searchParamsState = getInternalSearchParamsState(searchParams); searchParamsState.updateSearchParams(state.query); searchParamsState.updateURL = function () { state.query = String(searchParams) || null; }; if (!DESCRIPTORS) { that.href = serializeURL.call(that); that.origin = getOrigin.call(that); that.protocol = getProtocol.call(that); that.username = getUsername.call(that); that.password = getPassword.call(that); that.host = getHost.call(that); that.hostname = getHostname.call(that); that.port = getPort.call(that); that.pathname = getPathname.call(that); that.search = getSearch.call(that); that.searchParams = getSearchParams.call(that); that.hash = getHash.call(that); } }; var URLPrototype = URLConstructor.prototype; var serializeURL = function () { var url = getInternalURLState(this); var scheme = url.scheme; var username = url.username; var password = url.password; var host = url.host; var port = url.port; var path = url.path; var query = url.query; var fragment = url.fragment; var output = scheme + ':'; if (host !== null) { output += '//'; if (includesCredentials(url)) { output += username + (password ? ':' + password : '') + '@'; } output += serializeHost(host); if (port !== null) output += ':' + port; } else if (scheme == 'file') output += '//'; output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; if (query !== null) output += '?' + query; if (fragment !== null) output += '#' + fragment; return output; }; var getOrigin = function () { var url = getInternalURLState(this); var scheme = url.scheme; var port = url.port; if (scheme == 'blob') try { return new URLConstructor(scheme.path[0]).origin; } catch (error) { return 'null'; } if (scheme == 'file' || !isSpecial(url)) return 'null'; return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : ''); }; var getProtocol = function () { return getInternalURLState(this).scheme + ':'; }; var getUsername = function () { return getInternalURLState(this).username; }; var getPassword = function () { return getInternalURLState(this).password; }; var getHost = function () { var url = getInternalURLState(this); var host = url.host; var port = url.port; return host === null ? '' : port === null ? serializeHost(host) : serializeHost(host) + ':' + port; }; var getHostname = function () { var host = getInternalURLState(this).host; return host === null ? '' : serializeHost(host); }; var getPort = function () { var port = getInternalURLState(this).port; return port === null ? '' : String(port); }; var getPathname = function () { var url = getInternalURLState(this); var path = url.path; return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; }; var getSearch = function () { var query = getInternalURLState(this).query; return query ? '?' + query : ''; }; var getSearchParams = function () { return getInternalURLState(this).searchParams; }; var getHash = function () { var fragment = getInternalURLState(this).fragment; return fragment ? '#' + fragment : ''; }; var accessorDescriptor = function (getter, setter) { return { get: getter, set: setter, configurable: true, enumerable: true }; }; if (DESCRIPTORS) { defineProperties(URLPrototype, { // `URL.prototype.href` accessors pair // https://url.spec.whatwg.org/#dom-url-href href: accessorDescriptor(serializeURL, function (href) { var url = getInternalURLState(this); var urlString = $toString(href); var failure = parseURL(url, urlString); if (failure) throw TypeError(failure); getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); }), // `URL.prototype.origin` getter // https://url.spec.whatwg.org/#dom-url-origin origin: accessorDescriptor(getOrigin), // `URL.prototype.protocol` accessors pair // https://url.spec.whatwg.org/#dom-url-protocol protocol: accessorDescriptor(getProtocol, function (protocol) { var url = getInternalURLState(this); parseURL(url, $toString(protocol) + ':', SCHEME_START); }), // `URL.prototype.username` accessors pair // https://url.spec.whatwg.org/#dom-url-username username: accessorDescriptor(getUsername, function (username) { var url = getInternalURLState(this); var codePoints = arrayFrom($toString(username)); if (cannotHaveUsernamePasswordPort(url)) return; url.username = ''; for (var i = 0; i < codePoints.length; i++) { url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet); } }), // `URL.prototype.password` accessors pair // https://url.spec.whatwg.org/#dom-url-password password: accessorDescriptor(getPassword, function (password) { var url = getInternalURLState(this); var codePoints = arrayFrom($toString(password)); if (cannotHaveUsernamePasswordPort(url)) return; url.password = ''; for (var i = 0; i < codePoints.length; i++) { url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet); } }), // `URL.prototype.host` accessors pair // https://url.spec.whatwg.org/#dom-url-host host: accessorDescriptor(getHost, function (host) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; parseURL(url, $toString(host), HOST); }), // `URL.prototype.hostname` accessors pair // https://url.spec.whatwg.org/#dom-url-hostname hostname: accessorDescriptor(getHostname, function (hostname) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; parseURL(url, $toString(hostname), HOSTNAME); }), // `URL.prototype.port` accessors pair // https://url.spec.whatwg.org/#dom-url-port port: accessorDescriptor(getPort, function (port) { var url = getInternalURLState(this); if (cannotHaveUsernamePasswordPort(url)) return; port = $toString(port); if (port == '') url.port = null; else parseURL(url, port, PORT); }), // `URL.prototype.pathname` accessors pair // https://url.spec.whatwg.org/#dom-url-pathname pathname: accessorDescriptor(getPathname, function (pathname) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; url.path = []; parseURL(url, $toString(pathname), PATH_START); }), // `URL.prototype.search` accessors pair // https://url.spec.whatwg.org/#dom-url-search search: accessorDescriptor(getSearch, function (search) { var url = getInternalURLState(this); search = $toString(search); if (search == '') { url.query = null; } else { if ('?' == search.charAt(0)) search = search.slice(1); url.query = ''; parseURL(url, search, QUERY); } getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); }), // `URL.prototype.searchParams` getter // https://url.spec.whatwg.org/#dom-url-searchparams searchParams: accessorDescriptor(getSearchParams), // `URL.prototype.hash` accessors pair // https://url.spec.whatwg.org/#dom-url-hash hash: accessorDescriptor(getHash, function (hash) { var url = getInternalURLState(this); hash = $toString(hash); if (hash == '') { url.fragment = null; return; } if ('#' == hash.charAt(0)) hash = hash.slice(1); url.fragment = ''; parseURL(url, hash, FRAGMENT); }) }); } // `URL.prototype.toJSON` method // https://url.spec.whatwg.org/#dom-url-tojson redefine(URLPrototype, 'toJSON', function toJSON() { return serializeURL.call(this); }, { enumerable: true }); // `URL.prototype.toString` method // https://url.spec.whatwg.org/#URL-stringification-behavior redefine(URLPrototype, 'toString', function toString() { return serializeURL.call(this); }, { enumerable: true }); if (NativeURL) { var nativeCreateObjectURL = NativeURL.createObjectURL; var nativeRevokeObjectURL = NativeURL.revokeObjectURL; // `URL.createObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL // eslint-disable-next-line no-unused-vars -- required for `.length` if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) { return nativeCreateObjectURL.apply(NativeURL, arguments); }); // `URL.revokeObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL // eslint-disable-next-line no-unused-vars -- required for `.length` if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) { return nativeRevokeObjectURL.apply(NativeURL, arguments); }); } setToStringTag(URLConstructor, 'URL'); $$5({ global: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS }, { URL: URLConstructor }); (function (exports) { var global = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; Object.defineProperty(exports, '__esModule', { value: true }); var _classCallCheck = classCallCheck.exports; var _createClass = createClass.exports; var _inherits = inherits.exports; var _possibleConstructorReturn = possibleConstructorReturn.exports; var _getPrototypeOf = getPrototypeOf$2.exports; var _wrapNativeSuper = wrapNativeSuper.exports; var _defineProperty = defineProperty$5.exports; var _asyncToGenerator = asyncToGenerator.exports; var _regeneratorRuntime = require$$8; var _typeof = _typeof$2.exports; var log$2 = loglevel.exports; var operationRetrier = browser$5; var declarativeTypeValidator = browser$7; function _interopDefaultLegacy(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function get() { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck); var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass); var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits); var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn); var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf); var _wrapNativeSuper__default = /*#__PURE__*/_interopDefaultLegacy(_wrapNativeSuper); var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty); var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator); var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime); var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof); var log__namespace = /*#__PURE__*/_interopNamespace(log$2); var rngBrowser = { exports: {} }; // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection // getRandomValues needs to be invoked in a context where "this" is a Crypto // implementation. Also, find the complete implementation of crypto on IE11. var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto); if (getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef rngBrowser.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; } else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); rngBrowser.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid$2(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join(''); } var bytesToUuid_1 = bytesToUuid$2; var rng$1 = rngBrowser.exports; var bytesToUuid$1 = bytesToUuid_1; // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1$1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { var seedBytes = rng$1(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid$1(b); } var v1_1 = v1$1; var rng = rngBrowser.exports; var bytesToUuid = bytesToUuid_1; function v4$1(options, buf, offset) { var i = buf && offset || 0; if (typeof options == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } var v4_1 = v4$1; var v1 = v1_1; var v4 = v4_1; var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; var uuid_1 = uuid; function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * Cancellable promise. Extends the functionality of the native Promise to include the cancel method. * * Example: * * ```ts * * const cancellableFetchPromise = new CancellablePromise(async (resolve, reject, onCancel) => { * const request = fetch("https://example.com/"); * * onCancel(() => request.cancel()); * * try { * const response = await request; * resolve(response); * } catch (err) { * reject(err); * } * }); * * cancellableFetchPromise.cancel(); * ``` */ var CancellablePromise = /*#__PURE__*/function (_Promise) { _inherits__default["default"](CancellablePromise, _Promise); var _super = _createSuper$1(CancellablePromise); /** * Creates a new CancellablePromise. * @param executor A callback used to initialize the promise. This callback is passed three arguments: * a resolve callback used to resolve the promise with a value or the result of another promise, * a reject callback used to reject the promise with a provided reason or error, * and an onCancel callback used to define behavior of cancellation. */ function CancellablePromise(executor) { var _this; _classCallCheck__default["default"](this, CancellablePromise); var outerId = uuid_1.v4(); var outerRejectPromise; _this = _super.call(this, function (resolve, reject) { outerRejectPromise = reject; return executor(function (value) { CancellablePromise.cancellationMap.delete(outerId); resolve(value); }, function (reason) { CancellablePromise.cancellationMap.delete(outerId); reject(reason); }, function (cancellationFunction) { CancellablePromise.cancellationMap.set(outerId, cancellationFunction); }); }); _this.id = outerId; _this.rejectPromise = outerRejectPromise; return _this; } /** * Cancels the promise and invokes the cancellation callback if it was defined during instantiation. Cancellation will result in the promise being rejected. */ _createClass__default["default"](CancellablePromise, [{ key: "cancel", value: function cancel() { var onCancel = CancellablePromise.cancellationMap.get(this.id); onCancel === null || onCancel === void 0 ? void 0 : onCancel(); if (this.rejectPromise) { this.catch(function () { return void 0; }); this.rejectPromise(new Error("Promise was cancelled")); } return this; } }]); return CancellablePromise; }( /*#__PURE__*/_wrapNativeSuper__default["default"](Promise)); _defineProperty__default["default"](CancellablePromise, "cancellationMap", new Map()); function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default["default"](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; } return c > 3 && r && Object.defineProperty(target, key, r), r; } function __metadata(metadataKey, metadataValue) { if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default["default"](Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function prepareLine(prefix, args) { return ["".concat(new Date().toISOString(), " MCS Client ").concat(prefix, ":")].concat(Array.from(args)); } var Logger = /*#__PURE__*/function () { function Logger(prefix) { _classCallCheck__default["default"](this, Logger); _defineProperty__default["default"](this, "prefix", ""); this.prefix = prefix !== null && prefix !== undefined && prefix.length > 0 ? prefix + " " : ""; } _createClass__default["default"](Logger, [{ key: "setLevel", value: function setLevel(level) { log__namespace.setLevel(level); } }, { key: "trace", value: /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ function trace() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log__namespace.trace.apply(null, prepareLine(this.prefix + "T", args)); } }, { key: "debug", value: function debug() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } log__namespace.debug.apply(null, prepareLine(this.prefix + "D", args)); } }, { key: "info", value: function info() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } log__namespace.info.apply(null, prepareLine(this.prefix + "I", args)); } }, { key: "warn", value: function warn() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } log__namespace.warn.apply(null, prepareLine(this.prefix + "W", args)); } }, { key: "error", value: function error() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } log__namespace.error.apply(null, prepareLine(this.prefix + "E", args)); } }], [{ key: "scope", value: function scope(prefix) { return new Logger(prefix); } }, { key: "setLevel", value: function setLevel(level) { log__namespace.setLevel(level); } }, { key: "trace", value: function trace() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } log__namespace.trace.apply(null, prepareLine("T", args)); } }, { key: "debug", value: function debug() { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } log__namespace.debug.apply(null, prepareLine("D", args)); } }, { key: "info", value: function info() { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } log__namespace.info.apply(null, prepareLine("I", args)); } }, { key: "warn", value: function warn() { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { args[_key9] = arguments[_key9]; } log__namespace.warn.apply(null, prepareLine("W", args)); } }, { key: "error", value: function error() { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { args[_key10] = arguments[_key10]; } log__namespace.error.apply(null, prepareLine("E", args)); } }]); return Logger; }(); var MINIMUM_RETRY_DELAY = 1000; var MAXIMUM_RETRY_DELAY = 4000; var MAXIMUM_ATTEMPTS_COUNT = 3; var RETRY_WHEN_THROTTLED = true; var regionalMcsHost = function regionalMcsHost(region) { return "https://mcs.".concat(region !== null && region !== void 0 ? region : "us1", ".twilio.com"); }; var isFullUrl = function isFullUrl(url) { return url.startsWith("http"); }; var fullUrl = function fullUrl(partUrl, region) { return "".concat(!isFullUrl(partUrl) ? regionalMcsHost(region) : "").concat(partUrl); }; var Configuration = /*#__PURE__*/function () { function Configuration(token, baseUrl, baseSetUrl, options) { var _ref, _options$MCS, _ref2, _constructorOptions$r, _constructorOptions$r2, _constructorOptions$b; _classCallCheck__default["default"](this, Configuration); var constructorOptions = (_ref = (_options$MCS = options.MCS) !== null && _options$MCS !== void 0 ? _options$MCS : options) !== null && _ref !== void 0 ? _ref : {}; this.region = (_ref2 = (_constructorOptions$r = constructorOptions.region) !== null && _constructorOptions$r !== void 0 ? _constructorOptions$r : options.region) !== null && _ref2 !== void 0 ? _ref2 : 'us1'; this.mediaUrl = fullUrl(baseUrl, this.region); this.mediaSetUrl = baseSetUrl ? fullUrl(baseSetUrl) : "".concat(this.mediaUrl, "Set"); this.token = token; this.retryWhenThrottledOverride = (_constructorOptions$r2 = constructorOptions.retryWhenThrottledOverride) !== null && _constructorOptions$r2 !== void 0 ? _constructorOptions$r2 : RETRY_WHEN_THROTTLED; this.backoffConfigOverride = (_constructorOptions$b = constructorOptions.backoffConfigOverride) !== null && _constructorOptions$b !== void 0 ? _constructorOptions$b : Configuration.backoffConfigDefault; } _createClass__default["default"](Configuration, [{ key: "updateToken", value: function updateToken(token) { this.token = token; } }], [{ key: "backoffConfigDefault", get: function get() { return { min: MINIMUM_RETRY_DELAY, max: MAXIMUM_RETRY_DELAY, maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT }; } }, { key: "retryWhenThrottledDefault", get: function get() { return RETRY_WHEN_THROTTLED; } }]); return Configuration; }(); /** * @classdesc A Media represents a metadata information for the media upload * @property {String} sid - The server-assigned unique identifier for Media * @property {String} serviceSid - Service instance id which Media belongs/uploaded to * @property {Date} dateCreated - When the Media was created * @property {Date} dateUpdated - When the Media was updated * @property {Number} size - Size of media, bytes * @property {String} contentType - content type of media * @property {String} fileName - file name, if present, null otherwise * @property {MediaCategory} category - attachment category */ var Media = /*#__PURE__*/function () { function Media(config, network, data) { _classCallCheck__default["default"](this, Media); this.config = config; this.network = network; this._update(data); } _createClass__default["default"](Media, [{ key: "sid", get: function get() { return this.state.sid; } }, { key: "serviceSid", get: function get() { return this.state.serviceSid; } }, { key: "dateCreated", get: function get() { return this.state.dateCreated; } }, { key: "dateUpdated", get: function get() { return this.state.dateUpdated; } }, { key: "contentType", get: function get() { return this.state.contentType; } }, { key: "size", get: function get() { return this.state.size; } /** @deprecated Use filename instead */ }, { key: "fileName", get: function get() { return this.state.filename; } }, { key: "filename", get: function get() { return this.state.filename; } }, { key: "category", get: function get() { return this.state.category; } /** * Returns direct content URL to uploaded binary. This URL will expire after some time. * This function gets a new URL every time, preventing it from expiring but putting additional load on backend. * See getCachedContentUrl() for a function that reduces the amount of network requests. * * It is reasonable to build your own refresh logic upon these two functions: as soon as URL returned * by getCachedContentUrl() returns 40x status you should call getContentUrl() to refresh it. */ }, { key: "getContentUrl", value: function getContentUrl() { var _this = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(resolve, reject, onCancel) { var request, response; return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: request = _this.network.get("".concat(_this.config.mediaUrl, "/").concat(_this.sid)); onCancel(function () { return request.cancel(); }); _context.prev = 2; _context.next = 5; return request; case 5: response = _context.sent; _this._update(response.body); resolve(_this.state.contentDirectUrl); _context.next = 13; break; case 10: _context.prev = 10; _context.t0 = _context["catch"](2); reject(_context.t0); case 13: case "end": return _context.stop(); } } }, _callee, null, [[2, 10]]); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }()); } }, { key: "_update", value: function _update(data) { var _data$links$content_d, _data$filename, _data$category, _data$is_multipart_up; this.state = { sid: data.sid, serviceSid: data.service_sid, channelSid: data.channel_sid, messageSid: data.message_sid, dateCreated: data.date_created ? new Date(data.date_created) : null, dateUploadUpdated: data.date_upload_updated ? new Date(data.date_upload_updated) : null, dateUpdated: data.date_updated ? new Date(data.date_updated) : null, size: data.size, contentType: data.content_type, author: data.author, url: data.url, contentUrl: data.links.content, contentDirectUrl: (_data$links$content_d = data.links.content_direct_temporary) !== null && _data$links$content_d !== void 0 ? _data$links$content_d : null, filename: (_data$filename = data.filename) !== null && _data$filename !== void 0 ? _data$filename : null, category: (_data$category = data.category) !== null && _data$category !== void 0 ? _data$category : "media", isMultipartUpstream: (_data$is_multipart_up = data.is_multipart_upstream) !== null && _data$is_multipart_up !== void 0 ? _data$is_multipart_up : false }; } }]); return Media; }(); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TransportError = /*#__PURE__*/function (_Error) { _inherits__default["default"](TransportError, _Error); var _super = _createSuper(TransportError); function TransportError(message, code, body, status, headers) { var _this; _classCallCheck__default["default"](this, TransportError); _this = _super.call(this, message); _this.code = code; _this.body = body; _this.status = status; _this.headers = headers; return _this; } return _createClass__default["default"](TransportError); }( /*#__PURE__*/_wrapNativeSuper__default["default"](Error)); var XHR = global["XMLHttpRequest"] || {}; function parseResponseHeaders(headerString) { if (!headerString) { return {}; } return headerString.split("\r\n").map(function (el) { return el.split(": "); }).filter(function (el) { return el.length === 2 && el[1].length > 0; }).reduce(function (prev, curr) { prev[curr[0]] = curr[1]; return prev; }, {}); } function extractBody(xhr) { var contentType = xhr.getResponseHeader("Content-Type"); if (!contentType || contentType.indexOf("application/json") !== 0 || xhr.responseText.length === 0) { return xhr.responseText; } try { return JSON.parse(xhr.responseText); } catch (e) { return xhr.responseText; } } /** * Provides generic network interface */ var Transport = /*#__PURE__*/function () { function Transport() { _classCallCheck__default["default"](this, Transport); } _createClass__default["default"](Transport, [{ key: "get", value: /** * Make a GET request by given URL */ function get(url, headers) { return Transport.request("GET", url, headers); } /** * Make a POST request by given URL */ }, { key: "post", value: function post(url, headers, body) { return Transport.request("POST", url, headers, body); } }], [{ key: "request", value: function request(method, url, headers, body) { return new CancellablePromise(function (resolve, reject, onCancel) { var xhr = new XHR(); var isCancelled = false; onCancel(function () { xhr.abort(); isCancelled = true; }); xhr.open(method, url, true); xhr.onreadystatechange = function onreadystatechange() { if (xhr.readyState !== 4 || isCancelled) { return; } var responseHeaders = parseResponseHeaders(xhr.getAllResponseHeaders()); var body = extractBody(xhr); if (200 <= xhr.status && xhr.status < 300) { resolve({ status: xhr.status, headers: responseHeaders, body: body }); } else { var _xhr$statusText; var status = (_xhr$statusText = xhr.statusText) !== null && _xhr$statusText !== void 0 ? _xhr$statusText : "NONE"; var bodyRepresentation; if (typeof body === "string") { if (body && body.split("\n", 2).length === 1) bodyRepresentation = body;else { var _body$replace$split$f; // TODO: RTDSDK-3716: investigate why body is HTML string var errorInfo = (_body$replace$split$f = body.replace(/<.*?>/g, "").split(/\r\n/g).filter(function (str) { return str.length; })[0]) === null || _body$replace$split$f === void 0 ? void 0 : _body$replace$split$f.split(" "); bodyRepresentation = (errorInfo === null || errorInfo === void 0 ? void 0 : errorInfo.length) > 2 ? errorInfo === null || errorInfo === void 0 ? void 0 : errorInfo.slice(1).join(" ") : ""; } } else { bodyRepresentation = JSON.stringify(body); } var message = "".concat(xhr.status, ": [").concat(status, "] ").concat(bodyRepresentation); reject(new TransportError(message, xhr.status, body, status, responseHeaders)); } }; for (var headerName in headers) { xhr.setRequestHeader(headerName, headers[headerName]); if (headerName === "Content-Type" && headers[headerName] === "application/json") { body = JSON.stringify(body); } } xhr.send(body); }); } }]); return Transport; }(); var log$1 = Logger.scope("Network"); var Network = /*#__PURE__*/function () { function Network(config, transport) { _classCallCheck__default["default"](this, Network); this.config = config; this.transport = transport; } _createClass__default["default"](Network, [{ key: "backoffConfig", value: function backoffConfig() { return Object.assign(Configuration.backoffConfigDefault, this.config.backoffConfigOverride); } }, { key: "retryWhenThrottled", value: function retryWhenThrottled() { var _ref, _this$config$retryWhe; return (_ref = (_this$config$retryWhe = this.config.retryWhenThrottledOverride) !== null && _this$config$retryWhe !== void 0 ? _this$config$retryWhe : Configuration.retryWhenThrottledDefault) !== null && _ref !== void 0 ? _ref : false; } }, { key: "executeWithRetry", value: function executeWithRetry(request, retryWhenThrottled) { var _this = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref2 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2(resolve, reject, onCancel) { var retrier, codesToRetryOn; return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: retrier = new operationRetrier.Retrier(_this.backoffConfig()); codesToRetryOn = [502, 503, 504]; if (retryWhenThrottled) { codesToRetryOn.push(429); } onCancel(function () { retrier.cancel(); retrier.removeAllListeners(); }); retrier.on("attempt", /*#__PURE__*/_asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() { var requestPromise, result; return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.prev = 0; requestPromise = request(); onCancel(function () { requestPromise.cancel(); retrier.cancel(); retrier.removeAllListeners(); }); _context.next = 5; return requestPromise; case 5: result = _context.sent; retrier.succeeded(result); _context.next = 12; break; case 9: _context.prev = 9; _context.t0 = _context["catch"](0); if (codesToRetryOn.indexOf(_context.t0.status) > -1) { retrier.failed(_context.t0); } else if (_context.t0.message === "Twilsock disconnected") { // Ugly hack. We must make a proper exceptions for twilsock retrier.failed(_context.t0); } else { // Fatal error retrier.removeAllListeners(); retrier.cancel(); reject(_context.t0); } case 12: case "end": return _context.stop(); } } }, _callee, null, [[0, 9]]); }))); retrier.on("succeeded", function (result) { resolve(result); }); retrier.on("cancelled", function (err) { return reject(err); }); retrier.on("failed", function (err) { return reject(err); }); retrier.start(); case 9: case "end": return _context2.stop(); } } }, _callee2); })); return function (_x, _x2, _x3) { return _ref2.apply(this, arguments); }; }()); } }, { key: "get", value: function get(url) { var _this2 = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref4 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(resolve, reject, onCancel) { var headers, request, response; return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: headers = { "X-Twilio-Token": _this2.config.token }; request = _this2.executeWithRetry(function () { return _this2.transport.get(url, headers); }, _this2.retryWhenThrottled()); log$1.trace("sending GET request to ", url, " headers ", headers); onCancel(function () { return request.cancel(); }); _context3.prev = 4; _context3.next = 7; return request; case 7: response = _context3.sent; log$1.trace("response", response); resolve(response); _context3.next = 16; break; case 12: _context3.prev = 12; _context3.t0 = _context3["catch"](4); log$1.debug("get() error ".concat(_context3.t0)); reject(_context3.t0); case 16: case "end": return _context3.stop(); } } }, _callee3, null, [[4, 12]]); })); return function (_x4, _x5, _x6) { return _ref4.apply(this, arguments); }; }()); } }, { key: "post", value: function post(url, category, media, contentType, filename) { var _this3 = this; var headers = { "X-Twilio-Token": this.config.token }; if ((typeof FormData === "undefined" || !(media instanceof FormData)) && contentType) { Object.assign(headers, { "Content-Type": contentType }); } var fullUrl = new URL(url); if (category) { fullUrl.searchParams.append("Category", category); } if (filename) { fullUrl.searchParams.append("Filename", filename); } return new CancellablePromise( /*#__PURE__*/function () { var _ref5 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee4(resolve, reject, onCancel) { var request, response; return _regeneratorRuntime__default["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: request = _this3.transport.post(fullUrl.href, headers, media); onCancel(function () { return request.cancel(); }); log$1.trace("sending POST request to ".concat(url, " with headers ").concat(headers)); _context4.prev = 3; _context4.next = 6; return request; case 6: response = _context4.sent; _context4.next = 17; break; case 9: _context4.prev = 9; _context4.t0 = _context4["catch"](3); if (!(global["XMLHttpRequest"] === undefined && media instanceof FormData)) { _context4.next = 14; break; } reject(new TypeError("Posting FormData supported only with browser engine's FormData")); return _context4.abrupt("return"); case 14: log$1.debug("post() error ".concat(_context4.t0)); reject(_context4.t0); return _context4.abrupt("return"); case 17: log$1.trace("response", response); resolve(response); case 19: case "end": return _context4.stop(); } } }, _callee4, null, [[3, 9]]); })); return function (_x7, _x8, _x9) { return _ref5.apply(this, arguments); }; }()); } }]); return Network; }(); var version = "0.6.4"; var _class; var log = Logger.scope(""); /** * @classdesc A Client provides an interface for Media Content Service */ exports["default"] = (_class = /*#__PURE__*/function () { // eslint-disable-next-line /** * Base URLs must be full URLs with host. If host is not provided it will be generated from a default configuration * template using options.region. * * @param {String} token - Access token * @param {String} baseUrl - Base URL for Media Content Service Media resource, i.e. /v1/Services/{serviceSid}/Media * @param {String} baseSetUrl - Base URL for Media Content Service MediaSet resource, i.e. /v1/Services/{serviceSid}/MediaSet * @param {Client#ClientOptions} [options] - Options to customize the Client */ function Client(token, baseUrl, baseSetUrl) { var _this$options$logLeve, _this$options$transpo; var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; _classCallCheck__default["default"](this, Client); this.options = options; this.options.logLevel = (_this$options$logLeve = this.options.logLevel) !== null && _this$options$logLeve !== void 0 ? _this$options$logLeve : "silent"; this.config = new Configuration(token, baseUrl, baseSetUrl, this.options); log.setLevel(this.options.logLevel); this.options.transport = (_this$options$transpo = this.options.transport) !== null && _this$options$transpo !== void 0 ? _this$options$transpo : new Transport(); this.transport = this.options.transport; this.network = new Network(this.config, this.transport); } /** * These options can be passed to Client constructor * @typedef {Object} Client#ClientOptions * @property {String} [logLevel='silent'] - The level of logging to enable. Valid options * (from strictest to broadest): ['silent', 'error', 'warn', 'info', 'debug', 'trace'] */ /** * Update the token used for Client operations * @param {String} token - The JWT string of the new token * @returns {void} */ _createClass__default["default"](Client, [{ key: "updateToken", value: function updateToken(token) { log.info("updateToken"); this.config.updateToken(token); } /** * Gets media from media service * @param {String} sid - Media's SID */ }, { key: "get", value: function get(sid) { var _this = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(resolve, reject, onCancel) { var request, response; return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: request = _this.network.get("".concat(_this.config.mediaUrl, "/").concat(sid)); onCancel(function () { return request.cancel(); }); _context.prev = 2; _context.next = 5; return request; case 5: response = _context.sent; resolve(new Media(_this.config, _this.network, response.body)); _context.next = 12; break; case 9: _context.prev = 9; _context.t0 = _context["catch"](2); reject(_context.t0); case 12: case "end": return _context.stop(); } } }, _callee, null, [[2, 9]]); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }()); } /** * Posts raw content to media service * @param {String} contentType - content type of media * @param {String|Buffer|Blob} media - content to post * @param {MediaCategory|null} category - category for the media */ }, { key: "post", value: function post(contentType, media, category, filename) { var _this2 = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref2 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2(resolve, reject, onCancel) { var request, response; return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: request = _this2.network.post(_this2.config.mediaUrl, category !== null && category !== void 0 ? category : "media", media, contentType, filename); onCancel(function () { return request.cancel(); }); _context2.prev = 2; _context2.next = 5; return request; case 5: response = _context2.sent; resolve(new Media(_this2.config, _this2.network, response.body)); _context2.next = 12; break; case 9: _context2.prev = 9; _context2.t0 = _context2["catch"](2); reject(_context2.t0); case 12: case "end": return _context2.stop(); } } }, _callee2, null, [[2, 9]]); })); return function (_x4, _x5, _x6) { return _ref2.apply(this, arguments); }; }()); } /** * Posts FormData to media service. Can be used only with browser engine's FormData. * In non-browser FormData case the method will do promise reject with * new TypeError("Posting FormData supported only with browser engine's FormData") * @param {FormData} formData - form data to post * @param {MediaCategory|null} category - category for the media */ }, { key: "postFormData", value: function postFormData(formData, category) { var _this3 = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref3 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(resolve, reject, onCancel) { var request, response; return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: request = _this3.network.post(_this3.config.mediaUrl, category !== null && category !== void 0 ? category : "media", formData); onCancel(function () { return request.cancel(); }); _context3.prev = 2; _context3.next = 5; return request; case 5: response = _context3.sent; resolve(new Media(_this3.config, _this3.network, response.body)); _context3.next = 12; break; case 9: _context3.prev = 9; _context3.t0 = _context3["catch"](2); reject(_context3.t0); case 12: case "end": return _context3.stop(); } } }, _callee3, null, [[2, 9]]); })); return function (_x7, _x8, _x9) { return _ref3.apply(this, arguments); }; }()); } /** * Retrieve information about multiple media SIDs at the same time. * @param mediaSids Array of Media SIDs to get information from. */ }, { key: "mediaSetGet", value: function mediaSetGet(mediaSids) { var _this4 = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref4 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee4(resolve, reject, onCancel) { var query, request, response, media; return _regeneratorRuntime__default["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: query = { command: "get", list: mediaSids.map(function (sid) { return { media_sid: sid }; }) }; request = _this4.network.post("".concat(_this4.config.mediaSetUrl), null, query, "application/json"); onCancel(function () { return request.cancel(); }); _context4.prev = 3; _context4.next = 6; return request; case 6: response = _context4.sent; media = response.body.map(function (item) { if (item.code !== 200) { reject("Failed to obtain detailed information about Media items (failed SID ".concat(item.media_record.sid, ")")); return; } return new Media(_this4.config, _this4.network, item.media_record); }); resolve(media); _context4.next = 14; break; case 11: _context4.prev = 11; _context4.t0 = _context4["catch"](3); reject(_context4.t0); case 14: case "end": return _context4.stop(); } } }, _callee4, null, [[3, 11]]); })); return function (_x10, _x11, _x12) { return _ref4.apply(this, arguments); }; }()); } /** * Retrieve temporary URLs for a set of media SIDs. * @param mediaSids array of the media SIDs to get URLs from. */ }, { key: "mediaSetGetContentUrls", value: function mediaSetGetContentUrls(mediaSids) { var _this5 = this; return new CancellablePromise( /*#__PURE__*/function () { var _ref5 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee5(resolve, reject, onCancel) { var query, request, response, urls; return _regeneratorRuntime__default["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: query = { command: "get", list: mediaSids.map(function (sid) { return { media_sid: sid }; }) }; request = _this5.network.post("".concat(_this5.config.mediaSetUrl), null, query, "application/json"); onCancel(function () { return request.cancel(); }); _context5.prev = 3; _context5.next = 6; return request; case 6: response = _context5.sent; urls = new Map(); response.body.forEach(function (item) { if (item.code !== 200) { reject("Failed to obtain detailed information about Media items (failed SID ".concat(item.media_record.sid, ")")); return; } urls.set(item.media_record.sid, item.media_record.links.content_direct_temporary); }); resolve(urls); _context5.next = 15; break; case 12: _context5.prev = 12; _context5.t0 = _context5["catch"](3); reject(_context5.t0); case 15: case "end": return _context5.stop(); } } }, _callee5, null, [[3, 12]]); })); return function (_x13, _x14, _x15) { return _ref5.apply(this, arguments); }; }()); } }]); return Client; }(), _defineProperty__default["default"](_class, "version", version), _class); __decorate([declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", void 0)], exports["default"].prototype, "updateToken", null); __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", CancellablePromise)], exports["default"].prototype, "get", null); exports["default"] = __decorate([declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, declarativeTypeValidator.nonEmptyString, [declarativeTypeValidator.nonEmptyString, declarativeTypeValidator.literal(null)], [declarativeTypeValidator.pureObject, "undefined"]), __metadata("design:paramtypes", [String, String, Object, Object])], exports["default"]); // Proper renames should happen in index.ts, exports.CancellablePromise = CancellablePromise; exports.Client = exports["default"]; exports.McsClient = exports["default"]; exports.McsMedia = Media; exports.Media = Media; })(browser$1); var ArrayBufferViewCore = arrayBufferViewCore; var toLength$1 = toLength$o; var toInteger = toInteger$a; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.at` method // https://github.com/tc39/proposal-relative-indexing-method exportTypedArrayMethod('at', function at(index) { var O = aTypedArray(this); var len = toLength$1(O.length); var relativeIndex = toInteger(index); var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex; return (k < 0 || k >= len) ? undefined : O[k]; }); var $$4 = _export; var global$1 = global$D; var arrayBufferModule = arrayBuffer; var setSpecies = setSpecies$4; var ARRAY_BUFFER = 'ArrayBuffer'; var ArrayBuffer$1 = arrayBufferModule[ARRAY_BUFFER]; var NativeArrayBuffer = global$1[ARRAY_BUFFER]; // `ArrayBuffer` constructor // https://tc39.es/ecma262/#sec-arraybuffer-constructor $$4({ global: true, forced: NativeArrayBuffer !== ArrayBuffer$1 }, { ArrayBuffer: ArrayBuffer$1 }); setSpecies(ARRAY_BUFFER); function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var log$6 = Logger.scope("Participant"); /** * A participant represents a remote client in a conversation. */ var Participant = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Participant, _ReplayEventEmitter); var _super = _createSuper$7(Participant); /** * @internal */ function Participant(data, sid, conversation, links, services) { var _data$roleSid, _data$bindings; var _this; _classCallCheck$4(this, Participant); _this = _super.call(this); _this.conversation = conversation; _this.links = links; _this.services = services; _this.state = { attributes: parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " + sid, log$6), dateCreated: data.dateCreated ? parseTime(data.dateCreated) : null, dateUpdated: data.dateCreated ? parseTime(data.dateUpdated) : null, sid: sid, typingTimeout: null, isTyping: false, identity: data.identity, roleSid: (_data$roleSid = data.roleSid) !== null && _data$roleSid !== void 0 ? _data$roleSid : "", lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex) ? data.lastConsumedMessageIndex : null, lastReadTimestamp: data.lastConsumptionTimestamp ? parseTime(data.lastConsumptionTimestamp) : null, type: data.type || "chat", userInfo: data.userInfo, bindings: (_data$bindings = data.bindings) !== null && _data$bindings !== void 0 ? _data$bindings : {} }; if (!data.identity && !data.type) { throw new Error("Received invalid Participant object from server: Missing identity or type of Participant."); } return _this; } /** * Fired when the participant has started typing. * * Parameters: * 1. {@link Participant} `participant` - the participant in question * @event */ _createClass$4(Participant, [{ key: "sid", get: /** * Conversation that the remote client is a participant of. */ /** * The server-assigned unique identifier for the participant. */ function get() { return this.state.sid; } /** * Custom attributes of the participant. */ }, { key: "attributes", get: function get() { return this.state.attributes; } /** * Date this participant was created on. */ }, { key: "dateCreated", get: function get() { return this.state.dateCreated; } /** * Date this participant was last updated on. */ }, { key: "dateUpdated", get: function get() { return this.state.dateUpdated; } /** * Identity of the participant. */ }, { key: "identity", get: function get() { return this.state.identity; } /** * Indicates whether the participant is currently typing. */ }, { key: "isTyping", get: function get() { return this.state.isTyping; } /** * The index of the last read message by the participant. * Note that retrieving messages on a client endpoint does not mean that messages are read, * please consider reading about the [Read Horizon feature](https://www.twilio.com/docs/api/chat/guides/consumption-horizon) * to find out about the proper way to mark messages as read. */ }, { key: "lastReadMessageIndex", get: function get() { return this.state.lastReadMessageIndex; } /** * Date of the most recent read horizon update. */ }, { key: "lastReadTimestamp", get: function get() { return this.state.lastReadTimestamp; } }, { key: "roleSid", get: function get() { return this.state.roleSid; } /** * Type of the participant. */ }, { key: "type", get: function get() { return this.state.type; } /** * Get the bindings mapping for the current participant. * Available binding depends on the participant type. * You could access it as `participant.bindings.sms?.address` or * using the type dynamically `participant.bindings[participant.type]` * just be aware that the binding information has different structure for * each participant type. * See also {ParticipantEmailBinding}, the only available currently binding descriptor. */ }, { key: "bindings", get: function get() { var _this$state$bindings; return (_this$state$bindings = this.state.bindings) !== null && _this$state$bindings !== void 0 ? _this$state$bindings : {}; } }, { key: "_startTyping", value: /** * Internal method used to start or reset the typing indicator timeout (with event emitting). * @internal */ function _startTyping(timeout) { var _this2 = this; if (this.state.typingTimeout) { clearTimeout(this.state.typingTimeout); } this.state.isTyping = true; this.emit("typingStarted", this); this.conversation.emit("typingStarted", this); this.state.typingTimeout = Number(setTimeout(function () { return _this2._endTyping(); }, timeout)); return this; } /** * Internal method function used to stop the typing indicator timeout (with event emitting). * @internal */ }, { key: "_endTyping", value: function _endTyping() { if (!this.state.typingTimeout) { return; } this.state.isTyping = false; this.emit("typingEnded", this); this.conversation.emit("typingEnded", this); clearInterval(this.state.typingTimeout); this.state.typingTimeout = null; } /** * Internal method function used update local object's property roleSid with a new value. * @internal */ }, { key: "_update", value: function _update(data) { var updateReasons = []; var updateAttributes = parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " + this.state.sid, log$6); if (data.attributes && !isEqual(this.state.attributes, updateAttributes)) { this.state.attributes = updateAttributes; updateReasons.push("attributes"); } var updatedDateUpdated = parseTime(data.dateUpdated); if (data.dateUpdated && (updatedDateUpdated === null || updatedDateUpdated === void 0 ? void 0 : updatedDateUpdated.getTime()) !== (this.state.dateUpdated && this.state.dateUpdated.getTime())) { this.state.dateUpdated = updatedDateUpdated; updateReasons.push("dateUpdated"); } var updatedDateCreated = parseTime(data.dateCreated); if (data.dateCreated && (updatedDateCreated === null || updatedDateCreated === void 0 ? void 0 : updatedDateCreated.getTime()) !== (this.state.dateCreated && this.state.dateCreated.getTime())) { this.state.dateCreated = updatedDateCreated; updateReasons.push("dateCreated"); } if (data.roleSid && this.state.roleSid !== data.roleSid) { this.state.roleSid = data.roleSid; updateReasons.push("roleSid"); } if ((Number.isInteger(data.lastConsumedMessageIndex) || data.lastConsumedMessageIndex === null) && this.state.lastReadMessageIndex !== data.lastConsumedMessageIndex) { this.state.lastReadMessageIndex = data.lastConsumedMessageIndex; updateReasons.push("lastReadMessageIndex"); } if (data.lastConsumptionTimestamp) { var lastReadTimestamp = new Date(data.lastConsumptionTimestamp); if (!this.state.lastReadTimestamp || this.state.lastReadTimestamp.getTime() !== lastReadTimestamp.getTime()) { this.state.lastReadTimestamp = lastReadTimestamp; updateReasons.push("lastReadTimestamp"); } } if (data.bindings && !isEqual(this.state.bindings, data.bindings)) { this.state.bindings = data.bindings; updateReasons.push("bindings"); } if (updateReasons.length > 0) { this.emit("updated", { participant: this, updateReasons: updateReasons }); } return this; } /** * Get the user for this participant and subscribes to it. Supported only for participants of type `chat`. */ }, { key: "getUser", value: function () { var _getUser = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee() { return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(this.type != "chat")) { _context.next = 2; break; } throw new Error("Getting User is not supported for this Participant type: " + this.type); case 2: return _context.abrupt("return", this.services.users.getUser(this.state.identity, this.state.userInfo)); case 3: case "end": return _context.stop(); } } }, _callee, this); })); function getUser() { return _getUser.apply(this, arguments); } return getUser; }() /** * Remove the participant from the conversation. */ }, { key: "remove", value: function () { var _remove = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2() { return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: return _context2.abrupt("return", this.conversation.removeParticipant(this)); case 1: case "end": return _context2.stop(); } } }, _callee2, this); })); function remove() { return _remove.apply(this, arguments); } return remove; }() /** * Update the attributes of the participant. * @param attributes New attributes. */ }, { key: "updateAttributes", value: function () { var _updateAttributes = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3(attributes) { return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.services.commandExecutor.mutateResource("post", this.links.self, { attributes: JSON.stringify(attributes) }); case 2: return _context3.abrupt("return", this); case 3: case "end": return _context3.stop(); } } }, _callee3, this); })); function updateAttributes(_x) { return _updateAttributes.apply(this, arguments); } return updateAttributes; }() }]); return Participant; }(ReplayEventEmitter_1); _defineProperty$3(Participant, "typingStarted", "typingStarted"); _defineProperty$3(Participant, "typingEnded", "typingEnded"); _defineProperty$3(Participant, "updated", "updated"); __decorate$1([validateTypesAsync_1(json), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Promise)], Participant.prototype, "updateAttributes", null); function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var log$5 = Logger.scope("Participants"); /** * @classdesc Represents the collection of participants for the conversation * @fires Participants#participantJoined * @fires Participants#participantLeft * @fires Participants#participantUpdated */ var Participants = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Participants, _ReplayEventEmitter); var _super = _createSuper$6(Participants); function Participants(conversation, participants, links, configuration, services) { var _this; _classCallCheck$4(this, Participants); _this = _super.call(this); _defineProperty$3(_assertThisInitialized$3(_this), "rosterEntityPromise", null); _this.conversation = conversation; _this.participants = participants; _this.links = links; _this.configuration = configuration; _this.services = services; return _this; } _createClass$4(Participants, [{ key: "unsubscribe", value: function () { var _unsubscribe = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee() { var entity; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!this.rosterEntityPromise) { _context.next = 6; break; } _context.next = 3; return this.rosterEntityPromise; case 3: entity = _context.sent; entity.close(); this.rosterEntityPromise = null; case 6: case "end": return _context.stop(); } } }, _callee, this); })); function unsubscribe() { return _unsubscribe.apply(this, arguments); } return unsubscribe; }() }, { key: "subscribe", value: function subscribe(arg) { var _this2 = this; var participantsMapPromise = typeof arg === "string" ? this.services.syncClient.map({ id: arg, mode: "open_existing" }) : Promise.resolve(arg); return this.rosterEntityPromise = this.rosterEntityPromise || participantsMapPromise.then(function (rosterMap) { rosterMap.on("itemAdded", function (args) { log$5.debug(_this2.conversation.sid + " itemAdded: " + args.item.key); _this2.upsertParticipant(args.item.key, args.item.data).then(function (participant) { _this2.emit("participantJoined", participant); }); }); rosterMap.on("itemRemoved", function (args) { log$5.debug(_this2.conversation.sid + " itemRemoved: " + args.key); var participantSid = args.key; if (!_this2.participants.has(participantSid)) { return; } var leftParticipant = _this2.participants.get(participantSid); _this2.participants.delete(participantSid); if (!leftParticipant) { return; } _this2.emit("participantLeft", leftParticipant); }); rosterMap.on("itemUpdated", function (args) { log$5.debug(_this2.conversation.sid + " itemUpdated: " + args.item.key); _this2.upsertParticipant(args.item.key, args.item.data); }); var participantsPromises = []; var rosterMapHandler = function rosterMapHandler(paginator) { paginator.items.forEach(function (item) { participantsPromises.push(_this2.upsertParticipant(item.key, item.data)); }); return paginator.hasNextPage ? paginator.nextPage().then(rosterMapHandler) : null; }; return rosterMap.getItems().then(rosterMapHandler).then(function () { return Promise.all(participantsPromises); }).then(function () { return rosterMap; }); }).catch(function (err) { _this2.rosterEntityPromise = null; if (_this2.services.syncClient.connectionState != "disconnected") { log$5.error("Failed to get roster object for conversation", _this2.conversation.sid, err); } log$5.debug("ERROR: Failed to get roster object for conversation", _this2.conversation.sid, err); throw err; }); } }, { key: "upsertParticipantFromResponse", value: function () { var _upsertParticipantFromResponse = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2(data) { var _messagingBinding$typ; var sid, responseAttributes, dateCreated, dateUpdated, responseIdentity, roleSid, messagingBinding; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: sid = data.sid, responseAttributes = data.attributes, dateCreated = data.date_created, dateUpdated = data.date_updated, responseIdentity = data.identity, roleSid = data.role_sid, messagingBinding = data.messaging_binding; _context2.next = 3; return this.upsertParticipant(sid, { attributes: responseAttributes, dateCreated: new Date(dateCreated), dateUpdated: new Date(dateUpdated), identity: responseIdentity, roleSid: roleSid, lastConsumedMessageIndex: null, lastConsumptionTimestamp: null, type: (_messagingBinding$typ = messagingBinding === null || messagingBinding === void 0 ? void 0 : messagingBinding.type) !== null && _messagingBinding$typ !== void 0 ? _messagingBinding$typ : "chat" }); case 3: return _context2.abrupt("return", _context2.sent); case 4: case "end": return _context2.stop(); } } }, _callee2, this); })); function upsertParticipantFromResponse(_x) { return _upsertParticipantFromResponse.apply(this, arguments); } return upsertParticipantFromResponse; }() }, { key: "upsertParticipant", value: function () { var _upsertParticipant = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3(participantSid, data) { var _this3 = this; var participant, links; return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: participant = this.participants.get(participantSid); if (!participant) { _context3.next = 3; break; } return _context3.abrupt("return", participant._update(data)); case 3: links = { self: "".concat(this.links.participants, "/").concat(participantSid) }; participant = new Participant(data, participantSid, this.conversation, links, this.services); this.participants.set(participantSid, participant); participant.on("updated", function (args) { return _this3.emit("participantUpdated", args); }); return _context3.abrupt("return", participant); case 8: case "end": return _context3.stop(); } } }, _callee3, this); })); function upsertParticipant(_x2, _x3) { return _upsertParticipant.apply(this, arguments); } return upsertParticipant; }() /** * @returns {Promise>} returns list of participants {@see Participant} */ }, { key: "getParticipants", value: function () { var _getParticipants = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee4() { var _this4 = this; return _regeneratorRuntime$1.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: return _context4.abrupt("return", this.rosterEntityPromise ? this.rosterEntityPromise.then(function () { var participants = []; _this4.participants.forEach(function (participant) { return participants.push(participant); }); return participants; }) : []); case 1: case "end": return _context4.stop(); } } }, _callee4, this); })); function getParticipants() { return _getParticipants.apply(this, arguments); } return getParticipants; }() /** * Get participant by SID from conversation * @returns {Promise} */ }, { key: "getParticipantBySid", value: function () { var _getParticipantBySid = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee5(participantSid) { var _this5 = this; return _regeneratorRuntime$1.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: return _context5.abrupt("return", this.rosterEntityPromise ? this.rosterEntityPromise.then(function () { var participant = _this5.participants.get(participantSid); if (!participant) { throw new Error("Participant with SID " + participantSid + " was not found"); } return participant; }) : null); case 1: case "end": return _context5.stop(); } } }, _callee5, this); })); function getParticipantBySid(_x4) { return _getParticipantBySid.apply(this, arguments); } return getParticipantBySid; }() /** * Get participant by identity from conversation * @returns {Promise} */ }, { key: "getParticipantByIdentity", value: function () { var _getParticipantByIdentity = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee6(identity) { var _this6 = this; var foundParticipant; return _regeneratorRuntime$1.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: foundParticipant = null; return _context6.abrupt("return", this.rosterEntityPromise ? this.rosterEntityPromise.then(function () { _this6.participants.forEach(function (participant) { if (participant.identity === identity) { foundParticipant = participant; } }); if (!foundParticipant) { throw new Error("Participant with identity " + identity + " was not found"); } return foundParticipant; }) : null); case 2: case "end": return _context6.stop(); } } }, _callee6, this); })); function getParticipantByIdentity(_x5) { return _getParticipantByIdentity.apply(this, arguments); } return getParticipantByIdentity; }() /** * Add a chat participant to the conversation */ }, { key: "add", value: function () { var _add = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee7(identity, attributes) { return _regeneratorRuntime$1.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return this.services.commandExecutor.mutateResource("post", this.links.participants, { identity: identity, attributes: typeof attributes !== "undefined" ? JSON.stringify(attributes) : undefined }); case 2: return _context7.abrupt("return", _context7.sent); case 3: case "end": return _context7.stop(); } } }, _callee7, this); })); function add(_x6, _x7) { return _add.apply(this, arguments); } return add; }() /** * Add a non-chat participant to the conversation. */ }, { key: "addNonChatParticipant", value: function () { var _addNonChatParticipant = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee8(proxyAddress, address) { var _bindingOptions$email, _bindingOptions$email2; var attributes, bindingOptions, _args8 = arguments; return _regeneratorRuntime$1.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: attributes = _args8.length > 2 && _args8[2] !== undefined ? _args8[2] : {}; bindingOptions = _args8.length > 3 && _args8[3] !== undefined ? _args8[3] : {}; _context8.next = 4; return this.services.commandExecutor.mutateResource("post", this.links.participants, { attributes: typeof attributes !== "undefined" ? JSON.stringify(attributes) : undefined, messaging_binding: { address: address, proxy_address: proxyAddress, name: bindingOptions === null || bindingOptions === void 0 ? void 0 : (_bindingOptions$email = bindingOptions.email) === null || _bindingOptions$email === void 0 ? void 0 : _bindingOptions$email.name, level: bindingOptions === null || bindingOptions === void 0 ? void 0 : (_bindingOptions$email2 = bindingOptions.email) === null || _bindingOptions$email2 === void 0 ? void 0 : _bindingOptions$email2.level } }); case 4: return _context8.abrupt("return", _context8.sent); case 5: case "end": return _context8.stop(); } } }, _callee8, this); })); function addNonChatParticipant(_x8, _x9) { return _addNonChatParticipant.apply(this, arguments); } return addNonChatParticipant; }() /** * Remove the participant with a given identity from a conversation. */ }, { key: "remove", value: function remove(identity) { return this.services.commandExecutor.mutateResource("delete", "".concat(this.links.participants, "/").concat(encodeURIComponent(identity))); } }]); return Participants; }(ReplayEventEmitter_1); /** * Fired when participant joined conversation * @event Participants#participantJoined * @type {Participant} */ /** * Fired when participant left conversation * @event Participants#participantLeft * @type {Participant} */ /** * Fired when participant updated * @event Participants#participantUpdated * @type {Object} * @property {Participant} participant - Updated Participant * @property {Participant#UpdateReason[]} updateReasons - Array of Participant's updated event reasons */ var $$3 = _export; var aFunction = aFunction$9; var toObject = toObject$g; var toLength = toLength$o; var toString$1 = toString$d; var fails$1 = fails$B; var internalSort = arraySort; var arrayMethodIsStrict = arrayMethodIsStrict$4; var FF = engineFfVersion; var IE_OR_EDGE = engineIsIeOrEdge; var V8 = engineV8Version; var WEBKIT = engineWebkitVersion; var test = []; var nativeSort = test.sort; // IE8- var FAILS_ON_UNDEFINED = fails$1(function () { test.sort(undefined); }); // V8 bug var FAILS_ON_NULL = fails$1(function () { test.sort(null); }); // Old WebKit var STRICT_METHOD = arrayMethodIsStrict('sort'); var STABLE_SORT = !fails$1(function () { // feature detection can be too slow, so check engines versions if (V8) return V8 < 70; if (FF && FF > 3) return; if (IE_OR_EDGE) return true; if (WEBKIT) return WEBKIT < 603; var result = ''; var code, chr, value, index; // generate an array with more 512 elements (Chakra and old V8 fails only in this case) for (code = 65; code < 76; code++) { chr = String.fromCharCode(code); switch (code) { case 66: case 69: case 70: case 72: value = 3; break; case 68: case 71: value = 4; break; default: value = 2; } for (index = 0; index < 47; index++) { test.push({ k: chr + index, v: value }); } } test.sort(function (a, b) { return b.v - a.v; }); for (index = 0; index < test.length; index++) { chr = test[index].k.charAt(0); if (result.charAt(result.length - 1) !== chr) result += chr; } return result !== 'DGBEFHACIJK'; }); var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD || !STABLE_SORT; var getSortCompare = function (comparefn) { return function (x, y) { if (y === undefined) return -1; if (x === undefined) return 1; if (comparefn !== undefined) return +comparefn(x, y) || 0; return toString$1(x) > toString$1(y) ? 1 : -1; }; }; // `Array.prototype.sort` method // https://tc39.es/ecma262/#sec-array.prototype.sort $$3({ target: 'Array', proto: true, forced: FORCED }, { sort: function sort(comparefn) { if (comparefn !== undefined) aFunction(comparefn); var array = toObject(this); if (STABLE_SORT) return comparefn === undefined ? nativeSort.call(array) : nativeSort.call(array, comparefn); var items = []; var arrayLength = toLength(array.length); var itemsLength, index; for (index = 0; index < arrayLength; index++) { if (index in array) items.push(array[index]); } items = internalSort(items, getSortCompare(comparefn)); itemsLength = items.length; index = 0; while (index < itemsLength) array[index] = items[index++]; while (index < arrayLength) delete array[index++]; return array; } }); var $$2 = _export; var notARegExp = notARegexp; var requireObjectCoercible = requireObjectCoercible$a; var toString = toString$d; var correctIsRegExpLogic = correctIsRegexpLogic; // `String.prototype.includes` method // https://tc39.es/ecma262/#sec-string.prototype.includes $$2({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, { includes: function includes(searchString /* , position = 0 */) { return !!~toString(requireObjectCoercible(this)) .indexOf(toString(notARegExp(searchString)), arguments.length > 1 ? arguments[1] : undefined); } }); /** * Represents a media information for a message in a conversation. */ var Media = /*#__PURE__*/function () { /** * @internal */ function Media(data, services) { _classCallCheck$4(this, Media); _defineProperty$3(this, "mcsMedia", null); this.services = services; if (data instanceof browser$1.McsMedia) { this.mcsMedia = data; } this.state = { sid: data.sid, category: data.category, filename: data.filename, contentType: data.contentType, size: data.size }; } /** * Server-assigned unique identifier for the media. */ _createClass$4(Media, [{ key: "sid", get: function get() { return this.state.sid; } /** * File name. Null if absent. */ }, { key: "filename", get: function get() { return this.state.filename; } /** * Content type of the media. */ }, { key: "contentType", get: function get() { return this.state.contentType; } /** * Size of the media in bytes. */ }, { key: "size", get: function get() { return this.state.size; } /** * Media category, can be one of the {@link MediaCategory} values. */ }, { key: "category", get: function get() { return this.state.category; } /** * Returns the direct content URL for the media. * * This URL is impermanent, it will expire in several minutes and cannot be cached. * If the URL becomes expired, you need to request a new one. * Each call to this function produces a new temporary URL. */ }, { key: "getContentTemporaryUrl", value: function getContentTemporaryUrl() { var _this = this; return new browser$1.CancellablePromise( /*#__PURE__*/function () { var _ref = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(resolve, reject, onCancel) { var _this$mcsMedia; var fetchMediaRequest, contentUrlRequest, mcsMedia; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: fetchMediaRequest = _this._fetchMcsMedia(); contentUrlRequest = (_this$mcsMedia = _this.mcsMedia) === null || _this$mcsMedia === void 0 ? void 0 : _this$mcsMedia.getContentUrl(); onCancel(function () { fetchMediaRequest.cancel(); if (contentUrlRequest) { contentUrlRequest.cancel(); } }); _context.prev = 3; if (_this.mcsMedia) { _context.next = 9; break; } _context.next = 7; return fetchMediaRequest; case 7: mcsMedia = _context.sent; contentUrlRequest = mcsMedia.getContentUrl(); case 9: _context.t0 = resolve; if (!contentUrlRequest) { _context.next = 16; break; } _context.next = 13; return contentUrlRequest; case 13: _context.t1 = _context.sent; _context.next = 17; break; case 16: _context.t1 = null; case 17: _context.t2 = _context.t1; (0, _context.t0)(_context.t2); _context.next = 24; break; case 21: _context.prev = 21; _context.t3 = _context["catch"](3); reject(_context.t3); case 24: case "end": return _context.stop(); } } }, _callee, null, [[3, 21]]); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }()); } }, { key: "_fetchMcsMedia", value: function _fetchMcsMedia() { var _this2 = this; return new browser$1.CancellablePromise( /*#__PURE__*/function () { var _ref2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2(resolve, reject, onCancel) { var request; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: request = _this2.services.mcsClient.get(_this2.state.sid); if (!_this2.services.mcsClient) { _context2.next = 14; break; } onCancel(function () { return request.cancel(); }); _context2.prev = 3; _context2.next = 6; return request; case 6: _this2.mcsMedia = _context2.sent; resolve(_this2.mcsMedia); _context2.next = 13; break; case 10: _context2.prev = 10; _context2.t0 = _context2["catch"](3); reject(_context2.t0); case 13: return _context2.abrupt("return"); case 14: reject(new Error("Media Content Service is unavailable")); case 15: case "end": return _context2.stop(); } } }, _callee2, null, [[3, 10]]); })); return function (_x4, _x5, _x6) { return _ref2.apply(this, arguments); }; }()); } }]); return Media; }(); /** * Contains aggregated information about delivery statuses of a message across all participants * of a conversation. * * At any moment during the message delivery to a participant, the message can have zero or more of the following * delivery statuses: * * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message. * * Message is considered as **delivered** to a participant if Twilio has received confirmation of message * delivery from the upstream carrier, and, where available, the destination handset. * * Message considered as **undelivered** to a participant if Twilio has received a delivery receipt * indicating that the message was not delivered. This can happen for many reasons including carrier content * filtering and the availability of the destination handset. * * Message considered as **read** by a participant if the message has been delivered and opened by the * recipient in a conversation. The recipient must have enabled the read receipts. * * Message considered as **failed** to be delivered to a participant if the message could not be sent. * This can happen for various reasons including queue overflows, account suspensions and media * errors (in the case of MMS for instance). * * {@link AggregatedDeliveryReceipt} class contains an aggregated value {@link DeliveryAmount} for each delivery status. */ var AggregatedDeliveryReceipt = /*#__PURE__*/function () { /** * @internal */ function AggregatedDeliveryReceipt(data) { _classCallCheck$4(this, AggregatedDeliveryReceipt); this.state = data; } /** * Maximum number of delivery events expected for the message. */ _createClass$4(AggregatedDeliveryReceipt, [{ key: "total", get: function get() { return this.state.total; } /** * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message. * * @return Amount of participants that have the **sent** delivery status for the message. */ }, { key: "sent", get: function get() { return this.state.sent; } /** * Message is considered as **delivered** to a participant if Twilio has received confirmation of message * delivery from the upstream carrier, and, where available, the destination handset. * * @return Amount of participants that have the **delivered** delivery status for the message. */ }, { key: "delivered", get: function get() { return this.state.delivered; } /** * Message is considered as **read** by a participant, if the message has been delivered and opened by the * recipient in a conversation. The recipient must have enabled the read receipts. * * @return Amount of participants that have the **read** delivery status for the message. */ }, { key: "read", get: function get() { return this.state.read; } /** * Message is considered as **undelivered** to a participant if Twilio has received a delivery receipt * indicating that the message was not delivered. This can happen for many reasons including carrier content * filtering and the availability of the destination handset. * * @return Ammount of participants that have the **undelivered** delivery status for the message. */ }, { key: "undelivered", get: function get() { return this.state.undelivered; } /** * Message is considered as **failed** to be delivered to a participant if the message could not be sent. * This can happen for various reasons including queue overflows, account suspensions and media * errors (in the case of MMS for instance). Twilio does not charge you for failed messages. * * @return Amount of participants that have the **failed** delivery status for the message. */ }, { key: "failed", get: function get() { return this.state.failed; } }, { key: "_update", value: function _update(data) { this.state = data; } }, { key: "_isEquals", value: function _isEquals(data) { var isTotalSame = this.total === data.total; var isSentSame = this.sent === data.sent; var isDeliveredSame = this.delivered === data.delivered; var isReadSame = this.read === data.read; var isUndeliveredSame = this.undelivered === data.undelivered; var isFailedSame = this.failed === data.failed; return isTotalSame && isSentSame && isDeliveredSame && isReadSame && isUndeliveredSame && isFailedSame; } }]); return AggregatedDeliveryReceipt; }(); /** * Pagination helper class. */ var RestPaginator = /*#__PURE__*/function () { /** * @internal */ function RestPaginator(items, source, prevToken, nextToken) { _classCallCheck$4(this, RestPaginator); this.state = { prevToken: prevToken, nextToken: nextToken, source: source, items: items }; } /** * Request the next page. Does not modify the existing object. */ _createClass$4(RestPaginator, [{ key: "hasNextPage", get: /** * Indicates the existence of the next page. */ function get() { return !!this.state.nextToken; } /** * Indicates the existence of the previous page */ }, { key: "hasPrevPage", get: function get() { return !!this.state.prevToken; } /** * Array of elements on the current page. */ }, { key: "items", get: function get() { return this.state.items; } }, { key: "nextPage", value: function nextPage() { return this.hasNextPage ? this.state.source(this.state.nextToken) : Promise.reject(new Error("No next page")); } /** * Request the previous page. Does not modify the existing object. */ }, { key: "prevPage", value: function prevPage() { return this.hasPrevPage ? this.state.source(this.state.prevToken) : Promise.reject(new Error("No previous page")); } }]); return RestPaginator; }(); /** * Represents a delivery receipt of a message. */ var DetailedDeliveryReceipt = /*#__PURE__*/_createClass$4( /** * Unique identifier for the delivery receipt. */ /** * Unique identifier for the message in the conversation. */ /** * Unique identifier for the conversation. */ /** * Unique identifier for the `‘channel’` message (e.g., `WAxx` for WhatsApp, `SMxx` for SMS). */ /** * Unique identifier for the participant. */ /** * Status of the message delivery. */ /** * Numeric error code mapped from Status callback code. Information about the error codes can be found * [here](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors). */ /** * Date this delivery receipt was created on. */ /** * Date this delivery receipt was last updated on. */ /** * @internal */ function DetailedDeliveryReceipt(descriptor) { _classCallCheck$4(this, DetailedDeliveryReceipt); this.sid = descriptor.sid; this.messageSid = descriptor.message_sid; this.conversationSid = descriptor.conversation_sid; this.channelMessageSid = descriptor.channel_message_sid; this.participantSid = descriptor.participant_sid; this.status = descriptor.status || "queued"; this.errorCode = descriptor.error_code || 0; this.dateCreated = descriptor.date_created; this.dateUpdated = descriptor.date_updated; }); var browser = {}; Object.defineProperty(browser, '__esModule', { value: true }); var log$4 = loglevel.exports; function _interopDefaultLegacy$1(e) { return e && _typeof$3(e) === 'object' && 'default' in e ? e : { 'default': e }; } var log__default = /*#__PURE__*/_interopDefaultLegacy$1(log$4); var deprecated = function deprecated(oldName, newName, link) { return function (target, propertyKey, descriptor) { if (typeof descriptor.value !== "function" && (descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === undefined) { throw new Error("The deprecated decorator can only be applied to methods or getters"); } if (typeof descriptor.value === "function") { var originalMethod = descriptor.value; descriptor.value = function () { deprecationWarning("The method ".concat(oldName, " is deprecated").concat(newName ? ", use " + newName + " instead" : "").concat(link ? ", " + link : ".")); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return originalMethod.apply(this, args); }; return; } var originalGet = descriptor.get; descriptor.get = function () { deprecationWarning("The getter ".concat(oldName, " is deprecated").concat(newName ? ", use " + newName + " instead" : "").concat(link ? ", " + link : ".")); return originalGet === null || originalGet === void 0 ? void 0 : originalGet.apply(this); }; }; }; var deprecationWarning = function deprecationWarning(warning) { var currentLevel = log__default["default"].getLevel(); log__default["default"].setLevel("warn"); log__default["default"].warn(warning); log__default["default"].setLevel(currentLevel); }; var deprecated_1 = browser.deprecated = deprecated; var deprecationWarning_1 = browser.deprecationWarning = deprecationWarning; var collectActions = function collectActions(actions) { return actions.map(function (action) { var _action$id, _action$index, _action$phone, _action$url; var rawData = JSON.stringify(action); switch (action.type) { case "QUICK_REPLY": return { type: "reply", title: action.title, id: (_action$id = action.id) !== null && _action$id !== void 0 ? _action$id : "", index: (_action$index = action.index) !== null && _action$index !== void 0 ? _action$index : 0, rawData: rawData }; case "PHONE_NUMBER": return { type: "phone", title: action.title, phone: (_action$phone = action.phone) !== null && _action$phone !== void 0 ? _action$phone : "", rawData: rawData }; case "URL": return { type: "url", title: action.title, url: (_action$url = action.url) !== null && _action$url !== void 0 ? _action$url : "", rawData: rawData }; default: return { type: "other", rawData: rawData }; } }); }; var parseVariant = function parseVariant(type, data) { var rawData = JSON.stringify(data); switch (type) { case "twilio/text": { var variant = data; return { type: "text", body: variant.body, rawData: rawData }; } case "twilio/media": { var _variant = data; return { type: "media", body: _variant.body, media: _variant.media, rawData: rawData }; } case "twilio/location": { var _variant2 = data; return { type: "location", longitude: _variant2.longitude, latitude: _variant2.latitude, label: _variant2.label, rawData: rawData }; } case "twilio/quick-reply": { var _variant3 = data; return { type: "quickReply", body: _variant3.body, replies: _variant3.actions, rawData: rawData }; } case "twilio/call-to-action": { var _variant4 = data; return { type: "callToAction", body: _variant4.body, actions: collectActions(_variant4.actions), rawData: rawData }; } case "twilio/list-picker": { var _variant5 = data; return { type: "listPicker", body: _variant5.body, button: _variant5.button, items: _variant5.items, rawData: rawData }; } case "twilio/card": { var _variant6$media, _variant6$actions; var _variant6 = data; return { type: "card", title: _variant6.title, subtitle: _variant6.subtitle, media: (_variant6$media = _variant6.media) !== null && _variant6$media !== void 0 ? _variant6$media : [], actions: collectActions((_variant6$actions = _variant6.actions) !== null && _variant6$actions !== void 0 ? _variant6$actions : []), rawData: rawData }; } default: return { type: "other", rawData: rawData }; } }; var collectVariants = function collectVariants(variants) { var variantsMap = new Map(); for (var _i = 0, _Object$entries = Object.entries(variants); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray$1(_Object$entries[_i], 2), key = _Object$entries$_i[0], value = _Object$entries$_i[1]; variantsMap.set(key, parseVariant(key, value)); } return variantsMap; }; /** * Represents a variable for a content template. See * {@link ContentTemplate.variables}. */ var ContentTemplateVariable = /*#__PURE__*/function () { function ContentTemplateVariable( /** * Name of the variable. */ name, /** * Key of the variable */ value) { _classCallCheck$4(this, ContentTemplateVariable); this.name = name; this.value = value; } /** * Copies the variable with a new value. * * @param value The new value for the variable. */ _createClass$4(ContentTemplateVariable, [{ key: "copyWithValue", value: function copyWithValue(value) { return new ContentTemplateVariable(this.name, value); } }]); return ContentTemplateVariable; }(); /** * A rich content template. * * Use {@Link Client.getContentTemplates} to request all the templates available * for the current account. */ var ContentTemplate = /*#__PURE__*/_createClass$4( /** * The server-assigned unique identifier for the template. */ /** * Friendly name used to describe the content. Not visible to the recipient. */ /** * Variables used by this template. */ /** * Variants of the content. See {@link ContentData}. */ /** * Date of creation. */ /** * Date of the last update. */ /** * @internal */ function ContentTemplate(contentTemplateResponse) { _classCallCheck$4(this, ContentTemplate); this.sid = contentTemplateResponse.sid; this.friendlyName = contentTemplateResponse.friendly_name; this.variables = Object.entries(JSON.parse(contentTemplateResponse.variables)).map(function (_ref) { var _ref2 = _slicedToArray$1(_ref, 2), key = _ref2[0], value = _ref2[1]; return new ContentTemplateVariable(key, value); }); this.variants = collectVariants(contentTemplateResponse.variants); this.dateCreated = new Date(contentTemplateResponse.date_created); this.dateUpdated = new Date(contentTemplateResponse.date_updated); }); function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4(Object(source), !0).forEach(function (key) { _defineProperty$3(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var log$3 = Logger.scope("Message"); var XHR = // eslint-disable-next-line @typescript-eslint/no-var-requires global["XMLHttpRequest"] || {}; /** * A message in a conversation. */ var Message = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Message, _ReplayEventEmitter); var _super = _createSuper$5(Message); /** * Conversation that the message is in. */ /** * @internal */ function Message(index, data, conversation, links, configuration, services) { var _data$text, _data$lastUpdatedBy, _data$type, _data$memberSid; var _this; _classCallCheck$4(this, Message); _this = _super.call(this); _this.conversation = conversation; _this.links = links; _this.configuration = configuration; _this.services = services; _this.state = { sid: data.sid, index: index, author: data.author, subject: data.subject, contentSid: data.contentSid, body: (_data$text = data.text) !== null && _data$text !== void 0 ? _data$text : null, timestamp: data.timestamp ? new Date(data.timestamp) : null, dateUpdated: data.dateUpdated ? new Date(data.dateUpdated) : null, lastUpdatedBy: (_data$lastUpdatedBy = data.lastUpdatedBy) !== null && _data$lastUpdatedBy !== void 0 ? _data$lastUpdatedBy : null, attributes: parseAttributes(data.attributes, "Got malformed attributes for the message ".concat(data.sid), log$3), type: (_data$type = data.type) !== null && _data$type !== void 0 ? _data$type : "text", media: data.type === "media" && data.media ? new Media(data.media, _this.services) : null, medias: data.type === "media" && data.medias ? data.medias.map(function (m) { return new Media(m, _this.services); }) : data.type === "media" && data.media && !data.medias ? [new Media(_objectSpread$4(_objectSpread$4({}, data.media), {}, { category: "media" }), _this.services)] : null, participantSid: (_data$memberSid = data.memberSid) !== null && _data$memberSid !== void 0 ? _data$memberSid : null, aggregatedDeliveryReceipt: data.delivery ? new AggregatedDeliveryReceipt(data.delivery) : null }; return _this; } /** * Fired when the properties or the body of the message has been updated. * * Parameters: * 1. object `data` - info object provided with the event. It has the following properties: * * {@link Message} message - the message in question * * {@link MessageUpdateReason}[] updateReasons - array of reasons for the update */ _createClass$4(Message, [{ key: "sid", get: /** * The server-assigned unique identifier for the message. */ function get() { return this.state.sid; } /** * Name of the user that sent the message. */ }, { key: "author", get: function get() { return this.state.author; } /** * Message subject. Used only in email conversations. */ }, { key: "subject", get: function get() { return this.state.subject; } /** * Unique identifier of {@link ContentTemplate} for this message. */ }, { key: "contentSid", get: function get() { return this.state.contentSid; } /** * Body of the message. */ }, { key: "body", get: function get() { return this.state.body; } /** * Date this message was last updated on. */ }, { key: "dateUpdated", get: function get() { return this.state.dateUpdated; } /** * Index of this message in the conversation's list of messages. * * By design, the message indices may have arbitrary gaps between them, * that does not necessarily mean they were deleted or otherwise modified - just that * messages may have some non-contiguous indices even if they are being sent immediately one after another. * * Trying to use indices for some calculations is going to be unreliable. * * To calculate the number of unread messages, it is better to use the Read Horizon API. * See {@link Conversation.getUnreadMessagesCount} for details. */ }, { key: "index", get: function get() { return this.state.index; } /** * Identity of the last user that updated the message. */ }, { key: "lastUpdatedBy", get: function get() { return this.state.lastUpdatedBy; } /** * Date this message was created on. */ }, { key: "dateCreated", get: function get() { return this.state.timestamp; } /** * Custom attributes of the message. */ }, { key: "attributes", get: function get() { return this.state.attributes; } /** * Type of the message. */ }, { key: "type", get: function get() { return this.state.type; } /** * One of the attached media (if present). * @deprecated Use attachedMedia instead. Note that the latter is now an array. */ }, { key: "media", get: function get() { return this.state.media; } /** * Return all media attachments, except email body/history attachments, without temporary urls. */ }, { key: "attachedMedia", get: function get() { return this.getMediaByCategories(["media"]); } /** * The server-assigned unique identifier of the authoring participant. */ }, { key: "participantSid", get: function get() { return this.state.participantSid; } /** * Aggregated information about the message delivery statuses across all participants of a conversation.. */ }, { key: "aggregatedDeliveryReceipt", get: function get() { return this.state.aggregatedDeliveryReceipt; } /** * @deprecated * Return a (possibly empty) array of media matching a specific set of categories. * Allowed category is so far only 'media'. * @param categories Array of categories to match. * @returns Array of media descriptors matching given categories. */ }, { key: "getMediaByCategory", value: function getMediaByCategory(categories) { return this.getMediaByCategories(categories); } /** * Return a (possibly empty) array of media matching a specific set of categories. * Allowed category is so far only 'media'. * @param categories Array of categories to match. * @returns Array of media descriptors matching given categories. */ }, { key: "getMediaByCategories", value: function getMediaByCategories(categories) { var _this$state$medias; return ((_this$state$medias = this.state.medias) !== null && _this$state$medias !== void 0 ? _this$state$medias : []).filter(function (m) { return categories.includes(m.category); }); } /** * Get a media descriptor for an email body attachment of a provided type. * Allowed body types are returned in the Conversation.limits().emailBodiesAllowedContentTypes array. * @param type Type of email body to request, defaults to `text/plain`. */ }, { key: "getEmailBody", value: function getEmailBody() { var _this$getMediaByCateg, _this$getMediaByCateg2; var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "text/plain"; return (_this$getMediaByCateg = (_this$getMediaByCateg2 = this.getMediaByCategories(["body"])) === null || _this$getMediaByCateg2 === void 0 ? void 0 : _this$getMediaByCateg2.filter(function (m) { return m.contentType == type; }).shift()) !== null && _this$getMediaByCateg !== void 0 ? _this$getMediaByCateg : null; } /** * Get a media descriptor for an email history attachment of a provided type. * Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedContentTypes array. * @param type Type of email history to request, defaults to `text/plain`. */ }, { key: "getEmailHistory", value: function getEmailHistory() { var _this$getMediaByCateg3, _this$getMediaByCateg4; var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "text/plain"; return (_this$getMediaByCateg3 = (_this$getMediaByCateg4 = this.getMediaByCategories(["history"])) === null || _this$getMediaByCateg4 === void 0 ? void 0 : _this$getMediaByCateg4.filter(function (m) { return m.contentType == type; }).shift()) !== null && _this$getMediaByCateg3 !== void 0 ? _this$getMediaByCateg3 : null; } }, { key: "_update", value: function _update(data) { var updateReasons = []; if ((data.text || typeof data.text === "string") && data.text !== this.state.body) { this.state.body = data.text; updateReasons.push("body"); } if (data.subject && data.subject !== this.state.subject) { this.state.subject = data.subject; updateReasons.push("subject"); } if (data.lastUpdatedBy && data.lastUpdatedBy !== this.state.lastUpdatedBy) { this.state.lastUpdatedBy = data.lastUpdatedBy; updateReasons.push("lastUpdatedBy"); } if (data.author && data.author !== this.state.author) { this.state.author = data.author; updateReasons.push("author"); } if (data.dateUpdated && new Date(data.dateUpdated).getTime() !== (this.state.dateUpdated && this.state.dateUpdated.getTime())) { this.state.dateUpdated = new Date(data.dateUpdated); updateReasons.push("dateUpdated"); } if (data.timestamp && new Date(data.timestamp).getTime() !== (this.state.timestamp && this.state.timestamp.getTime())) { this.state.timestamp = new Date(data.timestamp); updateReasons.push("dateCreated"); } var updatedAttributes = parseAttributes(data.attributes, "Got malformed attributes for the message ".concat(this.sid), log$3); if (!isEqual(this.state.attributes, updatedAttributes)) { this.state.attributes = updatedAttributes; updateReasons.push("attributes"); } var updatedAggregatedDelivery = data.delivery; var currentAggregatedDelivery = this.state.aggregatedDeliveryReceipt; var isUpdatedAggregateDeliveryValid = !!updatedAggregatedDelivery && !!updatedAggregatedDelivery.total && !!updatedAggregatedDelivery.delivered && !!updatedAggregatedDelivery.failed && !!updatedAggregatedDelivery.read && !!updatedAggregatedDelivery.sent && !!updatedAggregatedDelivery.undelivered; if (isUpdatedAggregateDeliveryValid) { if (!currentAggregatedDelivery) { this.state.aggregatedDeliveryReceipt = new AggregatedDeliveryReceipt(updatedAggregatedDelivery); updateReasons.push("deliveryReceipt"); } else if (!currentAggregatedDelivery._isEquals(updatedAggregatedDelivery)) { currentAggregatedDelivery._update(updatedAggregatedDelivery); updateReasons.push("deliveryReceipt"); } } if (updateReasons.length > 0) { this.emit("updated", { message: this, updateReasons: updateReasons }); } } /** * Get the participant who is the author of the message. */ }, { key: "getParticipant", value: function () { var _getParticipant = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee() { var _this2 = this; var participant, errorMesage; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: participant = null; if (!this.state.participantSid) { _context.next = 5; break; } _context.next = 4; return this.conversation.getParticipantBySid(this.state.participantSid).catch(function () { log$3.debug("Participant with sid \"".concat(_this2.participantSid, "\" not found for message ").concat(_this2.sid)); return null; }); case 4: participant = _context.sent; case 5: if (!(!participant && this.state.author)) { _context.next = 9; break; } _context.next = 8; return this.conversation.getParticipantByIdentity(this.state.author).catch(function () { log$3.debug("Participant with identity \"".concat(_this2.author, "\" not found for message ").concat(_this2.sid)); return null; }); case 8: participant = _context.sent; case 9: if (!participant) { _context.next = 11; break; } return _context.abrupt("return", participant); case 11: errorMesage = "Participant with "; if (this.state.participantSid) { errorMesage += "SID '" + this.state.participantSid + "' "; } if (this.state.author) { if (this.state.participantSid) { errorMesage += "or "; } errorMesage += "identity '" + this.state.author + "' "; } if (errorMesage === "Participant with ") { errorMesage = "Participant "; } errorMesage += "was not found"; throw new Error(errorMesage); case 17: case "end": return _context.stop(); } } }, _callee, this); })); function getParticipant() { return _getParticipant.apply(this, arguments); } return getParticipant; }() /** * Get the delivery receipts of the message. */ }, { key: "getDetailedDeliveryReceipts", value: function () { var _getDetailedDeliveryReceipts = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2() { var paginator, detailedDeliveryReceipts; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this._getDetailedDeliveryReceiptsPaginator(); case 2: paginator = _context2.sent; detailedDeliveryReceipts = paginator.items; case 4: if (!paginator.hasNextPage) { _context2.next = 11; break; } _context2.next = 7; return paginator.nextPage(); case 7: paginator = _context2.sent; detailedDeliveryReceipts = [].concat(_toConsumableArray$1(detailedDeliveryReceipts), _toConsumableArray$1(paginator.items)); _context2.next = 4; break; case 11: return _context2.abrupt("return", detailedDeliveryReceipts); case 12: case "end": return _context2.stop(); } } }, _callee2, this); })); function getDetailedDeliveryReceipts() { return _getDetailedDeliveryReceipts.apply(this, arguments); } return getDetailedDeliveryReceipts; }() /** * Remove the message. */ }, { key: "remove", value: function () { var _remove = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3() { return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.services.commandExecutor.mutateResource("delete", this.links.self); case 2: return _context3.abrupt("return", this); case 3: case "end": return _context3.stop(); } } }, _callee3, this); })); function remove() { return _remove.apply(this, arguments); } return remove; }() /** * Edit the message body. * @param body New body of the message. */ }, { key: "updateBody", value: function () { var _updateBody = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee4(body) { return _regeneratorRuntime$1.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this.services.commandExecutor.mutateResource("post", this.links.self, { body: body }); case 2: return _context4.abrupt("return", this); case 3: case "end": return _context4.stop(); } } }, _callee4, this); })); function updateBody(_x) { return _updateBody.apply(this, arguments); } return updateBody; }() /** * Edit the message attributes. * @param attributes New attributes. */ }, { key: "updateAttributes", value: function () { var _updateAttributes = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee5(attributes) { return _regeneratorRuntime$1.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this.services.commandExecutor.mutateResource("post", this.links.self, { attributes: typeof attributes !== "undefined" ? JSON.stringify(attributes) : undefined }); case 2: return _context5.abrupt("return", this); case 3: case "end": return _context5.stop(); } } }, _callee5, this); })); function updateAttributes(_x2) { return _updateAttributes.apply(this, arguments); } return updateAttributes; }() /** * @deprecated * Get content URLs for all media attachments in the given set using a single operation. * @param contentSet Set of media attachments to query content URLs. */ }, { key: "attachTemporaryUrlsFor", value: function () { var _attachTemporaryUrlsFor = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee6(contentSet) { var _this3 = this; var sids; return _regeneratorRuntime$1.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: // We ignore existing mcsMedia members of each of the media entries. // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint. sids = contentSet === null || contentSet === void 0 ? void 0 : contentSet.map(function (m) { return m.sid; }); if (!(this.services.mcsClient && sids)) { _context6.next = 7; break; } _context6.next = 4; return this.services.mcsClient.mediaSetGet(sids); case 4: return _context6.abrupt("return", _context6.sent.map(function (item) { return new Media(item, _this3.services); })); case 7: throw new Error("Media Content Service is unavailable"); case 8: case "end": return _context6.stop(); } } }, _callee6, this); })); function attachTemporaryUrlsFor(_x3) { return _attachTemporaryUrlsFor.apply(this, arguments); } return attachTemporaryUrlsFor; }() /** * Get content URLs for all media attachments in the given set using a single operation. * @param contentSet Set of media attachments to query content URLs. */ }, { key: "getTemporaryContentUrlsForMedia", value: function getTemporaryContentUrlsForMedia(contentSet) { // We ignore existing mcsMedia members of each of the media entries. // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint. var sids = contentSet.map(function (m) { return m.sid; }); return this.getTemporaryContentUrlsForMediaSids(sids); } /** * Get content URLs for all media attachments in the given set of media sids using a single operation. * @param mediaSids Set of media sids to query for the content URL. */ }, { key: "getTemporaryContentUrlsForMediaSids", value: function getTemporaryContentUrlsForMediaSids(mediaSids) { var _this4 = this; return new browser$1.CancellablePromise( /*#__PURE__*/function () { var _ref = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee7(resolve, reject, onCancel) { var mediaGetRequest, urls; return _regeneratorRuntime$1.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: mediaGetRequest = _this4.services.mcsClient.mediaSetGetContentUrls(mediaSids !== null && mediaSids !== void 0 ? mediaSids : []); if (!(!_this4.services.mcsClient || !mediaSids)) { _context7.next = 4; break; } reject(new Error("Media Content Service is unavailable")); return _context7.abrupt("return"); case 4: onCancel(function () { mediaGetRequest.cancel(); }); _context7.prev = 5; _context7.next = 8; return mediaGetRequest; case 8: urls = _context7.sent; resolve(urls); _context7.next = 15; break; case 12: _context7.prev = 12; _context7.t0 = _context7["catch"](5); reject(_context7.t0); case 15: case "end": return _context7.stop(); } } }, _callee7, null, [[5, 12]]); })); return function (_x4, _x5, _x6) { return _ref.apply(this, arguments); }; }()); } /** * Get content URLs for all media attached to the message. */ }, { key: "getTemporaryContentUrlsForAttachedMedia", value: function getTemporaryContentUrlsForAttachedMedia() { var _media$map; var media = this.attachedMedia; var sids = (_media$map = media === null || media === void 0 ? void 0 : media.map(function (m) { return m.sid; })) !== null && _media$map !== void 0 ? _media$map : []; return this.getTemporaryContentUrlsForMediaSids(sids); } }, { key: "_getDetailedDeliveryReceiptsPaginator", value: function () { var _getDetailedDeliveryReceiptsPaginator2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee8(options) { var _this5 = this; var messagesReceiptsUrl, url, response; return _regeneratorRuntime$1.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: messagesReceiptsUrl = this.configuration.links.messagesReceipts.replace("%s", this.conversation.sid).replace("%s", this.sid); url = new UriBuilder$1(messagesReceiptsUrl).arg("PageToken", options === null || options === void 0 ? void 0 : options.pageToken).arg("PageSize", options === null || options === void 0 ? void 0 : options.pageSize).build(); _context8.next = 4; return this.services.network.get(url); case 4: response = _context8.sent; return _context8.abrupt("return", new RestPaginator(response.body.delivery_receipts.map(function (x) { return new DetailedDeliveryReceipt(x); }), function (pageToken, pageSize) { return _this5._getDetailedDeliveryReceiptsPaginator({ pageToken: pageToken, pageSize: pageSize }); }, response.body.meta.previous_token, response.body.meta.next_token)); case 6: case "end": return _context8.stop(); } } }, _callee8, this); })); function _getDetailedDeliveryReceiptsPaginator(_x7) { return _getDetailedDeliveryReceiptsPaginator2.apply(this, arguments); } return _getDetailedDeliveryReceiptsPaginator; }() /** * Get the {@link ContentData} for this message. Resolves to `null` when * {@link Message.contentSid} is null. */ }, { key: "getContentData", value: function getContentData() { var _this6 = this; return new browser$1.CancellablePromise( /*#__PURE__*/function () { var _ref2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee9(resolve, reject, onCancel) { var bodies, twilioPrefix, filteredMedias, contentMedia, urlPromise, url, jsonStringPromise, json, jsonString, dataType; return _regeneratorRuntime$1.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: if (!(_this6.state.contentSid === null)) { _context9.next = 3; break; } resolve(null); return _context9.abrupt("return"); case 3: bodies = _this6.getMediaByCategories(["body"]); if (!(bodies === null)) { _context9.next = 7; break; } resolve(null); return _context9.abrupt("return"); case 7: twilioPrefix = "application/x-vnd.com.twilio.rich."; filteredMedias = bodies.filter(function (media) { return media.contentType.startsWith(twilioPrefix); }); if (!(filteredMedias.length === 0)) { _context9.next = 12; break; } resolve(null); return _context9.abrupt("return"); case 12: contentMedia = filteredMedias[0]; urlPromise = contentMedia.getContentTemporaryUrl(); onCancel(function () { urlPromise.cancel(); }); _context9.prev = 15; _context9.next = 18; return urlPromise; case 18: url = _context9.sent; _context9.next = 25; break; case 21: _context9.prev = 21; _context9.t0 = _context9["catch"](15); reject(_context9.t0); return _context9.abrupt("return"); case 25: if (!(url === null)) { _context9.next = 28; break; } resolve(null); return _context9.abrupt("return"); case 28: jsonStringPromise = new Promise(function (resolve, reject) { var _url; var isCancelled = false; var xhr = new XHR(); xhr.open("GET", (_url = url) !== null && _url !== void 0 ? _url : "", true); xhr.responseType = "text"; xhr.onreadystatechange = function () { if (xhr.readyState !== 4 || isCancelled) { return; } resolve(xhr.responseText); }; xhr.onerror = function () { reject(xhr.statusText); }; onCancel(function () { isCancelled = true; xhr.abort(); reject(new Error("XHR has been aborted")); }); xhr.send(); }); _context9.prev = 29; _context9.next = 32; return jsonStringPromise; case 32: jsonString = _context9.sent; json = JSON.parse(jsonString); _context9.next = 40; break; case 36: _context9.prev = 36; _context9.t1 = _context9["catch"](29); reject(_context9.t1); return _context9.abrupt("return"); case 40: dataType = contentMedia.contentType.replace(twilioPrefix, "").replace(".", "/"); resolve(parseVariant(dataType, json.data)); case 42: case "end": return _context9.stop(); } } }, _callee9, null, [[15, 21], [29, 36]]); })); return function (_x8, _x9, _x10) { return _ref2.apply(this, arguments); }; }()); } }]); return Message; }(ReplayEventEmitter_1); _defineProperty$3(Message, "updated", "updated"); __decorate$1([deprecated_1("getMediaByCategory", "getMediaByCategories"), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Array]), __metadata$1("design:returntype", Array)], Message.prototype, "getMediaByCategory", null); __decorate$1([validateTypes_1([nonEmptyString_1, "undefined"]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Media)], Message.prototype, "getEmailBody", null); __decorate$1([validateTypes_1([nonEmptyString_1, "undefined"]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Media)], Message.prototype, "getEmailHistory", null); __decorate$1([validateTypesAsync_1("string"), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], Message.prototype, "updateBody", null); __decorate$1([validateTypesAsync_1(json), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Promise)], Message.prototype, "updateAttributes", null); __decorate$1([deprecated_1("attachTemporaryUrlsFor", "getTemporaryContentUrlsForMedia"), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Array]), __metadata$1("design:returntype", Promise)], Message.prototype, "attachTemporaryUrlsFor", null); __decorate$1([validateTypesAsync_1(nonEmptyArray_1("media", Media)), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Array]), __metadata$1("design:returntype", browser$1.CancellablePromise)], Message.prototype, "getTemporaryContentUrlsForMedia", null); __decorate$1([validateTypesAsync_1(nonEmptyArray_1("strings", "string")), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Array]), __metadata$1("design:returntype", browser$1.CancellablePromise)], Message.prototype, "getTemporaryContentUrlsForMediaSids", null); function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), !0).forEach(function (key) { _defineProperty$3(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createForOfIteratorHelper$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); } function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var log$2 = Logger.scope("Messages"); /** * Represents the collection of messages in a conversation */ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Messages, _ReplayEventEmitter); var _super = _createSuper$4(Messages); function Messages(conversation, configuration, services) { var _this; _classCallCheck$4(this, Messages); _this = _super.call(this); _this.conversation = conversation; _this.configuration = configuration; _this.services = services; _this.messagesByIndex = new Map(); _this.messagesListPromise = null; return _this; } /** * Subscribe to the Messages Event Stream * @param arg - Name of the Sync object, or the SyncList itself, that * represents the Messages resource. */ _createClass$4(Messages, [{ key: "subscribe", value: function () { var _subscribe = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(arg) { var _this2 = this; var list; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!this.messagesListPromise) { _context.next = 2; break; } return _context.abrupt("return", this.messagesListPromise); case 2: this.messagesListPromise = typeof arg === "string" ? this.services.syncClient.list({ id: arg, mode: "open_existing" }) : Promise.resolve(arg); _context.prev = 3; _context.next = 6; return this.messagesListPromise; case 6: list = _context.sent; list.on("itemAdded", function (args) { log$2.debug("".concat(_this2.conversation.sid, " itemAdded: ").concat(args.item.index)); var links = { self: "".concat(_this2.conversation._links.messages, "/").concat(args.item.data.sid), conversation: _this2.conversation._links.self, messages_receipts: "".concat(_this2.conversation._links.messages, "/").concat(args.item.data.sid, "/Receipts") }; var message = new Message(args.item.index, args.item.data, _this2.conversation, links, _this2.configuration, _this2.services); if (_this2.messagesByIndex.has(message.index)) { log$2.debug("Message arrived, but is already known and ignored", _this2.conversation.sid, message.index); return; } _this2.messagesByIndex.set(message.index, message); message.on("updated", function (args) { return _this2.emit("messageUpdated", args); }); _this2.emit("messageAdded", message); }); list.on("itemRemoved", function (args) { log$2.debug("#{this.conversation.sid} itemRemoved: ".concat(args.index)); var index = args.index; if (_this2.messagesByIndex.has(index)) { var message = _this2.messagesByIndex.get(index); if (!message) { return; } _this2.messagesByIndex.delete(message.index); message.removeAllListeners("updated"); _this2.emit("messageRemoved", message); } }); list.on("itemUpdated", function (args) { log$2.debug("".concat(_this2.conversation.sid, " itemUpdated: ").concat(args.item.index)); var message = _this2.messagesByIndex.get(args.item.index); if (message) { message._update(args.item.data); } }); return _context.abrupt("return", list); case 13: _context.prev = 13; _context.t0 = _context["catch"](3); this.messagesListPromise = null; if (this.services.syncClient.connectionState !== "disconnected") { log$2.error("Failed to get messages object for conversation", this.conversation.sid, _context.t0); } log$2.debug("ERROR: Failed to get messages object for conversation", this.conversation.sid, _context.t0); throw _context.t0; case 19: case "end": return _context.stop(); } } }, _callee, this, [[3, 13]]); })); function subscribe(_x) { return _subscribe.apply(this, arguments); } return subscribe; }() }, { key: "unsubscribe", value: function () { var _unsubscribe = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2() { var entity; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (this.messagesListPromise) { _context2.next = 2; break; } return _context2.abrupt("return"); case 2: _context2.next = 4; return this.messagesListPromise; case 4: entity = _context2.sent; entity.close(); this.messagesListPromise = null; case 7: case "end": return _context2.stop(); } } }, _callee2, this); })); function unsubscribe() { return _unsubscribe.apply(this, arguments); } return unsubscribe; }() /** * Send a message to the conversation. The message could include text and multiple media attachments. * @param message Message to post */ }, { key: "sendV2", value: function sendV2(message) { var _this3 = this; log$2.debug("Sending message V2", message.mediaContent, message.attributes, message.emailOptions); return new browser$1.CancellablePromise( /*#__PURE__*/function () { var _ref = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3(resolve, reject, onCancel) { var _message$emailOptions; var media, requests, _iterator, _step, _step$value, category, mediaContent, _mediaContent$content, _mediaContent$media, request, messagesPostRequest; return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: media = []; requests = []; onCancel(function () { requests.forEach(function (request) { return request.cancel(); }); }); _iterator = _createForOfIteratorHelper$2(message.mediaContent); _context3.prev = 4; _iterator.s(); case 6: if ((_step = _iterator.n()).done) { _context3.next = 25; break; } _step$value = _slicedToArray$1(_step.value, 2), category = _step$value[0], mediaContent = _step$value[1]; _context3.prev = 8; log$2.debug("Adding media to a message as ".concat(mediaContent instanceof FormData ? "FormData" : "SendMediaOptions"), mediaContent); request = mediaContent instanceof FormData ? _this3.services.mcsClient.postFormData(mediaContent, category) : _this3.services.mcsClient.post((_mediaContent$content = mediaContent.contentType) !== null && _mediaContent$content !== void 0 ? _mediaContent$content : "", (_mediaContent$media = mediaContent.media) !== null && _mediaContent$media !== void 0 ? _mediaContent$media : "", category, mediaContent.filename); requests.push(request); _context3.t0 = media; _context3.next = 15; return request; case 15: _context3.t1 = _context3.sent; _context3.t0.push.call(_context3.t0, _context3.t1); _context3.next = 23; break; case 19: _context3.prev = 19; _context3.t2 = _context3["catch"](8); reject(_context3.t2); return _context3.abrupt("return"); case 23: _context3.next = 6; break; case 25: _context3.next = 30; break; case 27: _context3.prev = 27; _context3.t3 = _context3["catch"](4); _iterator.e(_context3.t3); case 30: _context3.prev = 30; _iterator.f(); return _context3.finish(30); case 33: messagesPostRequest = _this3.services.commandExecutor.mutateResource("post", _this3.conversation._links.messages, { body: message.text, subject: (_message$emailOptions = message.emailOptions) === null || _message$emailOptions === void 0 ? void 0 : _message$emailOptions.subject, media_sids: media.map(function (m) { return m.sid; }), attributes: typeof message.attributes !== "undefined" ? JSON.stringify(message.attributes) : undefined, content_sid: message.contentSid, content_variables: typeof message.contentVariables !== "undefined" ? JSON.stringify(message.contentVariables.reduce(function (accum, current) { return _objectSpread$3(_objectSpread$3({}, accum), {}, _defineProperty$3({}, current.name, current.value)); }, {})) : undefined }); _context3.prev = 34; _context3.t4 = resolve; _context3.next = 38; return messagesPostRequest; case 38: _context3.t5 = _context3.sent; (0, _context3.t4)(_context3.t5); _context3.next = 45; break; case 42: _context3.prev = 42; _context3.t6 = _context3["catch"](34); reject(_context3.t6); case 45: case "end": return _context3.stop(); } } }, _callee3, null, [[4, 27, 30, 33], [8, 19], [34, 42]]); })); return function (_x2, _x3, _x4) { return _ref.apply(this, arguments); }; }()); } /** * Send Message to the conversation * @param message Message to post * @param attributes Message attributes * @param emailOptions Options that modify E-mail integration behaviors. * @returns Returns promise which can fail */ }, { key: "send", value: function () { var _send = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee4(message) { var attributes, emailOptions, _args4 = arguments; return _regeneratorRuntime$1.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: attributes = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {}; emailOptions = _args4.length > 2 ? _args4[2] : undefined; log$2.debug("Sending text message", message, attributes, emailOptions); return _context4.abrupt("return", this.services.commandExecutor.mutateResource("post", this.conversation._links.messages, { body: message !== null && message !== void 0 ? message : "", attributes: typeof attributes !== "undefined" ? JSON.stringify(attributes) : undefined, subject: emailOptions === null || emailOptions === void 0 ? void 0 : emailOptions.subject })); case 4: case "end": return _context4.stop(); } } }, _callee4, this); })); function send(_x5) { return _send.apply(this, arguments); } return send; }() /** * Send Media Message to the conversation * @param mediaContent Media content to post * @param attributes Message attributes * @param emailOptions Email options * @returns Returns promise which can fail */ }, { key: "sendMedia", value: function () { var _sendMedia = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee5(mediaContent) { var _mediaContent$content2, _mediaContent$media2; var attributes, emailOptions, media, _args5 = arguments; return _regeneratorRuntime$1.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: attributes = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; emailOptions = _args5.length > 2 ? _args5[2] : undefined; log$2.debug("Sending media message", mediaContent, attributes, emailOptions); log$2.debug("Sending media message as ".concat(mediaContent instanceof FormData ? "FormData" : "SendMediaOptions"), mediaContent, attributes); if (!(mediaContent instanceof FormData)) { _context5.next = 10; break; } _context5.next = 7; return this.services.mcsClient.postFormData(mediaContent); case 7: _context5.t0 = _context5.sent; _context5.next = 13; break; case 10: _context5.next = 12; return this.services.mcsClient.post((_mediaContent$content2 = mediaContent.contentType) !== null && _mediaContent$content2 !== void 0 ? _mediaContent$content2 : "", (_mediaContent$media2 = mediaContent.media) !== null && _mediaContent$media2 !== void 0 ? _mediaContent$media2 : "", "media", mediaContent.filename); case 12: _context5.t0 = _context5.sent; case 13: media = _context5.t0; _context5.next = 16; return this.services.commandExecutor.mutateResource("post", this.conversation._links.messages, { media_sids: [media.sid], attributes: typeof attributes !== "undefined" ? JSON.stringify(attributes) : undefined }); case 16: return _context5.abrupt("return", _context5.sent); case 17: case "end": return _context5.stop(); } } }, _callee5, this); })); function sendMedia(_x6) { return _sendMedia.apply(this, arguments); } return sendMedia; }() /** * Returns messages from conversation using paginator interface * @param pageSize Number of messages to return in single chunk. By default it's 30. * @param anchor Most early message id which is already known, or 'end' by default * @param direction Pagination order 'backwards' or 'forward', 'forward' by default * @returns Last page of messages by default */ }, { key: "getMessages", value: function () { var _getMessages2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee6(pageSize, anchor) { var direction, _args6 = arguments; return _regeneratorRuntime$1.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: direction = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "backwards"; return _context6.abrupt("return", this._getMessages(pageSize, anchor, direction)); case 2: case "end": return _context6.stop(); } } }, _callee6, this); })); function getMessages(_x7, _x8) { return _getMessages2.apply(this, arguments); } return getMessages; }() }, { key: "_wrapPaginator", value: function _wrapPaginator(order, page, op) { var _this4 = this; // Due to an inconsistency between Sync and Chat conventions, next and // previous pages should be swapped. var shouldReverse = order === "desc"; var nextPage = function nextPage() { return page.nextPage().then(function (page) { return _this4._wrapPaginator(order, page, op); }); }; var previousPage = function previousPage() { return page.prevPage().then(function (page) { return _this4._wrapPaginator(order, page, op); }); }; return op(page.items).then(function (items) { return { items: items.sort(function (x, y) { return x.index - y.index; }), hasPrevPage: shouldReverse ? page.hasNextPage : page.hasPrevPage, hasNextPage: shouldReverse ? page.hasPrevPage : page.hasNextPage, prevPage: shouldReverse ? nextPage : previousPage, nextPage: shouldReverse ? previousPage : nextPage }; }); } }, { key: "_upsertMessage", value: function _upsertMessage(index, value) { var _this5 = this; var cachedMessage = this.messagesByIndex.get(index); if (cachedMessage) { return cachedMessage; } var links = { self: "".concat(this.conversation._links.messages, "/").concat(value.sid), conversation: this.conversation._links.self, messages_receipts: "".concat(this.conversation._links.messages, "/").concat(value.sid, "/Receipts") }; var message = new Message(index, value, this.conversation, links, this.configuration, this.services); this.messagesByIndex.set(message.index, message); message.on("updated", function (args) { return _this5.emit("messageUpdated", args); }); return message; } /** * Returns last messages from conversation * @param {Number} [pageSize] Number of messages to return in single chunk. By default it's 30. * @param {String} [anchor] Most early message id which is already known, or 'end' by default * @param {String} [direction] Pagination order 'backwards' or 'forward', or 'forward' by default * @returns {Promise>} last page of messages by default * @private */ }, { key: "_getMessages", value: function () { var _getMessages3 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee7() { var _this6 = this; var pageSize, anchor, direction, order, list, page, _args7 = arguments; return _regeneratorRuntime$1.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: pageSize = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : 30; anchor = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : "end"; direction = _args7.length > 2 && _args7[2] !== undefined ? _args7[2] : "forward"; order = direction === "backwards" ? "desc" : "asc"; _context7.next = 6; return this.messagesListPromise; case 6: list = _context7.sent; _context7.next = 9; return list === null || list === void 0 ? void 0 : list.getItems({ from: anchor !== "end" ? anchor : void 0, pageSize: pageSize, order: order, limit: pageSize // @todo Limit equals pageSize by default in Sync. This is probably not ideal. }); case 9: page = _context7.sent; _context7.next = 12; return this._wrapPaginator(order, page, function (items) { return Promise.all(items.map(function (item) { return _this6._upsertMessage(item.index, item.data); })); }); case 12: return _context7.abrupt("return", _context7.sent); case 13: case "end": return _context7.stop(); } } }, _callee7, this); })); function _getMessages() { return _getMessages3.apply(this, arguments); } return _getMessages; }() }]); return Messages; }(ReplayEventEmitter_1); /** * An unsent message. Returned from {@link MessageBuilder.build}. */ var UnsentMessage = /*#__PURE__*/function () { /** * @internal */ function UnsentMessage(messagesEntity) { _classCallCheck$4(this, UnsentMessage); _defineProperty$3(this, "attributes", {}); _defineProperty$3(this, "mediaContent", []); _defineProperty$3(this, "emailOptions", {}); this.messagesEntity = messagesEntity; } /** * Send the prepared message to the conversation. * @returns Index of the new message in the conversation. */ _createClass$4(UnsentMessage, [{ key: "send", value: function send() { var _this = this; return new browser$1.CancellablePromise( /*#__PURE__*/function () { var _ref = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(resolve, reject, onCancel) { var request, response; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: request = _this.messagesEntity.sendV2(_this); onCancel(function () { return request.cancel(); }); _context.prev = 2; _context.next = 5; return request; case 5: response = _context.sent; resolve(parseToNumber(response.index)); _context.next = 12; break; case 9: _context.prev = 9; _context.t0 = _context["catch"](2); reject(_context.t0); case 12: case "end": return _context.stop(); } } }, _callee, null, [[2, 9]]); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }()); } }]); return UnsentMessage; }(); /** * Message builder. Allows the message to be built and sent via method chaining. * * Example: * * ```ts * await testConversation.prepareMessage() * .setBody('Hello!') * .setAttributes({foo: 'bar'}) * .addMedia(media1) * .addMedia(media2) * .build() * .send(); * ``` */ var MessageBuilder = /*#__PURE__*/function () { /** * @internal */ function MessageBuilder(limits, messagesEntity) { _classCallCheck$4(this, MessageBuilder); this.limits = limits; this.message = new UnsentMessage(messagesEntity); this.emailBodies = new Map(); this.emailHistories = new Map(); } /** * Sets the message body. * @param text Contents of the body. */ _createClass$4(MessageBuilder, [{ key: "setBody", value: function setBody(text) { this.message.text = text; return this; } /** * Sets the message subject. * @param subject Contents of the subject. */ }, { key: "setSubject", value: function setSubject(subject) { this.message.emailOptions.subject = subject; return this; } /** * Sets the message attributes. * @param attributes Message attributes. */ }, { key: "setAttributes", value: function setAttributes(attributes) { this.message.attributes = attributes; return this; } /** * Set the email body with a given content type. * @param contentType Format of the body to set (text/plain or text/html). * @param body Body payload in the selected format. */ }, { key: "setEmailBody", value: function setEmailBody(contentType, body) { this.emailBodies.set(contentType, body); return this; } /** * Set the email history with a given content type. * @param contentType Format of the history to set (text/plain or text/html). * @param history History payload in the selected format. */ }, { key: "setEmailHistory", value: function setEmailHistory(contentType, history) { this.emailHistories.set(contentType, history); return this; } /** * Adds {@link ContentTemplate} SID for the message alongside optional * variables. When no variables provided, the default values will be used. * * Adding the content SID converts the message to a rich message. In this * case, other fields are ignored and the message is sent using the content * from the the {@link ContentTemplate}. * * Use {@link Client.getContentTemplates} to request all available * {@link ContentTemplate}s. * * @param contentSid SID of the {@link ContentTemplate} * @param variables Custom variables to resolve the template. */ }, { key: "setContentTemplate", value: function setContentTemplate(contentSid) { var contentVariables = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; this.message.contentSid = contentSid; this.message.contentVariables = contentVariables; return this; } /** * Adds media to the message. * @param payload Media to add. */ }, { key: "addMedia", value: function addMedia(payload) { if (typeof FormData === "undefined" && payload instanceof FormData) { throw new Error("Could not add FormData content whilst not in a browser"); } if (!(payload instanceof FormData)) { var mediaOptions = payload; if (!mediaOptions.contentType || !mediaOptions.media) { throw new Error("Media content in SendMediaOptions must contain non-empty contentType and media"); } } this.message.mediaContent.push(["media", payload]); return this; } /** * Builds the message, making it ready to be sent. */ }, { key: "build", value: function build() { var _this = this; this.emailBodies.forEach(function (_, key) { if (!_this.limits.emailBodiesAllowedContentTypes.includes(key)) { throw new Error("Unsupported email body content type ".concat(key)); } }); this.emailHistories.forEach(function (_, key) { if (!_this.limits.emailHistoriesAllowedContentTypes.includes(key)) { throw new Error("Unsupported email history content type ".concat(key)); } }); if (this.emailBodies.size > this.limits.emailBodiesAllowedContentTypes.length) { throw new Error("Too many email bodies attached to the message (".concat(this.emailBodies.size, " > ").concat(this.limits.emailBodiesAllowedContentTypes.length, ")")); } if (this.emailHistories.size > this.limits.emailHistoriesAllowedContentTypes.length) { throw new Error("Too many email histories attached to the message (".concat(this.emailHistories.size, " > ").concat(this.limits.emailHistoriesAllowedContentTypes.length, ")")); } if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) { throw new Error("Too many media attachments in the message (".concat(this.message.mediaContent.length, " > ").concat(this.limits.mediaAttachmentsCountLimit, ")")); } // @todo we don't know the sizes of the attachments in FormData // @todo insertion below makes build() method non-repeatable - probably move to UnsentMessage.send() or even sendV2()? this.emailBodies.forEach(function (body) { _this.message.mediaContent.push(["body", body]); }); this.emailHistories.forEach(function (history) { _this.message.mediaContent.push(["history", history]); }); return this.message; } /** * Prepares a message and sends it to the conversation. */ }, { key: "buildAndSend", value: function buildAndSend() { return this.build().send(); } }]); return MessageBuilder; }(); __decorate$1([validateTypes_1("string"), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", MessageBuilder)], MessageBuilder.prototype, "setBody", null); __decorate$1([validateTypes_1("string"), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", MessageBuilder)], MessageBuilder.prototype, "setSubject", null); __decorate$1([validateTypes_1(json), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", MessageBuilder)], MessageBuilder.prototype, "setAttributes", null); __decorate$1([validateTypes_1("string", [FormData, sendMediaOptions]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, Object]), __metadata$1("design:returntype", MessageBuilder)], MessageBuilder.prototype, "setEmailBody", null); __decorate$1([validateTypes_1("string", [FormData, sendMediaOptions]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, Object]), __metadata$1("design:returntype", MessageBuilder)], MessageBuilder.prototype, "setEmailHistory", null); __decorate$1([validateTypes_1("string", [array_1("content variables", ContentTemplateVariable), "undefined"]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, Array]), __metadata$1("design:returntype", MessageBuilder)], MessageBuilder.prototype, "setContentTemplate", null); __decorate$1([validateTypes_1([FormData, sendMediaOptions]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", MessageBuilder)], MessageBuilder.prototype, "addMedia", null); function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * Map of the fields that will be processed with update messages. */ var fieldMappings = { lastMessage: "lastMessage", attributes: "attributes", createdBy: "createdBy", dateCreated: "dateCreated", dateUpdated: "dateUpdated", friendlyName: "friendlyName", lastConsumedMessageIndex: "lastConsumedMessageIndex", notificationLevel: "notificationLevel", sid: "sid", status: "status", uniqueName: "uniqueName", state: "state", bindings: "bindings" }; /** * A conversation represents communication between multiple Conversations * clients. */ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Conversation, _ReplayEventEmitter); var _super = _createSuper$3(Conversation); /** * Fired when a participant has joined the conversation. * * Parameters: * 1. {@link Participant} `participant` - participant that joined the * conversation * @event */ /** * Fired when a participant has left the conversation. * * Parameters: * 1. {@link Participant} `participant` - participant that left the * conversation * @event */ /** * Fired when data of a participant has been updated. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * {@link Participant} `participant` - participant that has received the * update * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons * for the update * @event */ /** * Fired when a new message has been added to the conversation. * * Parameters: * 1. {@link Message} `message` - message that has been added * @event */ /** * Fired when message is removed from the conversation's message list. * * Parameters: * 1. {@link Message} `message` - message that has been removed * @event */ /** * Fired when data of a message has been updated. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * {@link Message} `message` - message that has received the update * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for * the update * @event */ /** * Fired when a participant has stopped typing. * * Parameters: * 1. {@link Participant} `participant` - the participant that has stopped * typing * @event */ /** * Fired when a participant has started typing. * * Parameters: * 1. {@link Participant} `participant` - the participant that has started * typing * @event */ /** * Fired when the data of the conversation has been updated. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * {@link Conversation} `conversation` - conversation that has received * the update * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons * for the update * @event */ /** * Fired when the conversation was destroyed or the currently-logged-in user * has left private conversation. * * Parameters: * 1. {@link Conversation} `conversation` - conversation that has been removed * @event */ /** * Logger instance. */ /** * @param descriptor Conversation descriptor. * @param sid Conversation SID. * @param links Conversation links for REST requests. * @param configuration Client configuration. * @param services Conversation services. * @internal */ function Conversation(descriptor, sid, links, configuration, services) { var _descriptor$attribute, _descriptor$bindings; var _this; _classCallCheck$4(this, Conversation); _this = _super.call(this); _this.sid = sid; _this._links = links; _this._configuration = configuration; _this._services = services; _this._entityName = descriptor.channel; _this._internalState = { uniqueName: descriptor.uniqueName || null, status: "notParticipating", attributes: (_descriptor$attribute = descriptor.attributes) !== null && _descriptor$attribute !== void 0 ? _descriptor$attribute : {}, createdBy: descriptor.createdBy, dateCreated: parseTime(descriptor.dateCreated), dateUpdated: parseTime(descriptor.dateUpdated), friendlyName: descriptor.friendlyName || null, lastReadMessageIndex: Number.isInteger(descriptor.lastConsumedMessageIndex) ? descriptor.lastConsumedMessageIndex : null, bindings: (_descriptor$bindings = descriptor.bindings) !== null && _descriptor$bindings !== void 0 ? _descriptor$bindings : {} }; if (descriptor.notificationLevel) { _this._internalState.notificationLevel = descriptor.notificationLevel; } var participantsLinks = { participants: _this._links.participants }; _this._participants = new Map(); _this._participantsEntity = new Participants(_assertThisInitialized$3(_this), _this._participants, participantsLinks, _this._configuration, _this._services); _this._participantsEntity.on("participantJoined", function (participant) { return _this.emit("participantJoined", participant); }); _this._participantsEntity.on("participantLeft", function (participant) { return _this.emit("participantLeft", participant); }); _this._participantsEntity.on("participantUpdated", function (args) { return _this.emit("participantUpdated", args); }); _this._messagesEntity = new Messages(_assertThisInitialized$3(_this), configuration, services); _this._messagesEntity.on("messageAdded", function (message) { return _this._onMessageAdded(message); }); _this._messagesEntity.on("messageUpdated", function (args) { return _this.emit("messageUpdated", args); }); _this._messagesEntity.on("messageRemoved", function (message) { return _this.emit("messageRemoved", message); }); return _this; } /** * Unique name of the conversation. */ _createClass$4(Conversation, [{ key: "uniqueName", get: function get() { return this._internalState.uniqueName; } /** * Status of the conversation. */ }, { key: "status", get: function get() { return this._internalState.status; } /** * Name of the conversation. */ }, { key: "friendlyName", get: function get() { return this._internalState.friendlyName; } /** * Date this conversation was last updated on. */ }, { key: "dateUpdated", get: function get() { return this._internalState.dateUpdated; } /** * Date this conversation was created on. */ }, { key: "dateCreated", get: function get() { return this._internalState.dateCreated; } /** * Identity of the user that created this conversation. */ }, { key: "createdBy", get: function get() { var _this$_internalState$; return (_this$_internalState$ = this._internalState.createdBy) !== null && _this$_internalState$ !== void 0 ? _this$_internalState$ : ""; } /** * Custom attributes of the conversation. */ }, { key: "attributes", get: function get() { return this._internalState.attributes; } /** * Index of the last message the user has read in this conversation. */ }, { key: "lastReadMessageIndex", get: function get() { return this._internalState.lastReadMessageIndex; } /** * Last message sent to this conversation. */ }, { key: "lastMessage", get: function get() { var _this$_internalState$2; return (_this$_internalState$2 = this._internalState.lastMessage) !== null && _this$_internalState$2 !== void 0 ? _this$_internalState$2 : undefined; } /** * User notification level for this conversation. */ }, { key: "notificationLevel", get: function get() { var _this$_internalState$3; return (_this$_internalState$3 = this._internalState.notificationLevel) !== null && _this$_internalState$3 !== void 0 ? _this$_internalState$3 : "default"; } /** * Conversation bindings. Undocumented feature (for now). * @internal */ }, { key: "bindings", get: function get() { return this._internalState.bindings; } /** * Current conversation limits. */ }, { key: "limits", get: function get() { return this._configuration.limits; } /** * State of the conversation. */ }, { key: "state", get: function get() { return this._internalState.state; } /** * Source of the conversation update. * @internal */ }, { key: "_statusSource", get: function get() { return this._dataSource; } /** * Preprocess the update object. * @param update The update object received from Sync. * @param conversationSid The SID of the conversation in question. */ }, { key: "add", value: /** * Add a participant to the conversation by its identity. * @param identity Identity of the Client to add. * @param attributes Attributes to be attached to the participant. * @returns The added participant. */ function () { var _add = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(identity, attributes) { return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", this._participantsEntity.add(identity, attributes !== null && attributes !== void 0 ? attributes : {})); case 1: case "end": return _context.stop(); } } }, _callee, this); })); function add(_x, _x2) { return _add.apply(this, arguments); } return add; }() /** * Add a non-chat participant to the conversation. * @param proxyAddress Proxy (Twilio) address of the participant. * @param address User address of the participant. * @param attributes Attributes to be attached to the participant. * @param bindingOptions Options for adding email participants - name and * CC/To level. * @returns The added participant. */ }, { key: "addNonChatParticipant", value: function () { var _addNonChatParticipant = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2(proxyAddress, address) { var attributes, bindingOptions, _args2 = arguments; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: attributes = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : {}; bindingOptions = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : {}; return _context2.abrupt("return", this._participantsEntity.addNonChatParticipant(proxyAddress, address, attributes !== null && attributes !== void 0 ? attributes : {}, bindingOptions !== null && bindingOptions !== void 0 ? bindingOptions : {})); case 3: case "end": return _context2.stop(); } } }, _callee2, this); })); function addNonChatParticipant(_x3, _x4) { return _addNonChatParticipant.apply(this, arguments); } return addNonChatParticipant; }() /** * Advance the conversation's last read message index to the current read * horizon. Rejects if the user is not a participant of the conversation. Last * read message index is updated only if the new index value is higher than * the previous. * @param index Message index to advance to. * @return Resulting unread messages count in the conversation. */ }, { key: "advanceLastReadMessageIndex", value: function () { var _advanceLastReadMessageIndex = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3(index) { var _this$lastReadMessage; return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this._subscribeStreams(); case 2: if (!(index < ((_this$lastReadMessage = this.lastReadMessageIndex) !== null && _this$lastReadMessage !== void 0 ? _this$lastReadMessage : 0))) { _context3.next = 6; break; } _context3.next = 5; return this._setLastReadMessageIndex(this.lastReadMessageIndex); case 5: return _context3.abrupt("return", _context3.sent); case 6: _context3.next = 8; return this._setLastReadMessageIndex(index); case 8: return _context3.abrupt("return", _context3.sent); case 9: case "end": return _context3.stop(); } } }, _callee3, this); })); function advanceLastReadMessageIndex(_x5) { return _advanceLastReadMessageIndex.apply(this, arguments); } return advanceLastReadMessageIndex; }() /** * Delete the conversation and unsubscribe from its events. */ }, { key: "delete", value: function () { var _delete2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee4() { return _regeneratorRuntime$1.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._services.commandExecutor.mutateResource("delete", this._links.self); case 2: return _context4.abrupt("return", this); case 3: case "end": return _context4.stop(); } } }, _callee4, this); })); function _delete() { return _delete2.apply(this, arguments); } return _delete; }() /** * Get the custom attributes of this Conversation. */ }, { key: "getAttributes", value: function () { var _getAttributes = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee5() { return _regeneratorRuntime$1.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this._subscribe(); case 2: return _context5.abrupt("return", this.attributes); case 3: case "end": return _context5.stop(); } } }, _callee5, this); })); function getAttributes() { return _getAttributes.apply(this, arguments); } return getAttributes; }() /** * Returns messages from the conversation using the paginator interface. * @param pageSize Number of messages to return in a single chunk. Default is * 30. * @param anchor Index of the newest message to fetch. Default is from the * end. * @param direction Query direction. By default, it queries backwards * from newer to older. The `"forward"` value will query in the opposite * direction. * @return A page of messages. */ }, { key: "getMessages", value: function () { var _getMessages = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee6(pageSize, anchor, direction) { return _regeneratorRuntime$1.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return this._subscribeStreams(); case 2: return _context6.abrupt("return", this._messagesEntity.getMessages(pageSize, anchor, direction)); case 3: case "end": return _context6.stop(); } } }, _callee6, this); })); function getMessages(_x6, _x7, _x8) { return _getMessages.apply(this, arguments); } return getMessages; }() /** * Get a list of all the participants who are joined to this conversation. */ }, { key: "getParticipants", value: function () { var _getParticipants = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee7() { return _regeneratorRuntime$1.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return this._subscribeStreams(); case 2: return _context7.abrupt("return", this._participantsEntity.getParticipants()); case 3: case "end": return _context7.stop(); } } }, _callee7, this); })); function getParticipants() { return _getParticipants.apply(this, arguments); } return getParticipants; }() /** * Get conversation participants count. * * This method is semi-realtime. This means that this data will be eventually * correct, but will also be possibly incorrect for a few seconds. The * Conversations system does not provide real time events for counter values * changes. * * This is useful for any UI badges, but it is not recommended to build any * core application logic based on these counters being accurate in real time. */ }, { key: "getParticipantsCount", value: function () { var _getParticipantsCount = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee8() { var _response$body$partic; var url, response; return _regeneratorRuntime$1.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: url = new UriBuilder$1(this._configuration.links.conversations).path(this.sid).build(); _context8.next = 3; return this._services.network.get(url); case 3: response = _context8.sent; return _context8.abrupt("return", (_response$body$partic = response.body.participants_count) !== null && _response$body$partic !== void 0 ? _response$body$partic : 0); case 5: case "end": return _context8.stop(); } } }, _callee8, this); })); function getParticipantsCount() { return _getParticipantsCount.apply(this, arguments); } return getParticipantsCount; }() /** * Get a participant by its SID. * @param participantSid Participant SID. */ }, { key: "getParticipantBySid", value: function () { var _getParticipantBySid = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee9(participantSid) { return _regeneratorRuntime$1.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: return _context9.abrupt("return", this._participantsEntity.getParticipantBySid(participantSid)); case 1: case "end": return _context9.stop(); } } }, _callee9, this); })); function getParticipantBySid(_x9) { return _getParticipantBySid.apply(this, arguments); } return getParticipantBySid; }() /** * Get a participant by its identity. * @param identity Participant identity. */ }, { key: "getParticipantByIdentity", value: function () { var _getParticipantByIdentity = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee10() { var identity, _args10 = arguments; return _regeneratorRuntime$1.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: identity = _args10.length > 0 && _args10[0] !== undefined ? _args10[0] : ""; return _context10.abrupt("return", this._participantsEntity.getParticipantByIdentity(identity !== null && identity !== void 0 ? identity : "")); case 2: case "end": return _context10.stop(); } } }, _callee10, this); })); function getParticipantByIdentity() { return _getParticipantByIdentity.apply(this, arguments); } return getParticipantByIdentity; }() /** * Get the total message count in the conversation. * * This method is semi-realtime. This means that this data will be eventually * correct, but will also be possibly incorrect for a few seconds. The * Conversations system does not provide real time events for counter values * changes. * * This is useful for any UI badges, but it is not recommended to build any * core application logic based on these counters being accurate in real time. */ }, { key: "getMessagesCount", value: function () { var _getMessagesCount = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee11() { var _response$body$messag; var url, response; return _regeneratorRuntime$1.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: url = new UriBuilder$1(this._configuration.links.conversations).path(this.sid).build(); _context11.next = 3; return this._services.network.get(url); case 3: response = _context11.sent; return _context11.abrupt("return", (_response$body$messag = response.body.messages_count) !== null && _response$body$messag !== void 0 ? _response$body$messag : 0); case 5: case "end": return _context11.stop(); } } }, _callee11, this); })); function getMessagesCount() { return _getMessagesCount.apply(this, arguments); } return getMessagesCount; }() /** * Get count of unread messages for the user if they are a participant of this * conversation. Rejects if the user is not a participant of the conversation. * * Use this method to obtain the number of unread messages together with * {@link Conversation.updateLastReadMessageIndex} instead of relying on the * message indices which may have gaps. See {@link Message.index} for details. * * This method is semi-realtime. This means that this data will be eventually * correct, but it will also be possibly incorrect for a few seconds. The * Conversations system does not provide real time events for counter values * changes. * * This is useful for any UI badges, but it is not recommended to build any * core application logic based on these counters being accurate in real time. * * If the read horizon is not set, this function will return null. This could mean * that all messages in the conversation are unread, or that the read horizon system * is not being used. How to interpret this `null` value is up to the customer application. * * @return Number of unread messages based on the current read horizon set for * the user or `null` if the read horizon is not set. */ }, { key: "getUnreadMessagesCount", value: function () { var _getUnreadMessagesCount = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee12() { var url, response, unreadMessageCount; return _regeneratorRuntime$1.wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: url = new UriBuilder$1(this._configuration.links.myConversations).path(this.sid).build(); _context12.next = 3; return this._services.network.get(url); case 3: response = _context12.sent; if (!(response.body.conversation_sid !== this.sid)) { _context12.next = 6; break; } throw new Error("Conversation was not found in the user conversations list"); case 6: unreadMessageCount = response.body.unread_messages_count; if (!(typeof unreadMessageCount === "number")) { _context12.next = 9; break; } return _context12.abrupt("return", unreadMessageCount); case 9: return _context12.abrupt("return", null); case 10: case "end": return _context12.stop(); } } }, _callee12, this); })); function getUnreadMessagesCount() { return _getUnreadMessagesCount.apply(this, arguments); } return getUnreadMessagesCount; }() /** * Join the conversation and subscribe to its events. */ }, { key: "join", value: function () { var _join = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee13() { return _regeneratorRuntime$1.wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: _context13.next = 2; return this._services.commandExecutor.mutateResource("post", this._links.participants, { identity: this._configuration.userIdentity }); case 2: return _context13.abrupt("return", this); case 3: case "end": return _context13.stop(); } } }, _callee13, this); })); function join() { return _join.apply(this, arguments); } return join; }() /** * Leave the conversation. */ }, { key: "leave", value: function () { var _leave = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee14() { return _regeneratorRuntime$1.wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: if (!(this._internalState.status === "joined")) { _context14.next = 3; break; } _context14.next = 3; return this._services.commandExecutor.mutateResource("delete", "".concat(this._links.participants, "/").concat(encodeURIComponent(this._configuration.userIdentity))); case 3: return _context14.abrupt("return", this); case 4: case "end": return _context14.stop(); } } }, _callee14, this); })); function leave() { return _leave.apply(this, arguments); } return leave; }() /** * Remove a participant from the conversation. When a string is passed as the * argument, it will assume that the string is an identity or SID. * @param participant Identity, SID or the participant object to remove. */ }, { key: "removeParticipant", value: function () { var _removeParticipant = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee15(participant) { return _regeneratorRuntime$1.wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: _context15.next = 2; return this._participantsEntity.remove(typeof participant === "string" ? participant : participant.sid); case 2: case "end": return _context15.stop(); } } }, _callee15, this); })); function removeParticipant(_x10) { return _removeParticipant.apply(this, arguments); } return removeParticipant; }() /** * Send a message to the conversation. * @param message Message body for the text message, * `FormData` or {@link SendMediaOptions} for media content. Sending FormData * is supported only with the browser engine. * @param messageAttributes Attributes for the message. * @param emailOptions Email options for the message. * @return Index of the new message. */ }, { key: "sendMessage", value: function () { var _sendMessage = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee16(message, messageAttributes, emailOptions) { var _parseToNumber2; var _parseToNumber, _response, response; return _regeneratorRuntime$1.wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: if (!(typeof message === "string" || message === null)) { _context16.next = 5; break; } _context16.next = 3; return this._messagesEntity.send(message, messageAttributes, emailOptions); case 3: _response = _context16.sent; return _context16.abrupt("return", (_parseToNumber = parseToNumber(_response.index)) !== null && _parseToNumber !== void 0 ? _parseToNumber : 0); case 5: _context16.next = 7; return this._messagesEntity.sendMedia(message, messageAttributes, emailOptions); case 7: response = _context16.sent; return _context16.abrupt("return", (_parseToNumber2 = parseToNumber(response.index)) !== null && _parseToNumber2 !== void 0 ? _parseToNumber2 : 0); case 9: case "end": return _context16.stop(); } } }, _callee16, this); })); function sendMessage(_x11, _x12, _x13) { return _sendMessage.apply(this, arguments); } return sendMessage; }() /** * New interface to prepare for sending a message. * Use this instead of {@link Conversation.sendMessage}. * @return A MessageBuilder to help set all message sending options. */ }, { key: "prepareMessage", value: function prepareMessage() { return new MessageBuilder(this.limits, this._messagesEntity); } /** * Set last read message index of the conversation to the index of the last * known message. * @return Resulting unread messages count in the conversation. */ }, { key: "setAllMessagesRead", value: function () { var _setAllMessagesRead = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee17() { var messagesPage; return _regeneratorRuntime$1.wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: _context17.next = 2; return this._subscribeStreams(); case 2: _context17.next = 4; return this.getMessages(1); case 4: messagesPage = _context17.sent; if (!(messagesPage.items.length > 0)) { _context17.next = 7; break; } return _context17.abrupt("return", this.advanceLastReadMessageIndex(messagesPage.items[0].index)); case 7: return _context17.abrupt("return", 0); case 8: case "end": return _context17.stop(); } } }, _callee17, this); })); function setAllMessagesRead() { return _setAllMessagesRead.apply(this, arguments); } return setAllMessagesRead; }() /** * Set all messages in the conversation unread. * @returns New count of unread messages after this update. */ }, { key: "setAllMessagesUnread", value: function () { var _setAllMessagesUnread = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee18() { return _regeneratorRuntime$1.wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: _context18.next = 2; return this._subscribeStreams(); case 2: _context18.next = 4; return this._setLastReadMessageIndex(null); case 4: return _context18.abrupt("return", _context18.sent); case 5: case "end": return _context18.stop(); } } }, _callee18, this); })); function setAllMessagesUnread() { return _setAllMessagesUnread.apply(this, arguments); } return setAllMessagesUnread; }() /** * Set user notification level for this conversation. * @param notificationLevel New user notification level. */ }, { key: "setUserNotificationLevel", value: function () { var _setUserNotificationLevel = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee19(notificationLevel) { return _regeneratorRuntime$1.wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: _context19.next = 2; return this._services.commandExecutor.mutateResource("post", "".concat(this._configuration.links.myConversations, "/").concat(this.sid), { notification_level: notificationLevel }); case 2: case "end": return _context19.stop(); } } }, _callee19, this); })); function setUserNotificationLevel(_x14) { return _setUserNotificationLevel.apply(this, arguments); } return setUserNotificationLevel; }() /** * Send a notification to the server indicating that this client is currently * typing in this conversation. Typing ended notification is sent after a * while automatically, but by calling this method again you ensure that * typing ended is not received. */ }, { key: "typing", value: function typing() { return this._services.typingIndicator.send(this.sid); } /** * Update the attributes of the conversation. * @param attributes New attributes. */ }, { key: "updateAttributes", value: function () { var _updateAttributes = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee20(attributes) { return _regeneratorRuntime$1.wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: _context20.next = 2; return this._services.commandExecutor.mutateResource("post", this._links.self, { attributes: attributes !== undefined ? JSON.stringify(attributes) : undefined }); case 2: return _context20.abrupt("return", this); case 3: case "end": return _context20.stop(); } } }, _callee20, this); })); function updateAttributes(_x15) { return _updateAttributes.apply(this, arguments); } return updateAttributes; }() /** * Update the friendly name of the conversation. * @param friendlyName New friendly name. */ }, { key: "updateFriendlyName", value: function () { var _updateFriendlyName = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee21(friendlyName) { return _regeneratorRuntime$1.wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: if (!(this._internalState.friendlyName !== friendlyName)) { _context21.next = 3; break; } _context21.next = 3; return this._services.commandExecutor.mutateResource("post", this._links.self, { friendly_name: friendlyName }); case 3: return _context21.abrupt("return", this); case 4: case "end": return _context21.stop(); } } }, _callee21, this); })); function updateFriendlyName(_x16) { return _updateFriendlyName.apply(this, arguments); } return updateFriendlyName; }() /** * Set the last read message index to the current read horizon. * @param index Message index to set as last read. If null is provided, then * the behavior is identical to {@link Conversation.setAllMessagesUnread}. * @returns New count of unread messages after this update. */ }, { key: "updateLastReadMessageIndex", value: function () { var _updateLastReadMessageIndex = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee22(index) { return _regeneratorRuntime$1.wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: _context22.next = 2; return this._subscribeStreams(); case 2: return _context22.abrupt("return", this._setLastReadMessageIndex(index)); case 3: case "end": return _context22.stop(); } } }, _callee22, this); })); function updateLastReadMessageIndex(_x17) { return _updateLastReadMessageIndex.apply(this, arguments); } return updateLastReadMessageIndex; }() /** * Update the unique name of the conversation. * @param uniqueName New unique name for the conversation. Setting unique name * to null removes it. */ }, { key: "updateUniqueName", value: function () { var _updateUniqueName = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee23(uniqueName) { return _regeneratorRuntime$1.wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: if (!(this._internalState.uniqueName !== uniqueName)) { _context23.next = 4; break; } uniqueName || (uniqueName = ""); _context23.next = 4; return this._services.commandExecutor.mutateResource("post", this._links.self, { unique_name: uniqueName }); case 4: return _context23.abrupt("return", this); case 5: case "end": return _context23.stop(); } } }, _callee23, this); })); function updateUniqueName(_x18) { return _updateUniqueName.apply(this, arguments); } return updateUniqueName; }() /** * Load and subscribe to this conversation and do not subscribe to its * participants and messages. This or _subscribeStreams will need to be called * before any events on conversation will fire. * @internal */ }, { key: "_subscribe", value: function () { var _subscribe2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee24() { var _this2 = this; return _regeneratorRuntime$1.wrap(function _callee24$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: if (!this._entityPromise) { _context24.next = 2; break; } return _context24.abrupt("return", this._entityPromise); case 2: this._entityPromise = this._services.syncClient.document({ id: this._entityName, mode: "open_existing" }); _context24.prev = 3; _context24.next = 6; return this._entityPromise; case 6: this._entity = _context24.sent; this._entity.on("updated", function (args) { return _this2._update(args.data); }); this._entity.on("removed", function () { return _this2.emit("removed", _this2); }); this._update(this._entity.data); return _context24.abrupt("return", this._entity); case 13: _context24.prev = 13; _context24.t0 = _context24["catch"](3); this._entity = null; this._entityPromise = null; if (this._services.syncClient.connectionState != "disconnected") { Conversation._logger.error("Failed to get conversation object", _context24.t0); } Conversation._logger.debug("ERROR: Failed to get conversation object", _context24.t0); throw _context24.t0; case 20: case "end": return _context24.stop(); } } }, _callee24, this, [[3, 13]]); })); function _subscribe() { return _subscribe2.apply(this, arguments); } return _subscribe; }() /** * Fetch participants and messages of the conversation. This method needs to * be called during conversation initialization to catch broken conversations * (broken conversations are conversations that have essential Sync entities * missing, i.e. the conversation document, the messages list or the * participant map). In case of this conversation being broken, the method * will throw an exception that will be caught and handled gracefully. * @internal */ }, { key: "_fetchStreams", value: function () { var _fetchStreams2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee25() { var _this$_entity, _this$_entity2; var data; return _regeneratorRuntime$1.wrap(function _callee25$(_context25) { while (1) { switch (_context25.prev = _context25.next) { case 0: _context25.next = 2; return this._subscribe(); case 2: Conversation._logger.trace("_streamsAvailable, this.entity.data=", (_this$_entity = this._entity) === null || _this$_entity === void 0 ? void 0 : _this$_entity.data); data = (_this$_entity2 = this._entity) === null || _this$_entity2 === void 0 ? void 0 : _this$_entity2.data; _context25.next = 6; return this._services.syncClient.list({ id: data.messages, mode: "open_existing" }); case 6: this._messagesList = _context25.sent; _context25.next = 9; return this._services.syncClient.map({ id: data.roster, mode: "open_existing" }); case 9: this._participantsMap = _context25.sent; case 10: case "end": return _context25.stop(); } } }, _callee25, this); })); function _fetchStreams() { return _fetchStreams2.apply(this, arguments); } return _fetchStreams; }() /** * Load the attributes of this conversation and instantiate its participants * and messages. This or _subscribe will need to be called before any events * on the conversation will fire. This will need to be called before any * events on participants or messages will fire * @internal */ }, { key: "_subscribeStreams", value: function () { var _subscribeStreams2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee26() { var _this$_entity3, _this$_entity4, _this$_messagesList, _this$_participantsMa, data, messagesObjectName, rosterObjectName; return _regeneratorRuntime$1.wrap(function _callee26$(_context26) { while (1) { switch (_context26.prev = _context26.next) { case 0: _context26.prev = 0; _context26.next = 3; return this._subscribe(); case 3: Conversation._logger.trace("_subscribeStreams, this.entity.data=", (_this$_entity3 = this._entity) === null || _this$_entity3 === void 0 ? void 0 : _this$_entity3.data); data = (_this$_entity4 = this._entity) === null || _this$_entity4 === void 0 ? void 0 : _this$_entity4.data; messagesObjectName = data.messages; rosterObjectName = data.roster; _context26.next = 9; return Promise.all([this._messagesEntity.subscribe((_this$_messagesList = this._messagesList) !== null && _this$_messagesList !== void 0 ? _this$_messagesList : messagesObjectName), this._participantsEntity.subscribe((_this$_participantsMa = this._participantsMap) !== null && _this$_participantsMa !== void 0 ? _this$_participantsMa : rosterObjectName)]); case 9: _context26.next = 16; break; case 11: _context26.prev = 11; _context26.t0 = _context26["catch"](0); if (this._services.syncClient.connectionState !== "disconnected") { Conversation._logger.error("Failed to subscribe on conversation objects", this.sid, _context26.t0); } Conversation._logger.debug("ERROR: Failed to subscribe on conversation objects", this.sid, _context26.t0); throw _context26.t0; case 16: case "end": return _context26.stop(); } } }, _callee26, this, [[0, 11]]); })); function _subscribeStreams() { return _subscribeStreams2.apply(this, arguments); } return _subscribeStreams; }() /** * Stop listening for and firing events on this conversation. * @internal */ }, { key: "_unsubscribe", value: function () { var _unsubscribe2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee27() { return _regeneratorRuntime$1.wrap(function _callee27$(_context27) { while (1) { switch (_context27.prev = _context27.next) { case 0: if (!this._entity) { _context27.next = 5; break; } _context27.next = 3; return this._entity.close(); case 3: this._entity = null; this._entityPromise = null; case 5: return _context27.abrupt("return", Promise.all([this._participantsEntity.unsubscribe(), this._messagesEntity.unsubscribe()])); case 6: case "end": return _context27.stop(); } } }, _callee27, this); })); function _unsubscribe() { return _unsubscribe2.apply(this, arguments); } return _unsubscribe; }() /** * Set conversation status. * @internal */ }, { key: "_setStatus", value: function _setStatus(status, source) { var _this3 = this; this._dataSource = source; if (this._internalState.status === status) { return; } this._internalState.status = status; if (status === "joined") { this._subscribeStreams().catch(function (err) { Conversation._logger.debug("ERROR while setting conversation status " + status, err); if (_this3._services.syncClient.connectionState !== "disconnected") { throw err; } }); return; } if (this._entityPromise) { this._unsubscribe().catch(function (err) { Conversation._logger.debug("ERROR while setting conversation status " + status, err); if (_this3._services.syncClient.connectionState !== "disconnected") { throw err; } }); } } /** * Update the local conversation object with new values. * @internal */ }, { key: "_update", value: function _update(update) { var _update$lastMessage, _update$lastMessage2, _this$_internalState$4, _this$_internalState$5, _this$_internalState$6; Conversation._logger.trace("_update", update); Conversation.preprocessUpdate(update, this.sid); var updateReasons = new Set(); for (var _i = 0, _Object$keys = Object.keys(update); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; var localKey = fieldMappings[key]; if (!localKey) { continue; } switch (localKey) { case fieldMappings.status: if (!update.status || update.status === "unknown" || this._internalState.status === update.status) { break; } this._internalState.status = update.status; updateReasons.add(localKey); break; case fieldMappings.attributes: if (isEqual(this._internalState.attributes, update.attributes)) { break; } this._internalState.attributes = update.attributes; updateReasons.add(localKey); break; case fieldMappings.lastConsumedMessageIndex: if (update.lastConsumedMessageIndex === undefined || update.lastConsumedMessageIndex === this._internalState.lastReadMessageIndex) { break; } this._internalState.lastReadMessageIndex = update.lastConsumedMessageIndex; updateReasons.add("lastReadMessageIndex"); break; case fieldMappings.lastMessage: if (this._internalState.lastMessage && !update.lastMessage) { delete this._internalState.lastMessage; updateReasons.add(localKey); break; } this._internalState.lastMessage = this._internalState.lastMessage || {}; if (((_update$lastMessage = update.lastMessage) === null || _update$lastMessage === void 0 ? void 0 : _update$lastMessage.index) !== undefined && update.lastMessage.index !== this._internalState.lastMessage.index) { this._internalState.lastMessage.index = update.lastMessage.index; updateReasons.add(localKey); } if (((_update$lastMessage2 = update.lastMessage) === null || _update$lastMessage2 === void 0 ? void 0 : _update$lastMessage2.timestamp) !== undefined && ((_this$_internalState$4 = this._internalState.lastMessage) === null || _this$_internalState$4 === void 0 ? void 0 : (_this$_internalState$5 = _this$_internalState$4.dateCreated) === null || _this$_internalState$5 === void 0 ? void 0 : _this$_internalState$5.getTime()) !== update.lastMessage.timestamp.getTime()) { this._internalState.lastMessage.dateCreated = update.lastMessage.timestamp; updateReasons.add(localKey); } if (isEqual(this._internalState.lastMessage, {})) { delete this._internalState.lastMessage; } break; case fieldMappings.state: var state = update.state || undefined; if (state !== undefined) { state.dateUpdated = new Date(state.dateUpdated); } if (isEqual(this._internalState.state, state)) { break; } this._internalState.state = state; updateReasons.add(localKey); break; case fieldMappings.bindings: if (isEqual(this._internalState.bindings, update.bindings)) { break; } this._internalState.bindings = update.bindings; updateReasons.add(localKey); break; default: var isDate = update[key] instanceof Date; var keysMatchAsDates = isDate && ((_this$_internalState$6 = this._internalState[localKey]) === null || _this$_internalState$6 === void 0 ? void 0 : _this$_internalState$6.getTime()) === update[key].getTime(); var keysMatchAsNonDates = !isDate && this[localKey] === update[key]; if (keysMatchAsDates || keysMatchAsNonDates) { break; } this._internalState[localKey] = update[key]; updateReasons.add(localKey); } } if (updateReasons.size > 0) { this.emit("updated", { conversation: this, updateReasons: _toConsumableArray$1(updateReasons) }); } } /** * Handle onMessageAdded event. */ }, { key: "_onMessageAdded", value: function _onMessageAdded(message) { var _iterator = _createForOfIteratorHelper$1(this._participants.values()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var participant = _step.value; if (participant.identity === message.author) { participant._endTyping(); break; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this.emit("messageAdded", message); } /** * Set last read message index. * @param index New index to set. */ }, { key: "_setLastReadMessageIndex", value: function () { var _setLastReadMessageIndex2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee28(index) { var result; return _regeneratorRuntime$1.wrap(function _callee28$(_context28) { while (1) { switch (_context28.prev = _context28.next) { case 0: _context28.next = 2; return this._services.commandExecutor.mutateResource("post", "".concat(this._configuration.links.myConversations, "/").concat(this.sid), { last_read_message_index: index }); case 2: result = _context28.sent; return _context28.abrupt("return", result.unread_messages_count); case 4: case "end": return _context28.stop(); } } }, _callee28, this); })); function _setLastReadMessageIndex(_x19) { return _setLastReadMessageIndex2.apply(this, arguments); } return _setLastReadMessageIndex; }() }], [{ key: "preprocessUpdate", value: function preprocessUpdate(update, conversationSid) { try { if (typeof update.attributes === "string") { update.attributes = JSON.parse(update.attributes); } else if (update.attributes) { JSON.stringify(update.attributes); } } catch (e) { Conversation._logger.warn("Retrieved malformed attributes from the server for conversation: " + conversationSid); update.attributes = {}; } try { if (update.dateCreated) { update.dateCreated = new Date(update.dateCreated); } } catch (e) { Conversation._logger.warn("Retrieved malformed dateCreated from the server for conversation: " + conversationSid); delete update.dateCreated; } try { if (update.dateUpdated) { update.dateUpdated = new Date(update.dateUpdated); } } catch (e) { Conversation._logger.warn("Retrieved malformed dateUpdated from the server for conversation: " + conversationSid); delete update.dateUpdated; } try { if (update.lastMessage && update.lastMessage.timestamp) { update.lastMessage.timestamp = new Date(update.lastMessage.timestamp); } } catch (e) { Conversation._logger.warn("Retrieved malformed lastMessage.timestamp from the server for conversation: " + conversationSid); delete update.lastMessage.timestamp; } } }]); return Conversation; }(ReplayEventEmitter_1); _defineProperty$3(Conversation, "participantJoined", "participantJoined"); _defineProperty$3(Conversation, "participantLeft", "participantLeft"); _defineProperty$3(Conversation, "participantUpdated", "participantUpdated"); _defineProperty$3(Conversation, "messageAdded", "messageAdded"); _defineProperty$3(Conversation, "messageRemoved", "messageRemoved"); _defineProperty$3(Conversation, "messageUpdated", "messageUpdated"); _defineProperty$3(Conversation, "typingEnded", "typingEnded"); _defineProperty$3(Conversation, "typingStarted", "typingStarted"); _defineProperty$3(Conversation, "updated", "updated"); _defineProperty$3(Conversation, "removed", "removed"); _defineProperty$3(Conversation, "_logger", Logger.scope("Conversation")); __decorate$1([validateTypesAsync_1(nonEmptyString_1, optionalJson), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, Object]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "add", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1, nonEmptyString_1, optionalJson), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, String, Object, Object]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "addNonChatParticipant", null); __decorate$1([validateTypesAsync_1(nonNegativeInteger_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Number]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "advanceLastReadMessageIndex", null); __decorate$1([validateTypesAsync_1(["undefined", nonNegativeInteger_1], ["undefined", nonNegativeInteger_1], ["undefined", literal_1("backwards", "forward")]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Number, Number, String]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "getMessages", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "getParticipantBySid", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "getParticipantByIdentity", null); __decorate$1([validateTypesAsync_1([nonEmptyString_1, Participant]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "removeParticipant", null); __decorate$1([validateTypesAsync_1(["string", FormData, literal_1(null), objectSchema_1("media options", { contentType: nonEmptyString_1, media: custom_1(function (value) { var isValid = typeof value === "string" && value.length > 0 || value instanceof Uint8Array || value instanceof ArrayBuffer; if (typeof Blob === "function") { isValid = isValid || value instanceof Blob; } return [isValid, "a non-empty string, an instance of Buffer or an instance of Blob"]; }) })], optionalJson, ["undefined", literal_1(null), objectSchema_1("email attributes", { subject: [nonEmptyString_1, "undefined"] })]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object, Object, Object]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "sendMessage", null); __decorate$1([validateTypesAsync_1(literal_1("default", "muted")), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "setUserNotificationLevel", null); __decorate$1([validateTypesAsync_1(json), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "updateAttributes", null); __decorate$1([validateTypesAsync_1("string"), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "updateFriendlyName", null); __decorate$1([validateTypesAsync_1([literal_1(null), nonNegativeInteger_1]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Number]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "updateLastReadMessageIndex", null); __decorate$1([validateTypesAsync_1(["string", literal_1(null)]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], Conversation.prototype, "updateUniqueName", null); var Deferred = /*#__PURE__*/function () { function Deferred() { var _this = this; _classCallCheck$4(this, Deferred); this._promise = new Promise(function (resolve, reject) { _this._resolve = resolve; _this._reject = reject; }); } _createClass$4(Deferred, [{ key: "promise", get: function get() { return this._promise; } }, { key: "update", value: function update(value) { this._resolve(value); } }, { key: "set", value: function set(value) { this.current = value; this._resolve(value); } }, { key: "fail", value: function fail(e) { this._reject(e); } }]); return Deferred; }(); function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty$3(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var log$1 = Logger.scope("Conversations"); /** * Represents conversations collection * {@see Conversation} */ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Conversations, _ReplayEventEmitter); var _super = _createSuper$2(Conversations); function Conversations(configuration, services) { var _this; _classCallCheck$4(this, Conversations); _this = _super.call(this); _defineProperty$3(_assertThisInitialized$3(_this), "conversations", new Map()); _defineProperty$3(_assertThisInitialized$3(_this), "myConversationsRead", new Deferred()); _defineProperty$3(_assertThisInitialized$3(_this), "tombstones", new Set()); _defineProperty$3(_assertThisInitialized$3(_this), "myConversationsFetched", false); _this.configuration = configuration; _this.services = services; return _this; } _createClass$4(Conversations, [{ key: "addConversation", value: function () { var _addConversation = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(options) { var _response$sid, _response$sync_object, _response$sync_object2; var attributes, response, conversationSid, conversationDocument, links, existingConversation, conversation; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: attributes = typeof (options === null || options === void 0 ? void 0 : options.attributes) !== "undefined" ? options.attributes : {}; _context.next = 3; return this.services.commandExecutor.mutateResource("post", this.configuration.links.conversations, { friendly_name: options.friendlyName, unique_name: options.uniqueName, attributes: typeof attributes !== "undefined" ? JSON.stringify(attributes) : undefined }); case 3: response = _context.sent; conversationSid = (_response$sid = response.sid) !== null && _response$sid !== void 0 ? _response$sid : null; conversationDocument = (_response$sync_object = (_response$sync_object2 = response.sync_objects) === null || _response$sync_object2 === void 0 ? void 0 : _response$sync_object2.conversation) !== null && _response$sync_object !== void 0 ? _response$sync_object : null; links = _objectSpread$2({ self: response.url }, response.links); existingConversation = this.conversations.get(conversationSid); if (!existingConversation) { _context.next = 12; break; } _context.next = 11; return existingConversation._subscribe(); case 11: return _context.abrupt("return", existingConversation); case 12: conversation = new Conversation({ channel: conversationDocument, entityName: "", uniqueName: "", attributes: null, createdBy: "", friendlyName: "", lastConsumedMessageIndex: 0, dateCreated: null, dateUpdated: null }, conversationSid, links, this.configuration, this.services); this.conversations.set(conversation.sid, conversation); this._registerForEvents(conversation); _context.next = 17; return conversation._subscribe(); case 17: this.emit("conversationAdded", conversation); return _context.abrupt("return", conversation); case 19: case "end": return _context.stop(); } } }, _callee, this); })); function addConversation(_x) { return _addConversation.apply(this, arguments); } return addConversation; }() /** * Fetch conversations list and instantiate all necessary objects */ }, { key: "fetchConversations", value: function () { var _fetchConversations = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2() { var _this2 = this; var map, myConversations, upserts, _iterator, _step, conversation, errorMessage; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; _context2.next = 3; return this._getMap(); case 3: map = _context2.sent; map.on("itemAdded", function (args) { log$1.debug("itemAdded: ".concat(args.item.key)); _this2._upsertConversation("sync", args.item.key, args.item.data); }); map.on("itemRemoved", function (args) { log$1.debug("itemRemoved: ".concat(args.key)); var sid = args.key; if (!_this2.myConversationsFetched) { _this2.tombstones.add(sid); } var conversation = _this2.conversations.get(sid); if (!conversation) { return; } if (conversation.status === "joined") { conversation._setStatus("notParticipating", "sync"); _this2.emit("conversationLeft", conversation); } _this2.conversations.delete(sid); _this2.emit("conversationRemoved", conversation); conversation.emit("removed", conversation); }); map.on("itemUpdated", function (args) { log$1.debug("itemUpdated: ".concat(args.item.key)); _this2._upsertConversation("sync", args.item.key, args.item.data); }); _context2.next = 9; return this._fetchMyConversations(); case 9: myConversations = _context2.sent; upserts = []; _iterator = _createForOfIteratorHelper(myConversations); try { for (_iterator.s(); !(_step = _iterator.n()).done;) { conversation = _step.value; upserts.push(this._upsertConversation("rest", conversation["channel_sid"], conversation)); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this.myConversationsRead.set(true); _context2.next = 16; return Promise.all(upserts); case 16: this.myConversationsFetched = true; this.tombstones.clear(); log$1.debug("The conversations list has been successfully fetched"); return _context2.abrupt("return", this); case 22: _context2.prev = 22; _context2.t0 = _context2["catch"](0); errorMessage = "Failed to fetch the conversations list"; if (this.services.syncClient.connectionState !== "disconnected") { log$1.error(errorMessage, _context2.t0); } log$1.debug("ERROR: ".concat(errorMessage), _context2.t0); throw _context2.t0; case 28: case "end": return _context2.stop(); } } }, _callee2, this, [[0, 22]]); })); function fetchConversations() { return _fetchConversations.apply(this, arguments); } return fetchConversations; }() }, { key: "getConversations", value: function () { var _getConversations = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3() { var _this3 = this; var conversationsMap, page; return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this._getMap(); case 2: conversationsMap = _context3.sent; _context3.next = 5; return conversationsMap.getItems(); case 5: page = _context3.sent; return _context3.abrupt("return", this._wrapPaginator(page, function (items) { return Promise.all(items.map(function (item) { return _this3._upsertConversation("sync", item.key, item.data); })); })); case 7: case "end": return _context3.stop(); } } }, _callee3, this); })); function getConversations() { return _getConversations.apply(this, arguments); } return getConversations; }() }, { key: "getConversation", value: function () { var _getConversation = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee4(sid) { var _this4 = this; var conversationsMap, page, items; return _regeneratorRuntime$1.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._getMap(); case 2: conversationsMap = _context4.sent; _context4.next = 5; return conversationsMap.getItems({ key: sid }); case 5: page = _context4.sent; items = page.items.map(function (item) { return _this4._upsertConversation("sync", item.key, item.data); }); return _context4.abrupt("return", items.length > 0 ? items[0] : null); case 8: case "end": return _context4.stop(); } } }, _callee4, this); })); function getConversation(_x2) { return _getConversation.apply(this, arguments); } return getConversation; }() }, { key: "getConversationByUniqueName", value: function () { var _getConversationByUniqueName = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee5(uniqueName) { var url, response, body, sid, data; return _regeneratorRuntime$1.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: url = new UriBuilder$1(this.configuration.links.myConversations).path(uniqueName).build(); _context5.next = 3; return this.services.network.get(url); case 3: response = _context5.sent; body = response.body; sid = body.conversation_sid; data = { entityName: null, lastConsumedMessageIndex: body.last_read_message_index, status: (body === null || body === void 0 ? void 0 : body.status) || "unknown", friendlyName: body.friendly_name, dateUpdated: body.date_updated, dateCreated: body.date_created, uniqueName: body.unique_name, createdBy: body.created_by, attributes: body.attributes, channel: body.sync_objects.conversation, notificationLevel: body === null || body === void 0 ? void 0 : body.notification_level, sid: sid }; return _context5.abrupt("return", sid ? this._upsertConversation("sync", sid, data) : null); case 8: case "end": return _context5.stop(); } } }, _callee5, this); })); function getConversationByUniqueName(_x3) { return _getConversationByUniqueName.apply(this, arguments); } return getConversationByUniqueName; }() }, { key: "peekConversation", value: function () { var _peekConversation = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee6(sid) { var url, response, body, data; return _regeneratorRuntime$1.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: url = new UriBuilder$1(this.configuration.links.conversations).path(sid).build(); _context6.next = 3; return this.services.network.get(url); case 3: response = _context6.sent; body = response.body; data = { entityName: null, // lastConsumedMessageIndex: body.last_read_message_index, status: (body === null || body === void 0 ? void 0 : body.status) || "unknown", friendlyName: body.friendly_name, dateUpdated: body.date_updated, dateCreated: body.date_created, uniqueName: body.unique_name, createdBy: body.created_by, attributes: body.attributes, channel: "".concat(sid, ".channel"), // notificationLevel: body?.notification_level, sid: sid }; return _context6.abrupt("return", this._upsertConversation("sync", sid, data)); case 7: case "end": return _context6.stop(); } } }, _callee6, this); })); function peekConversation(_x4) { return _peekConversation.apply(this, arguments); } return peekConversation; }() }, { key: "_getMap", value: function () { var _getMap2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee7() { return _regeneratorRuntime$1.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return this.services.syncClient.map({ id: this.configuration.myConversations, mode: "open_existing" }); case 2: return _context7.abrupt("return", _context7.sent); case 3: case "end": return _context7.stop(); } } }, _callee7, this); })); function _getMap() { return _getMap2.apply(this, arguments); } return _getMap; }() }, { key: "_wrapPaginator", value: function () { var _wrapPaginator2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee8(page, op) { var _this5 = this; var items; return _regeneratorRuntime$1.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; return op(page.items); case 2: items = _context8.sent; return _context8.abrupt("return", { items: items.filter(function (item) { return item !== null; }), hasNextPage: page.hasNextPage, hasPrevPage: page.hasPrevPage, nextPage: function nextPage() { return page.nextPage().then(function (x) { return _this5._wrapPaginator(x, op); }); }, prevPage: function prevPage() { return page.prevPage().then(function (x) { return _this5._wrapPaginator(x, op); }); } }); case 4: case "end": return _context8.stop(); } } }, _callee8); })); function _wrapPaginator(_x5, _x6) { return _wrapPaginator2.apply(this, arguments); } return _wrapPaginator; }() }, { key: "_updateConversation", value: function () { var _updateConversation2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee9(source, conversation, data) { var areSourcesDifferent, isChannelSourceSync, updateData; return _regeneratorRuntime$1.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: areSourcesDifferent = conversation._statusSource !== undefined && source !== conversation._statusSource; isChannelSourceSync = source !== "rest" || conversation._statusSource === "sync"; if (!(areSourcesDifferent && isChannelSourceSync && source !== "sync")) { _context9.next = 5; break; } log$1.trace("upsertConversation: conversation is known from sync and came from REST, ignoring", { sid: conversation.sid, data: data.status, conversation: conversation.status }); return _context9.abrupt("return"); case 5: if (!(data.status === "joined" && conversation.status !== "joined")) { _context9.next = 15; break; } conversation._setStatus("joined", source); updateData = {}; if (typeof data.notificationLevel !== "undefined") { updateData.notificationLevel = data.notificationLevel; } if (typeof data.lastConsumedMessageIndex !== "undefined") { updateData.lastConsumedMessageIndex = data.lastConsumedMessageIndex; } if (!isEqual(updateData, {})) { conversation._update(updateData); } _context9.next = 13; return conversation._subscribe(); case 13: this.emit("conversationJoined", conversation); return _context9.abrupt("return"); case 15: if (!(data.status === "notParticipating" && conversation.status === "joined")) { _context9.next = 22; break; } conversation._setStatus("notParticipating", source); conversation._update(data); _context9.next = 20; return conversation._subscribe(); case 20: this.emit("conversationLeft", conversation); return _context9.abrupt("return"); case 22: if (!(data.status === "notParticipating")) { _context9.next = 26; break; } _context9.next = 25; return conversation._subscribe(); case 25: return _context9.abrupt("return"); case 26: conversation._update(data); case 27: case "end": return _context9.stop(); } } }, _callee9, this); })); function _updateConversation(_x7, _x8, _x9) { return _updateConversation2.apply(this, arguments); } return _updateConversation; }() }, { key: "_upsertConversation", value: function () { var _upsertConversation2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee10(source, sid, data) { var conversation, baseLink, links, newConversation; return _regeneratorRuntime$1.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: log$1.trace("upsertConversation called for ".concat(sid), data); conversation = this.conversations.get(sid); // If the channel is known, update it if (!conversation) { _context10.next = 9; break; } log$1.trace("upsertConversation: the conversation ".concat(conversation.sid, " is known;") + "its status is known from the source ".concat(conversation._statusSource, " ") + "and the update came from the source ".concat(source), conversation); _context10.next = 6; return this._updateConversation(source, conversation, data); case 6: _context10.next = 8; return conversation._subscribe(); case 8: return _context10.abrupt("return", conversation); case 9: if (!(source === "rest" && this.tombstones.has(sid))) { _context10.next = 12; break; } log$1.trace("upsertChannel: the conversation is deleted but reappeared again from REST, ignoring", sid); return _context10.abrupt("return", null); case 12: // If the conversation is unknown, fetch it log$1.trace("upsertConversation: creating a local conversation object with sid " + sid, data); baseLink = "".concat(this.configuration.links.conversations, "/").concat(sid); links = { self: baseLink, messages: "".concat(baseLink, "/Messages"), participants: "".concat(baseLink, "/Participants") }; newConversation = new Conversation(data, sid, links, this.configuration, this.services); this.conversations.set(sid, newConversation); _context10.prev = 17; _context10.next = 20; return newConversation._subscribe(); case 20: if (!(data.status === "joined")) { _context10.next = 23; break; } _context10.next = 23; return newConversation._fetchStreams(); case 23: _context10.next = 32; break; case 25: _context10.prev = 25; _context10.t0 = _context10["catch"](17); if (!(_context10.t0.name !== "SyncError")) { _context10.next = 29; break; } throw _context10.t0; case 29: log$1.trace("upsertChannel: the conversation is missing some Sync entity(ies), ignoring", sid, _context10.t0); this.conversations.delete(sid); return _context10.abrupt("return", null); case 32: this._registerForEvents(newConversation); this.emit("conversationAdded", newConversation); if (data.status === "joined") { newConversation._setStatus("joined", source); this.emit("conversationJoined", newConversation); } return _context10.abrupt("return", newConversation); case 36: case "end": return _context10.stop(); } } }, _callee10, this, [[17, 25]]); })); function _upsertConversation(_x10, _x11, _x12) { return _upsertConversation2.apply(this, arguments); } return _upsertConversation; }() }, { key: "_fetchMyConversations", value: function () { var _fetchMyConversations2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee11() { var conversations, pageToken, _response$body, url, response, receivedConversations; return _regeneratorRuntime$1.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: conversations = []; pageToken = null; case 2: url = new UriBuilder$1(this.configuration.links.myConversations); if (pageToken) { url.arg("PageToken", pageToken); } _context11.next = 6; return this.services.network.get(url.build()); case 6: response = _context11.sent; receivedConversations = (_response$body = response.body) === null || _response$body === void 0 ? void 0 : _response$body.conversations.map(function (conversationDescriptor) { return { descriptor: conversationDescriptor, channel_sid: conversationDescriptor.conversation_sid, status: conversationDescriptor.status, channel: conversationDescriptor.sync_objects.conversation, messages: conversationDescriptor.sync_objects.messages, roster: "".concat(conversationDescriptor.conversation_sid, ".roster"), lastConsumedMessageIndex: conversationDescriptor.last_read_message_index, notificationLevel: conversationDescriptor.notification_level }; }); pageToken = response.body.meta.next_token; conversations = [].concat(_toConsumableArray$1(conversations), _toConsumableArray$1(receivedConversations)); case 10: if (pageToken) { _context11.next = 2; break; } case 11: return _context11.abrupt("return", conversations); case 12: case "end": return _context11.stop(); } } }, _callee11, this); })); function _fetchMyConversations() { return _fetchMyConversations2.apply(this, arguments); } return _fetchMyConversations; }() }, { key: "_onConversationRemoved", value: function _onConversationRemoved(sid) { var conversation = this.conversations.get(sid); if (conversation) { this.conversations.delete(sid); this.emit("conversationRemoved", conversation); } } }, { key: "_registerForEvents", value: function _registerForEvents(conversation) { var _this6 = this; conversation.on("removed", function () { return _this6._onConversationRemoved(conversation.sid); }); conversation.on("updated", function (args) { return _this6.emit("conversationUpdated", args); }); conversation.on("participantJoined", function (participant) { return _this6.emit("participantJoined", participant); }); conversation.on("participantLeft", function (participant) { return _this6.emit("participantLeft", participant); }); conversation.on("participantUpdated", function (args) { return _this6.emit("participantUpdated", args); }); conversation.on("messageAdded", function (message) { return _this6.emit("messageAdded", message); }); conversation.on("messageUpdated", function (args) { return _this6.emit("messageUpdated", args); }); conversation.on("messageRemoved", function (message) { return _this6.emit("messageRemoved", message); }); conversation.on("typingStarted", function (participant) { return _this6.emit("typingStarted", participant); }); conversation.on("typingEnded", function (participant) { return _this6.emit("typingEnded", participant); }); } }]); return Conversations; }(ReplayEventEmitter_1); var $$1 = _export; var $find = arrayIteration.find; var addToUnscopables = addToUnscopables$3; var FIND = 'find'; var SKIPS_HOLES = true; // Shouldn't skip holes if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; }); // `Array.prototype.find` method // https://tc39.es/ecma262/#sec-array.prototype.find $$1({ target: 'Array', proto: true, forced: SKIPS_HOLES }, { find: function find(callbackfn /* , that = undefined */) { return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables addToUnscopables(FIND); function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * Container for known users */ var Users = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Users, _ReplayEventEmitter); var _super = _createSuper$1(Users); function Users(myself, configuration, services) { var _this; _classCallCheck$4(this, Users); _this = _super.call(this); _this.configuration = configuration; _this.services = services; _this.fifoStack = []; _this.myself = myself; _this.myself.on("updated", function (args) { return _this.emit("userUpdated", args); }); _this.myself.on("userSubscribed", function () { return _this.emit("userSubscribed", _this.myself); }); _this.myself.on("userUnsubscribed", function () { _this.emit("userUnsubscribed", _this.myself); _this.myself._ensureFetched(); }); _this.subscribedUsers = new Map(); return _this; } _createClass$4(Users, [{ key: "handleUnsubscribeUser", value: function handleUnsubscribeUser(user) { if (this.subscribedUsers.has(user.identity)) { this.subscribedUsers.delete(user.identity); } var foundItemIndex = 0; var foundItem = this.fifoStack.find(function (item, index) { if (item == user.identity) { foundItemIndex = index; return true; } return false; }); if (foundItem) { this.fifoStack.splice(foundItemIndex, 1); } this.emit("userUnsubscribed", user); } }, { key: "handleSubscribeUser", value: function handleSubscribeUser(user) { if (this.subscribedUsers.has(user.identity)) { return; } if (this.fifoStack.length >= this.configuration.userInfosToSubscribe) { var _this$subscribedUsers, _this$subscribedUsers2; var item = this.fifoStack.shift(); (_this$subscribedUsers = this.subscribedUsers) === null || _this$subscribedUsers === void 0 ? void 0 : (_this$subscribedUsers2 = _this$subscribedUsers.get(item)) === null || _this$subscribedUsers2 === void 0 ? void 0 : _this$subscribedUsers2.unsubscribe(); } this.fifoStack.push(user.identity); this.subscribedUsers.set(user.identity, user); this.emit("userSubscribed", user); } /** * Gets user, if it's in subscribed list - then return the user object from it, * if not - then subscribes and adds user to the FIFO stack * @returns {Promise} Fully initialized user */ }, { key: "getUser", value: function () { var _getUser = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(identity, entityName) { var _entityName, _this2 = this; var user, newUser; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.myself._ensureFetched(); case 2: if (!(identity == this.myself.identity)) { _context.next = 4; break; } return _context.abrupt("return", this.myself); case 4: user = this.subscribedUsers.get(identity); if (!user) { _context.next = 7; break; } return _context.abrupt("return", user); case 7: if (!((_entityName = entityName) !== null && _entityName !== void 0)) { _context.next = 11; break; } _context.next = 14; break; case 11: _context.next = 13; return this.getSyncUniqueName(identity); case 13: entityName = _context.sent; case 14: newUser = new User(identity, entityName, this.configuration, this.services); newUser.on("updated", function (args) { return _this2.emit("userUpdated", args); }); newUser.on("userSubscribed", function () { return _this2.handleSubscribeUser(newUser); }); newUser.on("userUnsubscribed", function () { return _this2.handleUnsubscribeUser(newUser); }); _context.next = 20; return newUser._ensureFetched(); case 20: return _context.abrupt("return", newUser); case 21: case "end": return _context.stop(); } } }, _callee, this); })); function getUser(_x, _x2) { return _getUser.apply(this, arguments); } return getUser; }() /** * @returns {Promise>} returns list of subscribed User objects {@see User} */ }, { key: "getSubscribedUsers", value: function () { var _getSubscribedUsers = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2() { var users; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.myself._ensureFetched(); case 2: users = [this.myself]; this.subscribedUsers.forEach(function (user) { return users.push(user); }); return _context2.abrupt("return", users); case 5: case "end": return _context2.stop(); } } }, _callee2, this); })); function getSubscribedUsers() { return _getSubscribedUsers.apply(this, arguments); } return getSubscribedUsers; }() /** * @returns {Promise} User's sync unique name */ }, { key: "getSyncUniqueName", value: function () { var _getSyncUniqueName = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3(identity) { var _response$body$sync_o, _response$body; var url, response; return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: url = new UriBuilder$1(this.configuration.links.users).path(identity).build(); _context3.next = 3; return this.services.network.get(url); case 3: response = _context3.sent; return _context3.abrupt("return", (_response$body$sync_o = (_response$body = response.body) === null || _response$body === void 0 ? void 0 : _response$body.sync_objects.user_info_map) !== null && _response$body$sync_o !== void 0 ? _response$body$sync_o : ""); case 5: case "end": return _context3.stop(); } } }, _callee3, this); })); function getSyncUniqueName(_x3) { return _getSyncUniqueName.apply(this, arguments); } return getSyncUniqueName; }() }]); return Users; }(ReplayEventEmitter_1); var log = Logger.scope("TypingIndicator"); /** * An important note in regards to typing timeout timers. There are two places that the SDK can get the "typing_timeout" attribute from. The first * place that the attribute appears in is the response received from POST -> /v1/typing REST call. In the body of that response, the value of the * "typing_timeout" attribute will be exactly the same as defined in the console. The second place that the attribute appears in is from a * notification of type "twilio.ipmsg.typing_indicator". In this case, the "typing_timeout" value will be +1 of that in the console. This * intentional. The timeout returned from the POST -> /v1/typing call should be used to disable further calls for that period of time. On contrary, * the timeout returned from the notification should be used as the timeout for the "typingEnded" event, +1 is to account for latency. * * @private */ /** * @class TypingIndicator * * @constructor * @private */ var TypingIndicator = /*#__PURE__*/function () { function TypingIndicator(getConversation, config, services) { _classCallCheck$4(this, TypingIndicator); this.configuration = config; this.services = services; this.getConversation = getConversation; this.serviceTypingTimeout = null; this.sentUpdates = new Map(); } _createClass$4(TypingIndicator, [{ key: "typingTimeout", get: function get() { return this.configuration.typingIndicatorTimeoutOverride || this.serviceTypingTimeout || this.configuration.typingIndicatorTimeoutDefault; } /** * Initialize TypingIndicator controller * Registers for needed message types and sets listeners * @private */ }, { key: "initialize", value: function initialize() { var _this = this; // this.services.notificationClient.subscribe(NotificationTypes.TYPING_INDICATOR, 'twilsock'); this.services.notificationClient.on("message", /*#__PURE__*/function () { var _ref = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(type, message) { return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(type === NotificationTypes.TYPING_INDICATOR)) { _context.next = 3; break; } _context.next = 3; return _this._handleRemoteTyping(message); case 3: case "end": return _context.stop(); } } }, _callee); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }()); } /** * Remote participants typing events handler */ }, { key: "_handleRemoteTyping", value: function () { var _handleRemoteTyping2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2(message) { var _this2 = this; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: log.trace("Got new typing indicator ", message); this.getConversation(message.channel_sid).then(function (conversation) { if (!conversation) { return; } conversation._participants.forEach(function (participant) { if (participant.identity !== message.identity) { return; } var timeout = _this2.configuration.typingIndicatorTimeoutOverride ? _this2.configuration.typingIndicatorTimeoutOverride + 1000 : message.typing_timeout * 1000; participant._startTyping(timeout); }); }).catch(function (err) { log.error(err); throw err; }); case 2: case "end": return _context2.stop(); } } }, _callee2, this); })); function _handleRemoteTyping(_x3) { return _handleRemoteTyping2.apply(this, arguments); } return _handleRemoteTyping; }() /** * Send typing event for the given conversation sid * @param {String} conversationSid */ }, { key: "send", value: function send(conversationSid) { var lastUpdate = this.sentUpdates.get(conversationSid); if (lastUpdate && lastUpdate > Date.now() - this.typingTimeout) { return Promise.resolve(); } this.sentUpdates.set(conversationSid, Date.now()); return this._send(conversationSid); } }, { key: "_send", value: function _send(conversationSid) { var _this3 = this; log.trace("Sending typing indicator"); var url = this.configuration.links.typing; var headers = { "Content-Type": "application/x-www-form-urlencoded" }; var body = "ChannelSid=".concat(conversationSid); return this.services.twilsockClient.post(url, headers, body, this.configuration.productId).then(function (response) { if (response.body.hasOwnProperty("typing_timeout")) { _this3.serviceTypingTimeout = response.body.typing_timeout * 1000; } }).catch(function (err) { log.error("Failed to send typing indicator:", err); throw err; }); } }]); return TypingIndicator; }(); /** * Push notification for a Conversations client. */ var PushNotification = /*#__PURE__*/_createClass$4( /** * Title of the notification. */ /** * Text of the notification. */ /** * Sound of the notification. */ /** * Number of the badge. */ /** * Notification action (`click_action` in FCM terms and `category` in APN terms). */ /** * Type of the notification. */ /** * Additional data of the conversation. */ /** * @internal */ function PushNotification(data) { _classCallCheck$4(this, PushNotification); this.title = data.title || null; this.body = data.body || null; this.sound = data.sound || null; this.badge = data.badge || null; this.action = data.action || null; this.type = data.type || null; this.data = data.data || {}; }); var version = "2.3.0"; function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty$3(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var trimSlashes = function trimSlashes(url) { return url.replace(/(^\/+|\/+$)/g, ""); }; var isMutationConflictResponse = function isMutationConflictResponse(response) { return response.status.code === 202; }; var CommandExecutor = /*#__PURE__*/function () { function CommandExecutor(_serviceUrl, _services, _productId) { _classCallCheck$4(this, CommandExecutor); this._serviceUrl = _serviceUrl; this._services = _services; this._productId = _productId; } _createClass$4(CommandExecutor, [{ key: "_preProcessUrl", value: function _preProcessUrl(url) { var trimmedUrl = trimSlashes(url); if (/^https?:\/\//.test(url)) { return trimmedUrl; } return "".concat(trimSlashes(this._serviceUrl), "/").concat(trimmedUrl); } }, { key: "_makeRequest", value: function () { var _makeRequest2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee(method, url, requestBody, headers) { var preProcessedUrl, finalHeaders, response, getUrl; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: preProcessedUrl = this._preProcessUrl(url); finalHeaders = _objectSpread$1({ "Content-Type": "application/json; charset=utf-8" }, headers || {}); _context.t0 = method; _context.next = _context.t0 === "get" ? 5 : _context.t0 === "post" ? 11 : _context.t0 === "delete" ? 15 : 19; break; case 5: getUrl = preProcessedUrl; if (requestBody) { getUrl += "?" + Object.entries(requestBody).map(function (entry) { return entry.map(encodeURIComponent).join("="); }).join("&"); } _context.next = 9; return this._services.transport.get(getUrl, finalHeaders, this._productId); case 9: response = _context.sent; return _context.abrupt("break", 19); case 11: _context.next = 13; return this._services.transport.post(preProcessedUrl, finalHeaders, JSON.stringify(requestBody), this._productId); case 13: response = _context.sent; return _context.abrupt("break", 19); case 15: _context.next = 17; return this._services.transport.delete(preProcessedUrl, finalHeaders, {}, this._productId); case 17: response = _context.sent; return _context.abrupt("break", 19); case 19: if (!(response.status.code < 200 || response.status.code >= 300)) { _context.next = 21; break; } throw new Error("Request responded with a non-success code ".concat(response.status.code)); case 21: return _context.abrupt("return", response); case 22: case "end": return _context.stop(); } } }, _callee, this); })); function _makeRequest(_x, _x2, _x3, _x4) { return _makeRequest2.apply(this, arguments); } return _makeRequest; }() }, { key: "fetchResource", value: function () { var _fetchResource = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2(url, requestBody) { var _this = this; var maxAttemptsCount, result; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: maxAttemptsCount = 6; _context2.prev = 1; _context2.next = 4; return new AsyncRetrier_1({ min: 50, max: 1600, maxAttemptsCount: maxAttemptsCount }).run(function () { return _this._makeRequest("get", url, requestBody); }); case 4: result = _context2.sent; return _context2.abrupt("return", result.body); case 8: _context2.prev = 8; _context2.t0 = _context2["catch"](1); throw new Error("Fetch resource from \"".concat(url, "\" failed.")); case 11: case "end": return _context2.stop(); } } }, _callee2, null, [[1, 8]]); })); function fetchResource(_x5, _x6) { return _fetchResource.apply(this, arguments); } return fetchResource; }() }, { key: "mutateResource", value: function () { var _mutateResource = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3(method, url, requestBody) { var result; return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this._makeRequest(method, url, requestBody, { "X-Twilio-Mutation-Id": uuid_1.v4() }); case 2: result = _context3.sent; if (!isMutationConflictResponse(result)) { _context3.next = 7; break; } _context3.next = 6; return this.fetchResource(result.body.resource_url); case 6: return _context3.abrupt("return", _context3.sent); case 7: return _context3.abrupt("return", result.body); case 8: case "end": return _context3.stop(); } } }, _callee3, this); })); function mutateResource(_x7, _x8, _x9) { return _mutateResource.apply(this, arguments); } return mutateResource; }() }]); return CommandExecutor; }(); var $ = _export; var FREEZING = freezing; var fails = fails$B; var isObject = isObject$p; var onFreeze = internalMetadata.exports.onFreeze; // eslint-disable-next-line es/no-object-freeze -- safe var $freeze = Object.freeze; var FAILS_ON_PRIMITIVES = fails(function () { $freeze(1); }); // `Object.freeze` method // https://tc39.es/ecma262/#sec-object.freeze $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING }, { freeze: function freeze(it) { return $freeze && isObject(it) ? $freeze(onFreeze(it)) : it; } }); var ContentClient = /*#__PURE__*/function () { function ContentClient(_services) { var _pageSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; var _cacheTtlMs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 5000; _classCallCheck$4(this, ContentClient); _defineProperty$3(this, "_cachedTemplates", null); this._services = _services; this._pageSize = _pageSize; this._cacheTtlMs = _cacheTtlMs; } _createClass$4(ContentClient, [{ key: "getContentTemplates", value: function () { var _getContentTemplates = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee() { var _this = this; var _yield$this$_fetchCon, _yield$this$_fetchCon2, templatesPage, nextToken, templates, _yield$this$_fetchCon3, _yield$this$_fetchCon4; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(this._cachedTemplates !== null)) { _context.next = 2; break; } return _context.abrupt("return", this._cachedTemplates); case 2: _context.next = 4; return this._fetchContentTemplates(); case 4: _yield$this$_fetchCon = _context.sent; _yield$this$_fetchCon2 = _slicedToArray$1(_yield$this$_fetchCon, 2); templatesPage = _yield$this$_fetchCon2[0]; nextToken = _yield$this$_fetchCon2[1]; templates = templatesPage; case 9: if (!(nextToken !== null)) { _context.next = 19; break; } _context.next = 12; return this._fetchContentTemplates(nextToken); case 12: _yield$this$_fetchCon3 = _context.sent; _yield$this$_fetchCon4 = _slicedToArray$1(_yield$this$_fetchCon3, 2); templatesPage = _yield$this$_fetchCon4[0]; nextToken = _yield$this$_fetchCon4[1]; templates = [].concat(_toConsumableArray$1(templates), _toConsumableArray$1(templatesPage)); _context.next = 9; break; case 19: this._cachedTemplates = Object.freeze(templates); setTimeout(function () { _this._cachedTemplates = null; }, this._cacheTtlMs); return _context.abrupt("return", templates); case 22: case "end": return _context.stop(); } } }, _callee, this); })); function getContentTemplates() { return _getContentTemplates.apply(this, arguments); } return getContentTemplates; }() }, { key: "_fetchContentTemplates", value: function () { var _fetchContentTemplates2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2(pageToken) { var contentTemplatesUrl, url, response; return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: contentTemplatesUrl = "Client/v2/ContentTemplates"; url = new UriBuilder$1(contentTemplatesUrl); url.arg("PageSize", this._pageSize); if (pageToken !== undefined) { url.arg("PageToken", pageToken); } _context2.next = 6; return this._services.commandExecutor.fetchResource(url.build()); case 6: response = _context2.sent; return _context2.abrupt("return", [response.templates.map(function (template) { return new ContentTemplate(template); }), response.meta.next_token]); case 8: case "end": return _context2.stop(); } } }, _callee2, this); })); function _fetchContentTemplates(_x) { return _fetchContentTemplates2.apply(this, arguments); } return _fetchContentTemplates; }() }]); return ContentClient; }(); var _class; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty$3(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf$4(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$4(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$4(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Client_1; /** * Client services. */ var ClientServices = /*#__PURE__*/_createClass$4(function ClientServices() { _classCallCheck$4(this, ClientServices); }); /** * A client is the starting point to the Twilio Conversations functionality. */ exports.Client = Client_1 = (_class = /*#__PURE__*/function (_ReplayEventEmitter) { _inherits$4(Client, _ReplayEventEmitter); var _super = _createSuper(Client); /** * Fired when a conversation becomes visible to the client. The event is also * triggered when the client creates a new conversation. * Fired for all conversations that the client has joined. * * Parameters: * 1. {@link Conversation} `conversation` - the conversation in question * @event */ /** * Fired when the client joins a conversation. * * Parameters: * 1. {@link Conversation} `conversation` - the conversation in question * @event */ /** * Fired when the client leaves a conversation. * * Parameters: * 1. {@link Conversation} `conversation` - the conversation in question * @event */ /** * Fired when a conversation is no longer visible to the client. * * Parameters: * 1. {@link Conversation} `conversation` - the conversation in question * @event */ /** * Fired when the attributes or the metadata of a conversation have been * updated. During conversation's creation and initialization, this event * might be fired multiple times for same joined or created conversation as * new data is arriving from different sources. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * {@link Conversation} `conversation` - the conversation in question * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons * for the update * @event */ /** * Fired when a participant has joined a conversation. * * Parameters: * 1. {@link Participant} `participant` - the participant in question * @event */ /** * Fired when a participant has left a conversation. * * Parameters: * 1. {@link Participant} `participant` - the participant in question * @event */ /** * Fired when a participant's fields have been updated. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * {@link Participant} `participant` - the participant in question * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons * for the update * @event */ /** * Fired when a new message has been added to the conversation on the server. * * Parameters: * 1. {@link Message} `message` - the message in question * @event */ /** * Fired when a message is removed from the message list of a conversation. * * Parameters: * 1. {@link Message} `message` - the message in question * @event */ /** * Fired when the fields of an existing message are updated with new values. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * {@link Message} `message` - the message in question * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for * the update * @event */ /** * Fired when the token is about to expire and needs to be updated. * @event */ /** * Fired when the token has expired. * @event */ /** * Fired when a participant has stopped typing. * * Parameters: * 1. {@link Participant} `participant` - the participant in question * @event */ /** * Fired when a participant has started typing. * * Parameters: * 1. {@link Participant} `participant` - the participant in question * @event */ /** * Fired when the client has received (and parsed) a push notification via one * of the push channels (apn or fcm). * * Parameters: * 1. {@link PushNotification} `pushNotification` - the push notification in * question * @event */ /** * Fired when the client has subscribed to a user. * * Parameters: * 1. {@link User} `user` - the user in question * @event */ /** * Fired when the client has unsubscribed from a user. * * Parameters: * 1. {@link User} `user` - the user in question * @event */ /** * Fired when the properties or the reachability status of a user have been * updated. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * {@link User} `user` - the user in question * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the * update * @event */ /** * @deprecated Use initialized or initFailed events instead * Fired when the state of the client has been changed. * * Parameters: * 1. {@link State} `state` - the new client state * @event */ /** * Fired when the client has completed initialization successfully. * @event */ /** * Fired when the client initialization failed. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following property: * * Error? `error` - the initialization error if present * @event */ /** * Fired when the connection state of the client has been changed. * * Parameters: * 1. {@link ConnectionState} `state` - the new connection state * @event */ /** * Fired when the connection is interrupted for an unexpected reason. * * Parameters: * 1. object `data` - info object provided with the event. It has the * following properties: * * boolean `terminal` - Twilsock will stop connection attempts if true * * string `message` - the error message of the root cause * * number? `httpStatusCode` - http status code if available * * number? `errorCode` - Twilio public error code if available * @event */ /** * Current version of the Conversations client. */ /** * Logger instance. */ /** * Supported push notification channels. */ /** * Supported push data fields. */ /** * Current version of the Conversations client. */ /** * Client connection state. */ /** * Returned Conversations instance is not yet fully initialized. Calling any * operations will block until it is. Use connection events to monitor when * client becomes fully available (connectionStateChanged with state * 'connected') or not available (connectionStateChange with state 'denied', * event tokenExpired, event connectionError). * * @param fpaToken Access token * @param options Options to customize the Client * @returns A not yet fully-initialized client. */ function Client(fpaToken) { var _this$_options$logLev, _this$_options$twilso, _this$_options$transp, _this$_options$notifi, _this$_options$syncCl; var _this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck$4(this, Client); _this = _super.call(this); _defineProperty$3(_assertThisInitialized$3(_this), "version", version); _defineProperty$3(_assertThisInitialized$3(_this), "connectionState", "unknown"); _defineProperty$3(_assertThisInitialized$3(_this), "parsePushNotification", Client_1.parsePushNotification); _this._fpaToken = fpaToken !== null && fpaToken !== void 0 ? fpaToken : ""; _this._options = options !== null && options !== void 0 ? options : {}; if (!_this._options.disableDeepClone) { var _options = _objectSpread(_objectSpread({}, _this._options), {}, { transport: undefined, twilsockClient: undefined }); _options = deepClone$1(_options); _options.transport = _this._options.transport; _options.twilsockClient = _this._options.twilsockClient; _this._options = _options; } _this._options.logLevel = (_this$_options$logLev = _this._options.logLevel) !== null && _this$_options$logLev !== void 0 ? _this$_options$logLev : "silent"; Client_1._logger.setLevel(_this._options.logLevel); var productId = _this._options.productId = "ip_messaging"; // Filling ClientMetadata _this._options.clientMetadata = _this._options.clientMetadata || {}; if (!_this._options.clientMetadata.hasOwnProperty("type")) { _this._options.clientMetadata.type = "conversations"; } if (!_this._options.clientMetadata.hasOwnProperty("sdk")) { _this._options.clientMetadata.sdk = "JS"; _this._options.clientMetadata.sdkv = version; } // Enable session local storage for Sync _this._options.Sync = _this._options.Sync || {}; if (typeof _this._options.Sync.enableSessionStorage === "undefined") { _this._options.Sync.enableSessionStorage = true; } if (_this._options.region) { _this._options.Sync.region = _this._options.region; } if (!fpaToken) { throw new Error("A valid Twilio token should be provided"); } _this._services = new ClientServices(); _this._myself = new User("", "", null, _this._services); var startTwilsock = !_this._options.twilsockClient; // Create default init registrations if none were provided. // Otherwise, the outside party have to list all the init registrations they // need. // Init registrations passed to the Conversations client will be passed down // to the Sync client as well. if (!_this._options.initRegistrations) { var initRegistration = new browser$4.InitRegistration(productId); Client_1.populateInitRegistrations(initRegistration); _this._options.initRegistrations = [initRegistration]; } _this._services.twilsockClient = _this._options.twilsockClient = (_this$_options$twilso = _this._options.twilsockClient) !== null && _this$_options$twilso !== void 0 ? _this$_options$twilso : new browser$4.TwilsockClient(fpaToken, productId, _this._options); _this._services.twilsockClient.on("tokenAboutToExpire", function () { return _this.emit("tokenAboutToExpire"); }); _this._services.twilsockClient.on("tokenExpired", function () { return _this.emit("tokenExpired"); }); _this._services.twilsockClient.on("connectionError", function (error) { return _this.emit("connectionError", error); }); _this._services.twilsockClient.on("stateChanged", function (state) { Client_1._logger.debug("Handling stateChanged for ConversationsClient: new state ".concat(state)); if (state !== _this.connectionState) { _this.connectionState = state; _this.emit("connectionStateChanged", _this.connectionState); } }); _this._services.transport = _this._options.transport = (_this$_options$transp = _this._options.transport) !== null && _this$_options$transp !== void 0 ? _this$_options$transp : _this._options.twilsockClient; _this._services.notificationClient = _this._options.notificationsClient = (_this$_options$notifi = _this._options.notificationsClient) !== null && _this$_options$notifi !== void 0 ? _this$_options$notifi : new browser$3.Notifications(fpaToken, _this._options); _this._services.syncClient = _this._options.syncClient = (_this$_options$syncCl = _this._options.syncClient) !== null && _this$_options$syncCl !== void 0 ? _this$_options$syncCl : new SyncClient(fpaToken, _this._options); var configurationOptions = (options === null || options === void 0 ? void 0 : options.Chat) || (options === null || options === void 0 ? void 0 : options.IPMessaging) || options || {}; var region = configurationOptions.region || (options === null || options === void 0 ? void 0 : options.region); var baseUrl = configurationOptions.apiUri || configurationOptions.typingUri || "https://aim.".concat(region || "us1", ".twilio.com"); _this._services.commandExecutor = new CommandExecutor(baseUrl, { transport: _this._options.transport }, productId); _this._services.contentClient = new ContentClient(_this._services); var emitFailed = function emitFailed(error) { _this._rejectEnsureReady(error); _this.emit("stateChanged", "failed"); _this.emit("initFailed", { error: error }); }; var emitDisconnected = function emitDisconnected() { emitFailed({ terminal: true, message: "Twilsock has disconnected." }); }; _this._services.twilsockClient.once("connectionError", emitFailed); _this._services.twilsockClient.once("disconnected", emitDisconnected); _this._services.twilsockClient.once("connected", /*#__PURE__*/_asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee() { var startupEvent, connectionError; return _regeneratorRuntime$1.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: Client_1._logger.debug("ConversationsClient started INITIALIZING"); _this._services.twilsockClient.off("connectionError", emitFailed); _this._services.twilsockClient.off("disconnected", emitDisconnected); _context.prev = 3; startupEvent = "conversations.client.startup"; _this._services.twilsockClient.addPartialTelemetryEvent(new browser$4.TelemetryEventDescription(startupEvent, "Conversations client startup", new Date()), startupEvent, browser$4.TelemetryPoint.Start); _context.next = 8; return _this._initialize(); case 8: _this._services.twilsockClient.addPartialTelemetryEvent(new browser$4.TelemetryEventDescription("", "", new Date()), startupEvent, browser$4.TelemetryPoint.End); _context.next = 17; break; case 11: _context.prev = 11; _context.t0 = _context["catch"](3); // Fail ChatClient if initialization is incomplete connectionError = { terminal: true, message: _context.t0.message }; _this._rejectEnsureReady(connectionError); _this.emit("stateChanged", "failed"); _this.emit("initFailed", { error: connectionError }); case 17: case "end": return _context.stop(); } } }, _callee, null, [[3, 11]]); }))); _this._ensureReady = new Promise(function (resolve, reject) { _this._resolveEnsureReady = resolve; _this._rejectEnsureReady = reject; }).catch(function () { return void 0; }); // @todo How to process unhandled rejection here? if (startTwilsock) { _this._services.twilsockClient.connect(); } return _this; } /** * Information of the logged-in user. Before client initialization, returns an * uninitialized user. Will trigger a {@link Client.userUpdated} event after * initialization. */ _createClass$4(Client, [{ key: "user", get: function get() { return this._myself; } /** * Client reachability state. Throws an error if accessed before the client * initialization was completed. */ }, { key: "reachabilityEnabled", get: function get() { if (!this._configuration) { throw new Error("Reachability information could not yet be accessed as the client " + "has not yet been initialized. Subscribe to the 'stateChanged' event " + "to properly react to the client initialization."); } return this._configuration.reachabilityEnabled; } /** * @deprecated * Current token. * @internal */ }, { key: "token", get: function get() { return this._fpaToken; } /** * @deprecated Call constructor directly. * * Factory method to create a Conversations client instance. * * The factory method will automatically trigger connection. * Do not use it if you need finer-grained control. * * Since this method returns an already-initialized client, some of the events * will be lost because they happen *before* the initialization. It is * recommended that `client.onWithReplay` is used as opposed to `client.on` * for subscribing to client events. The `client.onWithReplay` will re-emit * the most recent value for a given event if it emitted before the * subscription. * * @param token Access token. * @param options Options to customize the client. * @returns Returns a fully initialized client. */ }, { key: "shutdown", value: /** * Gracefully shut down the client. */ function () { var _shutdown = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee2() { return _regeneratorRuntime$1.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this._ensureReady; case 2: _context2.next = 4; return this._services.twilsockClient.disconnect(); case 4: case "end": return _context2.stop(); } } }, _callee2, this); })); function shutdown() { return _shutdown.apply(this, arguments); } return shutdown; }() /** * Update the token used by the client and re-register with the Conversations services. * @param token New access token. */ }, { key: "updateToken", value: function () { var _updateToken = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee3(token) { return _regeneratorRuntime$1.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this._ensureReady; case 2: Client_1._logger.info("updateToken"); if (!(this._fpaToken === token)) { _context3.next = 5; break; } return _context3.abrupt("return", this); case 5: _context3.next = 7; return this._services.twilsockClient.updateToken(token); case 7: _context3.next = 9; return this._services.notificationClient.updateToken(token); case 9: _context3.next = 11; return this._services.mcsClient.updateToken(token); case 11: this._fpaToken = token; return _context3.abrupt("return", this); case 13: case "end": return _context3.stop(); } } }, _callee3, this); })); function updateToken(_x) { return _updateToken.apply(this, arguments); } return updateToken; }() /** * Get a known conversation by its SID. * @param conversationSid Conversation sid */ }, { key: "getConversationBySid", value: function () { var _getConversationBySid = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee4(conversationSid) { var conversation; return _regeneratorRuntime$1.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._ensureReady; case 2: _context4.next = 4; return this._conversationsEntity.myConversationsRead.promise; case 4: _context4.next = 6; return this._conversationsEntity.getConversation(conversationSid); case 6: conversation = _context4.sent; if (conversation) { _context4.next = 12; break; } _context4.next = 10; return this.peekConversationBySid(conversationSid); case 10: conversation = _context4.sent; if (conversation) { deprecationWarning_1("The method getConversationBySid is deprecated to retrieve conversations you're not part of. Use peekConversationBySid instead."); } case 12: if (conversation) { _context4.next = 14; break; } throw new Error("Conversation with SID ".concat(conversationSid, " was not found.")); case 14: return _context4.abrupt("return", conversation); case 15: case "end": return _context4.stop(); } } }, _callee4, this); })); function getConversationBySid(_x2) { return _getConversationBySid.apply(this, arguments); } return getConversationBySid; }() /** * Peek a conversation by its SID. * @param conversationSid Conversation sid * @internal */ }, { key: "peekConversationBySid", value: function () { var _peekConversationBySid = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee5(conversationSid) { var conversation; return _regeneratorRuntime$1.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this._ensureReady; case 2: _context5.next = 4; return this._conversationsEntity.peekConversation(conversationSid); case 4: conversation = _context5.sent; if (conversation) { _context5.next = 7; break; } throw new Error("Conversation with SID ".concat(conversationSid, " was not found.")); case 7: return _context5.abrupt("return", conversation); case 8: case "end": return _context5.stop(); } } }, _callee5, this); })); function peekConversationBySid(_x3) { return _peekConversationBySid.apply(this, arguments); } return peekConversationBySid; }() /** * Get a known conversation by its unique identifier name. * @param uniqueName The unique identifier name of the conversation. */ }, { key: "getConversationByUniqueName", value: function () { var _getConversationByUniqueName = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee6(uniqueName) { var conversation; return _regeneratorRuntime$1.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return this._ensureReady; case 2: _context6.next = 4; return this._conversationsEntity.myConversationsRead.promise; case 4: _context6.next = 6; return this._conversationsEntity.getConversationByUniqueName(uniqueName); case 6: conversation = _context6.sent; if (conversation) { _context6.next = 9; break; } throw new Error("Conversation with unique name ".concat(uniqueName, " was not found.")); case 9: return _context6.abrupt("return", conversation); case 10: case "end": return _context6.stop(); } } }, _callee6, this); })); function getConversationByUniqueName(_x4) { return _getConversationByUniqueName.apply(this, arguments); } return getConversationByUniqueName; }() /** * Get the current list of all the subscribed conversations. */ }, { key: "getSubscribedConversations", value: function () { var _getSubscribedConversations = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee7() { return _regeneratorRuntime$1.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return this._ensureReady; case 2: return _context7.abrupt("return", this._conversationsPromise.then(function (conversations) { return conversations.getConversations(); })); case 3: case "end": return _context7.stop(); } } }, _callee7, this); })); function getSubscribedConversations() { return _getSubscribedConversations.apply(this, arguments); } return getSubscribedConversations; }() /** * Create a conversation on the server and subscribe to its events. * The default is a conversation with an empty friendly name. * @param options Options for the conversation. */ }, { key: "createConversation", value: function () { var _createConversation = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee8(options) { return _regeneratorRuntime$1.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; return this._ensureReady; case 2: options = options || {}; return _context8.abrupt("return", this._conversationsPromise.then(function (conversationsEntity) { return conversationsEntity.addConversation(options); })); case 4: case "end": return _context8.stop(); } } }, _callee8, this); })); function createConversation(_x5) { return _createConversation.apply(this, arguments); } return createConversation; }() /** * Register for push notifications. * @param channelType Channel type. * @param registrationId Push notification ID provided by the FCM/APNS service * on the platform. */ }, { key: "setPushRegistrationId", value: function () { var _setPushRegistrationId = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee9(channelType, registrationId) { return _regeneratorRuntime$1.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return this._ensureReady; case 2: this._subscribeToPushNotifications(channelType); this._services.notificationClient.setPushRegistrationId(channelType, registrationId); _context9.next = 6; return this._services.notificationClient.commitChanges(); case 6: case "end": return _context9.stop(); } } }, _callee9, this); })); function setPushRegistrationId(_x6, _x7) { return _setPushRegistrationId.apply(this, arguments); } return setPushRegistrationId; }() /** * Unregister from push notifications. * @param channelType Channel type. * @deprecated Use removePushRegistrations() instead. */ }, { key: "unsetPushRegistrationId", value: function () { var _unsetPushRegistrationId = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee10(channelType) { return _regeneratorRuntime$1.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return this._ensureReady; case 2: this._unsubscribeFromPushNotifications(channelType); _context10.next = 5; return this._services.notificationClient.commitChanges(); case 5: case "end": return _context10.stop(); } } }, _callee10, this); })); function unsetPushRegistrationId(_x8) { return _unsetPushRegistrationId.apply(this, arguments); } return unsetPushRegistrationId; }() /** * Clear existing registrations directly using provided device token. * This is useful to ensure stopped subscriptions without resubscribing. * * This function goes completely beside the state machine and removes all * registrations. * Use with caution: if it races with current state machine operations, * madness will ensue. * * @param channelType Channel type. * @param registrationId Push notification ID provided by the FCM/APNS service * on the platform. */ }, { key: "removePushRegistrations", value: function () { var _removePushRegistrations = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee11(channelType, registrationId) { return _regeneratorRuntime$1.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: _context11.next = 2; return this._services.notificationClient.removeRegistrations(channelType, registrationId); case 2: case "end": return _context11.stop(); } } }, _callee11, this); })); function removePushRegistrations(_x9, _x10) { return _removePushRegistrations.apply(this, arguments); } return removePushRegistrations; }() /** * Current version of the Conversations client. */ }, { key: "handlePushNotification", value: /** * Handle push notification payload parsing and emit the * {@link Client.pushNotification} event on this {@link Client} instance. * @param notificationPayload Push notification payload */ function () { var _handlePushNotification = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee12(notificationPayload) { return _regeneratorRuntime$1.wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return this._ensureReady; case 2: Client_1._logger.debug("handlePushNotification, notificationPayload=", notificationPayload); this.emit("pushNotification", Client_1.parsePushNotification(notificationPayload)); case 4: case "end": return _context12.stop(); } } }, _callee12, this); })); function handlePushNotification(_x11) { return _handlePushNotification.apply(this, arguments); } return handlePushNotification; }() /** * Gets a user with the given identity. If it's in the subscribed list, then * return the user object from it; * if not, then subscribe and add user to the subscribed list. * @param identity Identity of the user. * @returns A fully initialized user. */ }, { key: "getUser", value: function () { var _getUser = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee13(identity) { return _regeneratorRuntime$1.wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: _context13.next = 2; return this._ensureReady; case 2: return _context13.abrupt("return", this._services.users.getUser(identity)); case 3: case "end": return _context13.stop(); } } }, _callee13, this); })); function getUser(_x12) { return _getUser.apply(this, arguments); } return getUser; }() /** * Get a list of subscribed user objects. */ }, { key: "getSubscribedUsers", value: function () { var _getSubscribedUsers = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee14() { return _regeneratorRuntime$1.wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return this._ensureReady; case 2: return _context14.abrupt("return", this._services.users.getSubscribedUsers()); case 3: case "end": return _context14.stop(); } } }, _callee14, this); })); function getSubscribedUsers() { return _getSubscribedUsers.apply(this, arguments); } return getSubscribedUsers; }() /** * Get content URLs for all media attachments in the given set of media sids * using a single operation. * @param mediaSids Set of media sids to query for the content URL. */ }, { key: "getTemporaryContentUrlsForMediaSids", value: function getTemporaryContentUrlsForMediaSids(mediaSids) { var _this2 = this; return new browser$1.CancellablePromise( /*#__PURE__*/function () { var _ref2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee15(resolve, reject, onCancel) { var request, urls; return _regeneratorRuntime$1.wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: if (!(!_this2._services.mcsClient || !mediaSids)) { _context15.next = 3; break; } reject(new Error("Media Content Service is unavailable")); return _context15.abrupt("return"); case 3: request = _this2._services.mcsClient.mediaSetGetContentUrls(mediaSids); onCancel(function () { request.cancel(); }); _context15.prev = 5; _context15.next = 8; return request; case 8: urls = _context15.sent; resolve(urls); _context15.next = 15; break; case 12: _context15.prev = 12; _context15.t0 = _context15["catch"](5); reject(_context15.t0); case 15: case "end": return _context15.stop(); } } }, _callee15, null, [[5, 12]]); })); return function (_x13, _x14, _x15) { return _ref2.apply(this, arguments); }; }()); } /** * Get content URLs for all media attachments in the given set using a single * operation. * @param contentSet Set of media attachments to query content URLs. */ }, { key: "getTemporaryContentUrlsForMedia", value: function getTemporaryContentUrlsForMedia(contentSet) { // We ignore existing mcsMedia members of each of the media entries. // Instead, we just collect their sids and pull new descriptors from a // mediaSet GET endpoint. var sids = contentSet.map(function (m) { return m.sid; }); return this.getTemporaryContentUrlsForMediaSids(sids); } /** * Returns rich content templates belonging to the account. Rich content * templates can be created via the Twilio console or the REST API. */ }, { key: "getContentTemplates", value: function () { var _getContentTemplates = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee16() { return _regeneratorRuntime$1.wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: _context16.next = 2; return this._ensureReady; case 2: _context16.next = 4; return this._services.contentClient.getContentTemplates(); case 4: return _context16.abrupt("return", _context16.sent); case 5: case "end": return _context16.stop(); } } }, _callee16, this); })); function getContentTemplates() { return _getContentTemplates.apply(this, arguments); } return getContentTemplates; }() /** * Initialize the client. */ }, { key: "_initialize", value: function () { var _initialize2 = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee17() { var _this3 = this; var configurationResponse; return _regeneratorRuntime$1.wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: _context17.next = 2; return this._services.commandExecutor.fetchResource("Client/v2/Configuration"); case 2: configurationResponse = _context17.sent; this._configuration = new Configuration$1(this._options, configurationResponse, Client_1._logger); this._myself._resolveInitialization(this._configuration, this._configuration.userIdentity, this._configuration.userInfo, true); this._services.typingIndicator = new TypingIndicator(this.getConversationBySid.bind(this), this._configuration, this._services); this._services.network = new Network(this._configuration, this._services); this._services.users = new Users(this._myself, this._configuration, this._services); this._services.users.on("userSubscribed", function (user) { _this3.emit("userSubscribed", user); }); this._services.users.on("userUpdated", function (args) { return _this3.emit("userUpdated", args); }); this._services.users.on("userUnsubscribed", function (user) { _this3.emit("userUnsubscribed", user); }); this._conversationsEntity = new Conversations(this._configuration, this._services); this._conversationsEntity.on("conversationAdded", function (conversation) { _this3.emit("conversationAdded", conversation); }); this._conversationsEntity.on("conversationRemoved", function (conversation) { _this3.emit("conversationRemoved", conversation); }); this._conversationsEntity.on("conversationJoined", function (conversation) { _this3.emit("conversationJoined", conversation); }); this._conversationsEntity.on("conversationLeft", function (conversation) { _this3.emit("conversationLeft", conversation); }); this._conversationsEntity.on("conversationUpdated", function (args) { return _this3.emit("conversationUpdated", args); }); this._conversationsEntity.on("participantJoined", function (participant) { _this3.emit("participantJoined", participant); }); this._conversationsEntity.on("participantLeft", function (participant) { _this3.emit("participantLeft", participant); }); this._conversationsEntity.on("participantUpdated", function (args) { return _this3.emit("participantUpdated", args); }); this._conversationsEntity.on("messageAdded", function (message) { return _this3.emit("messageAdded", message); }); this._conversationsEntity.on("messageUpdated", function (args) { return _this3.emit("messageUpdated", args); }); this._conversationsEntity.on("messageRemoved", function (message) { return _this3.emit("messageRemoved", message); }); this._conversationsEntity.on("typingStarted", function (participant) { return _this3.emit("typingStarted", participant); }); this._conversationsEntity.on("typingEnded", function (participant) { return _this3.emit("typingEnded", participant); }); this._conversationsPromise = this._conversationsEntity.fetchConversations().then(function () { return _this3._conversationsEntity; }).catch(function (error) { throw error; }); _context17.next = 28; return this._services.users.myself._ensureFetched(); case 28: Client_1._supportedPushChannels.forEach(function (channelType) { return _this3._subscribeToPushNotifications(channelType); }); this._services.typingIndicator.initialize(); this._services.mcsClient = new browser$1.McsClient(this._fpaToken, this._configuration.links.mediaService, this._configuration.links.mediaSetService, _objectSpread(_objectSpread({}, this._options), {}, { transport: undefined })); this._resolveEnsureReady(); this.emit("stateChanged", "initialized"); this.emit("initialized"); case 34: case "end": return _context17.stop(); } } }, _callee17, this); })); function _initialize() { return _initialize2.apply(this, arguments); } return _initialize; }() /** * Subscribe to push notifications. * @param channelType The channel type to subscribe to. */ }, { key: "_subscribeToPushNotifications", value: function _subscribeToPushNotifications(channelType) { var _this4 = this; [NotificationTypes.NEW_MESSAGE, NotificationTypes.ADDED_TO_CONVERSATION, NotificationTypes.REMOVED_FROM_CONVERSATION, NotificationTypes.TYPING_INDICATOR, NotificationTypes.CONSUMPTION_UPDATE].forEach(function (messageType) { _this4._services.notificationClient.subscribe(channelType, messageType); }); } /** * Unsubscribe from push notifications. * @param channelType The channel type to unsubscribe from. */ }, { key: "_unsubscribeFromPushNotifications", value: function _unsubscribeFromPushNotifications(channelType) { var _this5 = this; [NotificationTypes.NEW_MESSAGE, NotificationTypes.ADDED_TO_CONVERSATION, NotificationTypes.REMOVED_FROM_CONVERSATION, NotificationTypes.TYPING_INDICATOR, NotificationTypes.CONSUMPTION_UPDATE].forEach(function (messageType) { _this5._services.notificationClient.unsubscribe(channelType, messageType); }); } }], [{ key: "create", value: function () { var _create = _asyncToGenerator$1( /*#__PURE__*/_regeneratorRuntime$1.mark(function _callee18(token, options) { var client; return _regeneratorRuntime$1.wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: if (!(options !== null && options !== void 0 && options.twilsockClient)) { _context18.next = 2; break; } throw new Error("Obsolete usage of ConversationsClient.create() " + "factory method: if you pass twilsock from the outside then you must " + "use ConversationsClient constructor and be prepared to work with " + "uninitialized client."); case 2: client = new Client_1(token, options); _context18.next = 5; return client._ensureReady; case 5: return _context18.abrupt("return", client); case 6: case "end": return _context18.stop(); } } }, _callee18); })); function create(_x16, _x17) { return _create.apply(this, arguments); } return create; }() /** * Static method for push notification payload parsing. Returns parsed push as * a {@link PushNotification} object. * @param notificationPayload Push notification payload. */ }, { key: "parsePushNotification", value: function parsePushNotification(notificationPayload) { Client_1._logger.debug("parsePushNotification, notificationPayload=", notificationPayload); // APNS specifics if (typeof notificationPayload.aps !== "undefined") { if (!notificationPayload.twi_message_type) { throw new Error("Provided push notification payload does not contain Programmable Chat push notification type"); } var data = Client_1._parsePushNotificationChatData(notificationPayload); var apsPayload = notificationPayload.aps; var body; var title = null; if (typeof apsPayload.alert === "string") { body = apsPayload.alert || null; } else { var _apsPayload$alert, _apsPayload$alert2; body = ((_apsPayload$alert = apsPayload.alert) === null || _apsPayload$alert === void 0 ? void 0 : _apsPayload$alert.body) || null; title = ((_apsPayload$alert2 = apsPayload.alert) === null || _apsPayload$alert2 === void 0 ? void 0 : _apsPayload$alert2.title) || null; } return new PushNotification({ title: title, body: body, sound: apsPayload.sound || null, badge: apsPayload.badge || null, action: apsPayload.category || null, type: notificationPayload.twi_message_type, data: data }); } // FCM specifics if (typeof notificationPayload.data !== "undefined") { var dataPayload = notificationPayload.data; if (!dataPayload.twi_message_type) { throw new Error("Provided push notification payload does not contain Programmable Chat push notification type"); } var _data = Client_1._parsePushNotificationChatData(notificationPayload.data); return new PushNotification({ title: dataPayload.twi_title || null, body: dataPayload.twi_body || null, sound: dataPayload.twi_sound || null, badge: null, action: dataPayload.twi_action || null, type: dataPayload.twi_message_type, data: _data }); } throw new Error("Provided push notification payload is not Programmable Chat notification"); } /** * Static method for parsing push notification chat data. * @param data Data to parse */ }, { key: "_parsePushNotificationChatData", value: function _parsePushNotificationChatData(data) { var result = {}; for (var key in Client_1._supportedPushDataFields) { var value = data[key]; if (typeof value === "undefined" || value === null) { continue; } if (key === "message_index" || key === "media_count") { var number = parseToNumber(value); if (number !== null) { result[Client_1._supportedPushDataFields[key]] = number; } continue; } if (key === "media") { if (typeof value === "string") { try { result[Client_1._supportedPushDataFields[key]] = JSON.parse(value); } catch (_unused) { Client_1._logger.debug("Media message notification parsing error"); } } continue; } result[Client_1._supportedPushDataFields[key]] = value; } return result; } /** * Populate the client with init registrations. * @param reg The init registration to populate. */ }, { key: "populateInitRegistrations", value: function populateInitRegistrations(reg) { reg.populateInitRegistrations([NotificationTypes.TYPING_INDICATOR]); SyncClient.populateInitRegistrations(reg); } }]); return Client; }(ReplayEventEmitter_1), _defineProperty$3(_class, "conversationAdded", "conversationAdded"), _defineProperty$3(_class, "conversationJoined", "conversationJoined"), _defineProperty$3(_class, "conversationLeft", "conversationLeft"), _defineProperty$3(_class, "conversationRemoved", "conversationRemoved"), _defineProperty$3(_class, "conversationUpdated", "conversationUpdated"), _defineProperty$3(_class, "participantJoined", "participantJoined"), _defineProperty$3(_class, "participantLeft", "participantLeft"), _defineProperty$3(_class, "participantUpdated", "participantUpdated"), _defineProperty$3(_class, "messageAdded", "messageAdded"), _defineProperty$3(_class, "messageRemoved", "messageRemoved"), _defineProperty$3(_class, "messageUpdated", "messageUpdated"), _defineProperty$3(_class, "tokenAboutToExpire", "tokenAboutToExpire"), _defineProperty$3(_class, "tokenExpired", "tokenExpired"), _defineProperty$3(_class, "typingEnded", "typingEnded"), _defineProperty$3(_class, "typingStarted", "typingStarted"), _defineProperty$3(_class, "pushNotification", "pushNotification"), _defineProperty$3(_class, "userSubscribed", "userSubscribed"), _defineProperty$3(_class, "userUnsubscribed", "userUnsubscribed"), _defineProperty$3(_class, "userUpdated", "userUpdated"), _defineProperty$3(_class, "stateChanged", "stateChanged"), _defineProperty$3(_class, "initialized", "initialized"), _defineProperty$3(_class, "initFailed", "initFailed"), _defineProperty$3(_class, "connectionStateChanged", "connectionStateChanged"), _defineProperty$3(_class, "connectionError", "connectionError"), _defineProperty$3(_class, "version", version), _defineProperty$3(_class, "_logger", Logger.scope("Client")), _defineProperty$3(_class, "_supportedPushChannels", ["fcm", "apn"]), _defineProperty$3(_class, "_supportedPushDataFields", { conversation_sid: "conversationSid", conversation_title: "conversationTitle", message_sid: "messageSid", message_index: "messageIndex", media_count: "mediaCount", media: "media" // object }), _class); __decorate$1([deprecated_1("token"), __metadata$1("design:type", String), __metadata$1("design:paramtypes", [])], exports.Client.prototype, "token", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "updateToken", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "getConversationBySid", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "peekConversationBySid", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "getConversationByUniqueName", null); __decorate$1([validateTypesAsync_1(["undefined", objectSchema_1("conversation options", { friendlyName: ["string", "undefined"], isPrivate: ["boolean", "undefined"], uniqueName: ["string", "undefined"] })]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "createConversation", null); __decorate$1([validateTypesAsync_1(literal_1("fcm", "apn"), "string"), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "setPushRegistrationId", null); __decorate$1([validateTypesAsync_1(literal_1("fcm", "apn")), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "unsetPushRegistrationId", null); __decorate$1([validateTypesAsync_1(literal_1("fcm", "apn"), nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "removePushRegistrations", null); __decorate$1([validateTypesAsync_1(pureObject_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "handlePushNotification", null); __decorate$1([validateTypesAsync_1(nonEmptyString_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String]), __metadata$1("design:returntype", Promise)], exports.Client.prototype, "getUser", null); __decorate$1([validateTypesAsync_1(nonEmptyArray_1("strings", "string")), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Array]), __metadata$1("design:returntype", browser$1.CancellablePromise)], exports.Client.prototype, "getTemporaryContentUrlsForMediaSids", null); __decorate$1([validateTypesAsync_1(nonEmptyArray_1("media", Media)), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Array]), __metadata$1("design:returntype", browser$1.CancellablePromise)], exports.Client.prototype, "getTemporaryContentUrlsForMedia", null); __decorate$1([deprecated_1("Client.create()", "new Client()"), validateTypesAsync_1("string", ["undefined", pureObject_1]), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [String, Object]), __metadata$1("design:returntype", Promise)], exports.Client, "create", null); __decorate$1([validateTypes_1(pureObject_1), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", [Object]), __metadata$1("design:returntype", PushNotification)], exports.Client, "parsePushNotification", null); exports.Client = Client_1 = __decorate$1([validateConstructorTypes_1(nonEmptyString_1, [pureObject_1, "undefined"]), __metadata$1("design:paramtypes", [String, Object])], exports.Client); exports.AggregatedDeliveryReceipt = AggregatedDeliveryReceipt; exports.CancellablePromise = browser$1.CancellablePromise; exports.ContentTemplate = ContentTemplate; exports.ContentTemplateVariable = ContentTemplateVariable; exports.Conversation = Conversation; exports.DetailedDeliveryReceipt = DetailedDeliveryReceipt; exports.Media = Media; exports.Message = Message; exports.MessageBuilder = MessageBuilder; exports.NotificationTypes = NotificationTypes; exports.Participant = Participant; exports.PushNotification = PushNotification; exports.RestPaginator = RestPaginator; exports.UnsentMessage = UnsentMessage; exports.User = User; Object.defineProperty(exports, '__esModule', { value: true }); return exports; })({});