UNPKG

twilio-video

Version:

Twilio Video JavaScript Library

1,272 lines (1,201 loc) 1.19 MB
/*! twilio-video.js 2.35.0 The following license applies to all parts of this software except as documented below. Copyright (C) 2019-2026 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. */ (function(root) { var module = { exports: {} }; var exports = module.exports; var __twilio_video = (function () { function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace(n) { if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n; var f = n.default; if (typeof f == "function") { var a = function a () { var isInstance = false; try { isInstance = this instanceof a; } catch {} if (isInstance) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__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 es5$2 = {exports: {}}; var createlocaltracks = {}; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } 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 === "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 __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; } function __runInitializers(thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; } function __propKey(x) { return typeof x === "symbol" ? x : "".concat(x); } function __setFunctionName(f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } function __addDisposableResource(env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { env.stack.push({ async: true }); } return value; } var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; function __disposeResources(env) { function fail(e) { env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } var r, s = 0; function next() { while (r = env.stack.pop()) { try { if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); if (r.dispose) { var result = r.dispose.call(r.value); if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); } else s |= 1; } catch (e) { fail(e); } } if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); } function __rewriteRelativeImportExtension(path, preserveJsx) { if (typeof path === "string" && /^\.\.?\//.test(path)) { return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); }); } return path; } var tslib_es6 = { __extends, __assign, __rest, __decorate, __param, __esDecorate, __runInitializers, __propKey, __setFunctionName, __metadata, __awaiter, __generator, __createBinding, __exportStar, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet, __classPrivateFieldIn, __addDisposableResource, __disposeResources, __rewriteRelativeImportExtension, }; var tslib_es6$1 = /*#__PURE__*/Object.freeze({ __proto__: null, __addDisposableResource: __addDisposableResource, get __assign () { return __assign; }, __asyncDelegator: __asyncDelegator, __asyncGenerator: __asyncGenerator, __asyncValues: __asyncValues, __await: __await, __awaiter: __awaiter, __classPrivateFieldGet: __classPrivateFieldGet, __classPrivateFieldIn: __classPrivateFieldIn, __classPrivateFieldSet: __classPrivateFieldSet, __createBinding: __createBinding, __decorate: __decorate, __disposeResources: __disposeResources, __esDecorate: __esDecorate, __exportStar: __exportStar, __extends: __extends, __generator: __generator, __importDefault: __importDefault, __importStar: __importStar, __makeTemplateObject: __makeTemplateObject, __metadata: __metadata, __param: __param, __propKey: __propKey, __read: __read, __rest: __rest, __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, __runInitializers: __runInitializers, __setFunctionName: __setFunctionName, __spread: __spread, __spreadArray: __spreadArray, __spreadArrays: __spreadArrays, __values: __values, default: tslib_es6 }); var require$$0 = /*@__PURE__*/getAugmentedNamespace(tslib_es6$1); var noisecancellationimpl = {}; var noisecancellationadapter = {}; var dynamicimport; var hasRequiredDynamicimport; function requireDynamicimport () { if (hasRequiredDynamicimport) return dynamicimport; hasRequiredDynamicimport = 1; dynamicimport = (function (scope) { const { location, URL } = scope; if ([location, URL].some(api => !api)) { return function dynamicImportNotSupported(module) { return Promise.reject(new Error(`Failed to import: ${module}: dynamicImport is not supported`)); }; } scope.__twilioVideoImportedModules = { // Imported module map. }; return function dynamicImport(module) { if (module in scope.__twilioVideoImportedModules) { return Promise.resolve(scope.__twilioVideoImportedModules[module]); } // NOTE(mmalavalli): Calling import() directly can cause build issues in TypeScript and Webpack // (and probably other frameworks). So, we create a Function that calls import() in its body. // eslint-disable-next-line no-new-func return new Function('scope', `return import('${new URL(module, location)}').then(m => scope.__twilioVideoImportedModules['${module}'] = m);`)(scope); }; }(globalThis)); return dynamicimport; } /** * Copyright (c) 2013 Tim Perry * Licensed under the MIT license. * * Copied from https://github.com/pimterry/loglevel (1.7.0) * and modified to remove browser and AMD module support, while keeping CommonJS. * It was causing a conflict when this is bundled using CommonJS, and then loaded via RequireJS. * The proper way to fix this module is to have a build that outputs CommonJS and AMD separately * which needs to be submitted to the original module's repo. */ var loglevel; var hasRequiredLoglevel; function requireLoglevel () { if (hasRequiredLoglevel) return loglevel; hasRequiredLoglevel = 1; /* istanbul ignore file */ /* eslint-disable */ // Slightly dubious tricks to cut down minimized file size var noop = function () { }; var undefinedType = "undefined"; var isIE = (typeof window !== undefinedType) && (typeof 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 === 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 !== 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; var storageKey = "loglevel"; if (typeof name === "string") { storageKey += ":" + name; } else if (typeof name === "symbol") { storageKey = undefined; } function persistLevelIfPossible(levelNum) { var levelName = (logMethods[levelNum] || 'silent').toUpperCase(); if (typeof 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 === undefinedType || !storageKey) return; try { storedLevel = window.localStorage[storageKey]; } catch (ignore) { } // Fallback to cookies if local storage gives us nothing if (typeof 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; } /* * * 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 === undefinedType && level < self.levels.SILENT) { return "No console available for logging"; } } else { throw "log.setLevel() called with invalid level: " + level; } }; self.setDefaultLevel = function (level) { if (!getPersistedLevel()) { self.setLevel(level, false); } }; 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 == null ? "WARN" : defaultLevel; } self.setLevel(initialLevel, false); } /* * * Top-level API * */ var defaultLogger = new Logger(); var _loggersByName = {}; defaultLogger.getLogger = function getLogger(name) { if ((typeof 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 !== undefinedType) ? window.log : undefined; defaultLogger.noConflict = function () { if (typeof window !== undefinedType && window.log === defaultLogger) { window.log = _log; } return defaultLogger; }; defaultLogger.getLoggers = function getLoggers() { return _loggersByName; }; // ES6 default export, for compatibility defaultLogger['default'] = defaultLogger; loglevel = defaultLogger; return loglevel; } var constants = {exports: {}}; var name = "twilio-video"; var version = "2.35.0"; var require$$5 = { name: name, version: version}; constants.exports; var hasRequiredConstants; function requireConstants () { if (hasRequiredConstants) return constants.exports; hasRequiredConstants = 1; (function (module) { const packageInfo = require$$5; module.exports.SDK_NAME = `${packageInfo.name}.js`; module.exports.SDK_VERSION = packageInfo.version; module.exports.SDP_FORMAT = 'unified'; module.exports.hardwareDevicePublisheriPad = { hwDeviceManufacturer: 'Apple', hwDeviceModel: 'iPad', hwDeviceType: 'tablet', platformName: 'iOS' }; module.exports.hardwareDevicePublisheriPhone = { hwDeviceManufacturer: 'Apple', hwDeviceModel: 'iPhone', hwDeviceType: 'mobile', platformName: 'iOS' }; module.exports.DEFAULT_ENVIRONMENT = 'prod'; module.exports.DEFAULT_REALM = 'us1'; module.exports.DEFAULT_REGION = 'gll'; module.exports.DEFAULT_LOG_LEVEL = 'warn'; module.exports.DEFAULT_LOGGER_NAME = 'twilio-video'; module.exports.WS_SERVER = (environment, region) => { region = region === 'gll' ? 'global' : encodeURIComponent(region); return environment === 'prod' ? `wss://${region}.vss.twilio.com/signaling` : `wss://${region}.vss.${environment}.twilio.com/signaling`; }; module.exports.PUBLISH_MAX_ATTEMPTS = 5; module.exports.PUBLISH_BACKOFF_JITTER = 10; module.exports.PUBLISH_BACKOFF_MS = 20; /** * Returns the appropriate indefinite article ("a" | "an"). * @param {string} word - The word which determines whether "a" | "an" is returned * @returns {string} "a" if word's first letter is a vowel, "an" otherwise */ function article(word) { // NOTE(mmalavalli): This will not be accurate for words like "hour", // which have consonants as their first character, but are pronounced like // vowels. We can address this issue if the need arises. return ['a', 'e', 'i', 'o', 'u'].includes(word.toLowerCase()[0]) ? 'an' : 'a'; } module.exports.typeErrors = { ILLEGAL_INVOKE(name, context) { return new TypeError(`Illegal call to ${name}: ${context}`); }, INVALID_TYPE(name, type) { return new TypeError(`${name} must be ${article(type)} ${type}`); }, INVALID_VALUE(name, values) { return new RangeError(`${name} must be one of ${values.join(', ')}`); }, REQUIRED_ARGUMENT(name) { return new TypeError(`${name} must be specified`); } }; module.exports.DEFAULT_FRAME_RATE = 24; module.exports.DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS = 10000; module.exports.DEFAULT_ICE_GATHERING_TIMEOUT_MS = 15000; module.exports.DEFAULT_SESSION_TIMEOUT_SEC = 30; module.exports.DEFAULT_NQ_LEVEL_LOCAL = 1; module.exports.DEFAULT_NQ_LEVEL_REMOTE = 0; module.exports.MAX_NQ_LEVEL = 3; module.exports.ICE_ACTIVITY_CHECK_PERIOD_MS = 1000; module.exports.ICE_INACTIVITY_THRESHOLD_MS = 3000; module.exports.iceRestartBackoffConfig = { factor: 1.1, min: 1, max: module.exports.DEFAULT_SESSION_TIMEOUT_SEC * 1000, jitter: 1 }; module.exports.reconnectBackoffConfig = { factor: 1.5, min: 80, jitter: 1 }; module.exports.subscriptionMode = { MODE_COLLABORATION: 'collaboration', MODE_GRID: 'grid', MODE_PRESENTATION: 'presentation' }; module.exports.trackSwitchOffMode = { MODE_DISABLED: 'disabled', MODE_DETECTED: 'detected', MODE_PREDICTED: 'predicted' }; module.exports.trackPriority = { PRIORITY_HIGH: 'high', PRIORITY_LOW: 'low', PRIORITY_STANDARD: 'standard' }; module.exports.clientTrackSwitchOffControl = { MODE_AUTO: 'auto', MODE_MANUAL: 'manual' }; module.exports.videoContentPreferencesMode = { MODE_AUTO: 'auto', MODE_MANUAL: 'manual' }; } (constants)); return constants.exports; } /* eslint new-cap:0 */ var log; var hasRequiredLog; function requireLog () { if (hasRequiredLog) return log; hasRequiredLog = 1; const defaultGetLogger = requireLoglevel().getLogger; const constants = requireConstants(); const { DEFAULT_LOG_LEVEL, DEFAULT_LOGGER_NAME } = constants; const E = requireConstants().typeErrors; let deprecationWarningsByComponentConstructor; function getDeprecationWarnings(componentConstructor) { deprecationWarningsByComponentConstructor = deprecationWarningsByComponentConstructor || new Map(); if (deprecationWarningsByComponentConstructor.has(componentConstructor)) { return deprecationWarningsByComponentConstructor.get(componentConstructor); } const deprecationWarnings = new Set(); deprecationWarningsByComponentConstructor.set(componentConstructor, deprecationWarnings); return deprecationWarnings; } /** * Selectively outputs messages to console based on specified minimum module * specific log levels. * * NOTE: The values in the logLevels object passed to the constructor is changed * by subsequent calls to {@link Log#setLevels}. */ class Log { /** * Construct a new {@link Log} object. * @param {String} moduleName - Name of the logging module (webrtc/media/signaling) * @param {object} component - Component owning this instance of {@link Log} * @param {LogLevels} logLevels - Logging levels. See {@link LogLevels} * @param {String} loggerName - Name of the logger instance. Used when calling getLogger from loglevel module * @param {Function} [getLogger] - optional method used internally. */ constructor(moduleName, component, logLevels, loggerName, getLogger) { if (typeof moduleName !== 'string') { throw E.INVALID_TYPE('moduleName', 'string'); } if (!component) { throw E.REQUIRED_ARGUMENT('component'); } if (typeof logLevels !== 'object') { logLevels = {}; } getLogger = getLogger || defaultGetLogger; validateLogLevels(logLevels); /* istanbul ignore next */ Object.defineProperties(this, { _component: { value: component }, _logLevels: { value: logLevels }, _warnings: { value: new Set() }, _loggerName: { get: function get() { let name = loggerName && typeof loggerName === 'string' ? loggerName : DEFAULT_LOGGER_NAME; if (!this._logLevelsEqual) { name = `${name}-${moduleName}`; } return name; } }, _logger: { get: function get() { const logger = getLogger(this._loggerName); let level = this._logLevels[moduleName] || DEFAULT_LOG_LEVEL; // There is no 'off' in the logger module. It uses 'silent' instead level = level === 'off' ? 'silent' : level; logger.setDefaultLevel(level); return logger; } }, _logLevelsEqual: { get: function get() { // True if all levels are the same return (new Set(Object.values(this._logLevels)).size) === 1; } }, logLevel: { get: function get() { return Log.getLevelByName(logLevels[moduleName] || DEFAULT_LOG_LEVEL); } }, name: { get: component.toString.bind(component) } }); } /** * Get the log level (number) by its name (string) * @param {String} name - Name of the log level * @returns {Number} Requested log level * @throws {TwilioError} INVALID_LOG_LEVEL (32056) * @public */ static getLevelByName(name) { if (!isNaN(name)) { return parseInt(name, 10); } name = name.toUpperCase(); validateLogLevel(name); return Log[name]; } /** * Create a child {@link Log} instance with this._logLevels * @param moduleName - Name of the logging module * @param component - Component owning this instance of {@link Log} * @returns {Log} this */ createLog(moduleName, component) { let name = this._loggerName; // Grab the original logger name if (!this._logLevelsEqual) { name = name.substring(0, name.lastIndexOf('-')); } return new Log(moduleName, component, this._logLevels, name); } /** * Set new log levels. * This changes the levels for all its ancestors, * siblings, and children and descendants instances of {@link Log}. * @param {LogLevels} levels - New log levels * @throws {TwilioError} INVALID_ARGUMENT * @returns {Log} this */ setLevels(levels) { validateLogLevels(levels); Object.assign(this._logLevels, levels); return this; } /** * Log a message using the logger method appropriate for the specified logLevel * @param {Number} logLevel - Log level of the message being logged * @param {Array} messages - Message(s) to log * @returns {Log} This instance of {@link Log} * @public */ log(logLevel, messages) { let name = Log._levels[logLevel]; // eslint-disable-next-line no-use-before-define if (!name) { throw E.INVALID_VALUE('logLevel', LOG_LEVEL_VALUES); } name = name.toLowerCase(); const prefix = [new Date().toISOString(), name, this.name]; (this._logger[name] || function noop() { })(...prefix.concat(messages)); return this; } /** * Log a debug message * @param {...String} messages - Message(s) to pass to the logger * @returns {Log} This instance of {@link Log} * @public */ debug() { return this.log(Log.DEBUG, [].slice.call(arguments)); } /** * Log a deprecation warning. Deprecation warnings are logged as warnings and * they are only ever logged once. * @param {String} deprecationWarning - The deprecation warning * @returns {Log} This instance of {@link Log} * @public */ deprecated(deprecationWarning) { const deprecationWarnings = getDeprecationWarnings(this._component.constructor); if (deprecationWarnings.has(deprecationWarning)) { return this; } deprecationWarnings.add(deprecationWarning); return this.warn(deprecationWarning); } /** * Log an info message * @param {...String} messages - Message(s) to pass to the logger * @returns {Log} This instance of {@link Log} * @public */ info() { return this.log(Log.INFO, [].slice.call(arguments)); } /** * Log a warn message * @param {...String} messages - Message(s) to pass to the logger * @returns {Log} This instance of {@link Log} * @public */ warn() { return this.log(Log.WARN, [].slice.call(arguments)); } /** * Log a warning once. * @param {String} warning * @returns {Log} This instance of {@link Log} * @public */ warnOnce(warning) { if (this._warnings.has(warning)) { return this; } this._warnings.add(warning); return this.warn(warning); } /** * Log an error message * @param {...String} messages - Message(s) to pass to the logger * @returns {Log} This instance of {@link Log} * @public */ error() { return this.log(Log.ERROR, [].slice.call(arguments)); } /** * Log an error message and throw an exception * @param {TwilioError} error - Error to throw * @param {String} customMessage - Custom message for the error * @public */ throw(error, customMessage) { if (error.clone) { error = error.clone(customMessage); } this.log(Log.ERROR, error); throw error; } } // Singleton Constants /* eslint key-spacing:0 */ /* istanbul ignore next */ Object.defineProperties(Log, { DEBUG: { value: 0 }, INFO: { value: 1 }, WARN: { value: 2 }, ERROR: { value: 3 }, OFF: { value: 4 }, _levels: { value: [ 'DEBUG', 'INFO', 'WARN', 'ERROR', 'OFF', ] } }); const LOG_LEVELS_SET = {}; const LOG_LEVEL_VALUES = []; const LOG_LEVEL_NAMES = Log._levels.map((level, i) => { LOG_LEVELS_SET[level] = true; LOG_LEVEL_VALUES.push(i); return level; }); function validateLogLevel(level) { if (!(level in LOG_LEVELS_SET)) { throw E.INVALID_VALUE('level', LOG_LEVEL_NAMES); } } function validateLogLevels(levels) { Object.keys(levels).forEach(moduleName => { validateLogLevel(levels[moduleName].toUpperCase()); }); } log = Log; return log; } var hasRequiredNoisecancellationadapter; function requireNoisecancellationadapter () { if (hasRequiredNoisecancellationadapter) return noisecancellationadapter; hasRequiredNoisecancellationadapter = 1; Object.defineProperty(noisecancellationadapter, "__esModule", { value: true }); noisecancellationadapter.createNoiseCancellationAudioProcessor = createNoiseCancellationAudioProcessor; const tslib_1 = require$$0; const dynamicImport = requireDynamicimport(); requireLog(); const PLUGIN_CONFIG = { krisp: { supportedVersion: '1.0.0', pluginFile: 'krispsdk.mjs' }, rnnoise: { supportedVersion: '0.6.0', pluginFile: 'rnnoise_sdk.mjs' } }; const ensureVersionSupported = ({ supportedVersion, plugin, log }) => { if (!plugin.getVersion || !plugin.isSupported) { throw new Error('Plugin does not export getVersion/isSupported api. Are you using old version of the plugin ?'); } const pluginVersion = plugin.getVersion(); log.debug(`Plugin Version = ${pluginVersion}`); const supportedVersions = supportedVersion.split('.').map(version => Number(version)); const pluginVersions = pluginVersion.split('.').map(version => Number(version)); if (supportedVersions.length !== 3 || pluginVersions.length !== 3) { throw new Error(`Unsupported Plugin version format: ${supportedVersion}, ${pluginVersion}`); } if (supportedVersions[0] !== pluginVersions[0]) { throw new Error(`Major version mismatch: [Plugin version ${pluginVersion}], [Supported Version ${supportedVersion}]`); } if (pluginVersions[1] < supportedVersions[1]) { throw new Error(`Minor version mismatch: [Plugin version ${pluginVersion}] < [Supported Version ${supportedVersion}]`); } const tempContext = new AudioContext(); const isSupported = plugin.isSupported(tempContext); tempContext.close(); if (!isSupported) { throw new Error('Noise Cancellation plugin is not supported on your browser'); } }; let audioProcessors = new Map(); function createNoiseCancellationAudioProcessor(noiseCancellationOptions, log) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let audioProcessor = audioProcessors.get(noiseCancellationOptions.vendor); if (!audioProcessor) { let pluginConfig = PLUGIN_CONFIG[noiseCancellationOptions.vendor]; if (!pluginConfig) { throw new Error(`Unsupported NoiseCancellationOptions.vendor: ${noiseCancellationOptions.vendor}`); } const { supportedVersion, pluginFile } = pluginConfig; const rootDir = noiseCancellationOptions.sdkAssetsPath; const sdkFilePath = `${rootDir}/${pluginFile}`; try { log.debug('loading noise cancellation sdk: ', sdkFilePath); const dynamicModule = yield dynamicImport(sdkFilePath); log.debug('Loaded noise cancellation sdk:', dynamicModule); const plugin = dynamicModule.default; ensureVersionSupported({ supportedVersion, plugin, log }); if (!plugin.isInitialized()) { log.debug('initializing noise cancellation sdk: ', rootDir); yield plugin.init({ rootDir }); log.debug('noise cancellation sdk initialized!'); } audioProcessor = { vendor: noiseCancellationOptions.vendor, isInitialized: () => plugin.isInitialized(), isConnected: () => plugin.isConnected(), isEnabled: () => plugin.isEnabled(), disconnect: () => plugin.disconnect(), enable: () => plugin.enable(), disable: () => plugin.disable(), destroy: () => plugin.destroy(), setLogging: (enabl