UNPKG

@opentok/client

Version:

The OpenTok.js library lets you use OpenTok-powered video sessions on the web

1,774 lines (1,559 loc) 5.12 MB
/** * @license OpenTok.js 2.30.5 ee13e838e * * Copyright (c) 2010-2025 TokBox, Inc. * Subject to the applicable Software Development Kit (SDK) License Agreement: * https://www.vonage.com/legal/communications-apis/terms-of-use/ * * Date: Mon, 21 Jul 2025 17:56:59 GMT */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["OT"] = factory(); else root["OT"] = factory(); })(window, 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 366); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = _interopRequireDefault; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(0); exports.__esModule = true; exports.default = void 0; var _debug = _interopRequireDefault(__webpack_require__(421)); var _memoize = _interopRequireDefault(__webpack_require__(129)); var _logLevels = _interopRequireDefault(__webpack_require__(130)); /** * @typedef {Object} Logger * @property {Function} error * @property {Function} warn * @property {Function} info * @property {Function} log * @property {Function} debug * @property {Function} spam */ const createLogger = (0, _memoize.default)(namespace => { /** @type Logger */ const API = {}; const setMethods = () => { Object.keys(_logLevels.default).forEach(name => { const method = _logLevels.default[name].method; const log = (0, _debug.default)(`OpenTok:${namespace}:${name.toLowerCase()}`); log.log = console[method].bind(console); // eslint-disable-line no-console API[name.toLowerCase()] = log; }); }; setMethods(); return API; }); createLogger.setLogLevel = level => { let oldRules; try { oldRules = (typeof window !== undefined ? window : global).localStorage.debug; } catch (err) { // will get Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': // The document is sandboxed and lacks the 'allow-same-origin' flag. oldRules = ''; } const newDebugRules = Object.keys(_logLevels.default).map(name => `${level >= _logLevels.default[name].priority ? '' : '-'}(autogen)?OpenTok:*:${name.toLowerCase()}`); const debugStr = [...newDebugRules, ...(oldRules || '').split(/[\s,]/).filter(rule => rule.indexOf('(autogen)?') === -1)].filter(x => x).join(','); _debug.default.enable(debugStr); }; var _default = createLogger; exports.default = _default; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version v4.2.8+1e68dce6 */ (function (global, factory) { true ? module.exports = factory() : undefined; }(this, (function () { 'use strict'; function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } var _isArray = void 0; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; var len = 0; var vertxNext = void 0; var customSchedulerFn = void 0; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var vertx = Function('return this')().require('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = void 0; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { var callback = arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve$1(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(2); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = tryThen(then$$1, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return resolve(promise, value); }, function (reason) { return reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } else { fulfill(promise, maybeThenable); } } } function resolve(promise, value) { if (promise === value) { reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { var then$$1 = void 0; try { then$$1 = value.then; } catch (error) { reject(promise, error); return; } handleMaybeThenable(promise, value, then$$1); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = void 0, callback = void 0, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = void 0, error = void 0, succeeded = true; if (hasCallback) { try { value = callback(detail); } catch (e) { succeeded = false; error = e; } if (promise === value) { reject(promise, cannotReturnOwn()); return; } } else { value = detail; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { resolve(promise, value); } else if (succeeded === false) { reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { resolve(promise, value); }, function rejectPromise(reason) { reject(promise, reason); }); } catch (e) { reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function validationError() { return new Error('Array Methods must be provided an Array'); } var Enumerator = function () { function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationError()); } } Enumerator.prototype._enumerate = function _enumerate(input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { var _then = void 0; var error = void 0; var didError = false; try { _then = entry.then; } catch (e) { didError = true; error = e; } if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise$1) { var promise = new c(noop); if (didError) { reject(promise, error); } else { handleMaybeThenable(promise, entry, _then); } this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator.prototype._settledAt = function _settledAt(state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; return Enumerator; }(); /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject$1(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {Function} resolver Useful for tooling. @constructor */ var Promise$1 = function () { function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ Promise.prototype.catch = function _catch(onRejection) { return this.then(null, onRejection); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @return {Promise} */ Promise.prototype.finally = function _finally(callback) { var promise = this; var constructor = promise.constructor; if (isFunction(callback)) { return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }); } return promise.then(callback, callback); }; return Promise; }(); Promise$1.prototype.then = then; Promise$1.all = all; Promise$1.race = race; Promise$1.resolve = resolve$1; Promise$1.reject = reject$1; Promise$1._setScheduler = setScheduler; Promise$1._setAsap = setAsap; Promise$1._asap = asap; /*global self*/ function polyfill() { var local = void 0; if (typeof (typeof window !== undefined ? window : global) !== 'undefined') { local = (typeof window !== undefined ? window : global); } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise$1; } // Strange compat.. Promise$1.polyfill = polyfill; Promise$1.Promise = Promise$1; return Promise$1; }))); //# sourceMappingURL=es6-promise.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(24))) /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(0); exports.__esModule = true; exports.default = void 0; var _envParser = _interopRequireDefault(__webpack_require__(477)); const env = _envParser.default.parse(); var _default = env; exports.default = _default; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(417); /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Promise) {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; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(2))) /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(0); exports.__esModule = true; exports.default = eventing; var _assign = _interopRequireDefault(__webpack_require__(9)); var _isFunction = _interopRequireDefault(__webpack_require__(20)); var _events = _interopRequireDefault(__webpack_require__(12)); var _log = _interopRequireDefault(__webpack_require__(1)); var _weakMemoizeBind = _interopRequireDefault(__webpack_require__(424)); const logging = (0, _log.default)('Events'); /** * This base class defines the <code>on</code>, <code>once</code>, and <code>off</code> * methods of objects that can dispatch events. * * @class EventDispatcher */ function eventing(self) { const ee = new _events.default(); ee.on('newListener', eventName => { ee.emit(`${eventName}:added`); }); ee.on('removeListener', eventName => { ee.emit(`${eventName}:removed`); }); const eventingMixin = { /** * A map of events already dispatched. */ eventsDispatched: {}, /** * Adds an event handler function for one or more events. * * <p> * The following code adds an event handler for one event: * </p> * * <pre> * obj.on("eventName", function (event) { * // This is the event handler. * }); * </pre> * * <p>If you pass in multiple event names and a handler method, the handler is * registered for each of those events:</p> * * <pre> * obj.on("eventName1 eventName2", * function (event) { * // This is the event handler. * }); * </pre> * * <p>You can also pass in a third <code>context</code> parameter (which is optional) to * define the value of <code>this</code> in the handler method:</p> * * <pre>obj.on("eventName", * function (event) { * // This is the event handler. * }, * obj); * </pre> * * <p> * The method also supports an alternate syntax, in which the first parameter is an object * that is a hash map of event names and handler functions and the second parameter (optional) * is the context for this in each handler: * </p> * <pre> * obj.on( * { * eventName1: function (event) { * // This is the handler for eventName1. * }, * eventName2: function (event) { * // This is the handler for eventName2. * } * }, * obj); * </pre> * * <p> * If you do not add a handler for an event, the event is ignored locally. * </p> * * @param {String} type The string identifying the type of event. You can specify multiple event * names in this string, separating them with a space. The event handler will process each of * the events. * @param {Function} handler The handler function to process the event. This function takes * the event object as a parameter. * @param {Object} context (Optional) Defines the value of <code>this</code> in the event * handler function. * * @returns {EventDispatcher} The EventDispatcher object. * * @memberOf EventDispatcher * @method #on * @see <a href="#off">off()</a> * @see <a href="#once">once()</a> * @see <a href="#events">Events</a> */ on(eventNames, handlerOrContext, context) { if (typeof eventNames === 'string' && handlerOrContext) { eventNames.split(' ').forEach(eventName => { ee.on(eventName, (0, _weakMemoizeBind.default)(handlerOrContext, context)); }); } else { Object.keys(eventNames).forEach(eventName => { ee.on(eventName, (0, _weakMemoizeBind.default)(eventNames[eventName], handlerOrContext)); }); } return this; }, /** * Removes an event handler or handlers. * * <p>If you pass in one event name and a handler method, the handler is removed for that * event:</p> * * <pre>obj.off("eventName", eventHandler);</pre> * * <p>If you pass in multiple event names and a handler method, the handler is removed for * those events:</p> * * <pre>obj.off("eventName1 eventName2", eventHandler);</pre> * * <p>If you pass in an event name (or names) and <i>no</i> handler method, all handlers are * removed for those events:</p> * * <pre>obj.off("event1Name event2Name");</pre> * * <p>If you pass in no arguments, <i>all</i> event handlers are removed for all events * dispatched by the object:</p> * * <pre>obj.off();</pre> * * <p> * The method also supports an alternate syntax, in which the first parameter is an object that * is a hash map of event names and handler functions and the second parameter (optional) is * the context for this in each handler: * </p> * <pre> * obj.off( * { * eventName1: event1Handler, * eventName2: event2Handler * }); * </pre> * * @param {String} type (Optional) The string identifying the type of event. You can * use a space to specify multiple events, as in "accessAllowed accessDenied * accessDialogClosed". If you pass in no <code>type</code> value (or other arguments), * all event handlers are removed for the object. * @param {Function} handler (Optional) The event handler function to remove. The handler * must be the same function object as was passed into <code>on()</code>. Be careful with * helpers like <code>bind()</code> that return a new function when called. If you pass in * no <code>handler</code>, all event handlers are removed for the specified event * <code>type</code>. * @param {Object} context (Optional) If you specify a <code>context</code>, the event handler * is removed for all specified events and handlers that use the specified context. (The * context must match the context passed into <code>on()</code>.) * * @returns {Object} The object that dispatched the event. * * @memberOf EventDispatcher * @method #off * @see <a href="#on">on()</a> * @see <a href="#once">once()</a> * @see <a href="#events">Events</a> */ off(eventNames, handlerOrContext, context) { if (typeof eventNames === 'string') { this.off(eventNames.split(' '), handlerOrContext, context); } else if (Array.isArray(eventNames)) { eventNames.forEach(eventName => { if (handlerOrContext && (0, _isFunction.default)(handlerOrContext)) { ee.removeListener(eventName, (0, _weakMemoizeBind.default)(handlerOrContext, context)); } else { ee.removeAllListeners(eventName); } }); } else if (!eventNames) { ee.removeAllListeners(); } else { Object.keys(eventNames).forEach(eventName => { // @todo was {foo: undefined} expected to remove all foo events? ee.removeListener(eventName, (0, _weakMemoizeBind.default)(eventNames[eventName], handlerOrContext)); }); } return this; }, /** * Adds an event handler function for one or more events. Once the handler is called, * the specified handler method is removed as a handler for this event. (When you use * the <code>on()</code> method to add an event handler, the handler is <i>not</i> * removed when it is called.) The <code>once()</code> method is the equivilent of * calling the <code>on()</code> * method and calling <code>off()</code> the first time the handler is invoked. * * <p> * The following code adds a one-time event handler for one event: * </p> * * <pre> * obj.once("eventName", function (event) { * // This is the event handler. * }); * </pre> * * <p>If you pass in multiple event names and a handler method, the handler is registered * for each of those events:</p> * * <pre>obj.once("eventName1 eventName2" * function (event) { * // This is the event handler. * }); * </pre> * * <p>You can also pass in a third <code>context</code> parameter (which is optional) to define * the value of * <code>this</code> in the handler method:</p> * * <pre>obj.once("eventName", * function (event) { * // This is the event handler. * }, * obj); * </pre> * * <p> * The method also supports an alternate syntax, in which the first parameter is an object that * is a hash map of event names and handler functions and the second parameter (optional) is the * context for this in each handler: * </p> * <pre> * obj.once( * { * eventName1: function (event) { * // This is the event handler for eventName1. * }, * eventName2: function (event) { * // This is the event handler for eventName1. * } * }, * obj); * </pre> * * @param {String} type The string identifying the type of event. You can specify multiple * event names in this string, separating them with a space. The event handler will process * the first occurence of the events. After the first event, the handler is removed (for * all specified events). * @param {Function} handler The handler function to process the event. This function takes * the event object as a parameter. * @param {Object} context (Optional) Defines the value of <code>this</code> in the event * handler function. * * @returns {Object} The object that dispatched the event. * * @memberOf EventDispatcher * @method #once * @see <a href="#on">on()</a> * @see <a href="#off">off()</a> * @see <a href="#events">Events</a> */ once(eventNames, handlerOrContext, context) { if (typeof eventNames === 'string' && handlerOrContext) { eventNames.split(' ').forEach(eventName => { ee.once(eventName, (0, _weakMemoizeBind.default)(handlerOrContext, context)); }); } else { Object.keys(eventNames).forEach(eventName => { ee.once(eventName, (0, _weakMemoizeBind.default)(eventNames[eventName], handlerOrContext)); }); } return this; }, /** * Execute any listeners bound to the +event+ Event. * * Each handler will be executed. * * @param [Event] event An Event object. * @return this */ dispatchEvent(event) { if (!event.type) { throw new Error('dispatchEvent: Event has no type'); } if (!event.target) { event.target = this; // eslint-disable-line no-param-reassign } this.trigger(event.type, event); return this; }, dispatchEventOnce(event, targetId) { if (!this.isEventDispatched(event.type, targetId)) { this.dispatchEvent(event); if (this.eventsDispatched[event.type]) { this.eventsDispatched[event.type].push(targetId); } else { this.eventsDispatched[event.type] = [targetId]; } } }, isEventDispatched(type, targetId) { var _this$eventsDispatche; return (_this$eventsDispatche = this.eventsDispatched[type]) == null ? void 0 : _this$eventsDispatche.includes(targetId); }, /** * Execute each handler for the event called +name+. * * Each handler will be executed, and any exceptions that they throw will * be caught and logged * * @example * foo.on('bar', function(name, message) { * alert("Hello " + name + ": " + message); * }); * * foo.trigger('Vonage Video API', 'asdf'); // -> Hello Vonage Video API: asdf * * @param {String} eventName The name of this event. * @param {Array} arguments The arguments handlers will be called with * * @return this */ trigger(eventName) { try { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } ee.emit(eventName, ...args); } catch (e) { logging.error('An error occurred in an event handler', e); } return this; }, // Alias of trigger for easier node compatibility emit() { return self.trigger(...arguments); }, /** * @deprecated use <a href="#on">on()</a> or <a href="#once">once()</a> instead. * <p> * This method registers a method as an event listener for a specific event. * <p> * * <p> * If a handler is not