@reactoo/watchtogether-sdk-js 2.7.15 → 2.7.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/watchtogether-sdk.js +167 -167
- package/dist/watchtogether-sdk.min.js +2 -2
- package/example/index.html +4 -4
- package/package.json +2 -2
- package/src/modules/wt-room.js +1 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
2
|
* @reactoo/watchtogether-sdk-js
|
|
3
|
-
* @version 2.7.
|
|
3
|
+
* @version 2.7.16
|
|
4
4
|
*/
|
|
5
5
|
(function webpackUniversalModuleDefinition(root, factory) {
|
|
6
6
|
if(typeof exports === 'object' && typeof module === 'object')
|
|
@@ -540,6 +540,157 @@ eval("// TODO(Babel 8): Remove this file.\n\nvar runtime = __webpack_require__(/
|
|
|
540
540
|
|
|
541
541
|
/***/ }),
|
|
542
542
|
|
|
543
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/duplexify/index.js":
|
|
544
|
+
/*!************************************************************************************!*\
|
|
545
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/duplexify/index.js ***!
|
|
546
|
+
\************************************************************************************/
|
|
547
|
+
/*! no static exports found */
|
|
548
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
549
|
+
|
|
550
|
+
eval("/* WEBPACK VAR INJECTION */(function(Buffer, process) {var stream = __webpack_require__(/*! readable-stream */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/readable-browser.js\");\nvar eos = __webpack_require__(/*! end-of-stream */ \"./node_modules/end-of-stream/index.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar shift = __webpack_require__(/*! stream-shift */ \"./node_modules/stream-shift/index.js\");\nvar SIGNAL_FLUSH = Buffer.from && Buffer.from !== Uint8Array.from ? Buffer.from([0]) : new Buffer([0]);\nvar onuncork = function (self, fn) {\n if (self._corked) self.once('uncork', fn);else fn();\n};\nvar autoDestroy = function (self, err) {\n if (self._autoDestroy) self.destroy(err);\n};\nvar destroyer = function (self, end) {\n return function (err) {\n if (err) autoDestroy(self, err.message === 'premature close' ? null : err);else if (end && !self._ended) self.end();\n };\n};\nvar end = function (ws, fn) {\n if (!ws) return fn();\n if (ws._writableState && ws._writableState.finished) return fn();\n if (ws._writableState) return ws.end(fn);\n ws.end();\n fn();\n};\nvar toStreams2 = function (rs) {\n return new stream.Readable({\n objectMode: true,\n highWaterMark: 16\n }).wrap(rs);\n};\nvar Duplexify = function (writable, readable, opts) {\n if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts);\n stream.Duplex.call(this, opts);\n this._writable = null;\n this._readable = null;\n this._readable2 = null;\n this._autoDestroy = !opts || opts.autoDestroy !== false;\n this._forwardDestroy = !opts || opts.destroy !== false;\n this._forwardEnd = !opts || opts.end !== false;\n this._corked = 1; // start corked\n this._ondrain = null;\n this._drained = false;\n this._forwarding = false;\n this._unwrite = null;\n this._unread = null;\n this._ended = false;\n this.destroyed = false;\n if (writable) this.setWritable(writable);\n if (readable) this.setReadable(readable);\n};\ninherits(Duplexify, stream.Duplex);\nDuplexify.obj = function (writable, readable, opts) {\n if (!opts) opts = {};\n opts.objectMode = true;\n opts.highWaterMark = 16;\n return new Duplexify(writable, readable, opts);\n};\nDuplexify.prototype.cork = function () {\n if (++this._corked === 1) this.emit('cork');\n};\nDuplexify.prototype.uncork = function () {\n if (this._corked && --this._corked === 0) this.emit('uncork');\n};\nDuplexify.prototype.setWritable = function (writable) {\n if (this._unwrite) this._unwrite();\n if (this.destroyed) {\n if (writable && writable.destroy) writable.destroy();\n return;\n }\n if (writable === null || writable === false) {\n this.end();\n return;\n }\n var self = this;\n var unend = eos(writable, {\n writable: true,\n readable: false\n }, destroyer(this, this._forwardEnd));\n var ondrain = function () {\n var ondrain = self._ondrain;\n self._ondrain = null;\n if (ondrain) ondrain();\n };\n var clear = function () {\n self._writable.removeListener('drain', ondrain);\n unend();\n };\n if (this._unwrite) process.nextTick(ondrain); // force a drain on stream reset to avoid livelocks\n\n this._writable = writable;\n this._writable.on('drain', ondrain);\n this._unwrite = clear;\n this.uncork(); // always uncork setWritable\n};\nDuplexify.prototype.setReadable = function (readable) {\n if (this._unread) this._unread();\n if (this.destroyed) {\n if (readable && readable.destroy) readable.destroy();\n return;\n }\n if (readable === null || readable === false) {\n this.push(null);\n this.resume();\n return;\n }\n var self = this;\n var unend = eos(readable, {\n writable: false,\n readable: true\n }, destroyer(this));\n var onreadable = function () {\n self._forward();\n };\n var onend = function () {\n self.push(null);\n };\n var clear = function () {\n self._readable2.removeListener('readable', onreadable);\n self._readable2.removeListener('end', onend);\n unend();\n };\n this._drained = true;\n this._readable = readable;\n this._readable2 = readable._readableState ? readable : toStreams2(readable);\n this._readable2.on('readable', onreadable);\n this._readable2.on('end', onend);\n this._unread = clear;\n this._forward();\n};\nDuplexify.prototype._read = function () {\n this._drained = true;\n this._forward();\n};\nDuplexify.prototype._forward = function () {\n if (this._forwarding || !this._readable2 || !this._drained) return;\n this._forwarding = true;\n var data;\n while (this._drained && (data = shift(this._readable2)) !== null) {\n if (this.destroyed) continue;\n this._drained = this.push(data);\n }\n this._forwarding = false;\n};\nDuplexify.prototype.destroy = function (err) {\n if (this.destroyed) return;\n this.destroyed = true;\n var self = this;\n process.nextTick(function () {\n self._destroy(err);\n });\n};\nDuplexify.prototype._destroy = function (err) {\n if (err) {\n var ondrain = this._ondrain;\n this._ondrain = null;\n if (ondrain) ondrain(err);else this.emit('error', err);\n }\n if (this._forwardDestroy) {\n if (this._readable && this._readable.destroy) this._readable.destroy();\n if (this._writable && this._writable.destroy) this._writable.destroy();\n }\n this.emit('close');\n};\nDuplexify.prototype._write = function (data, enc, cb) {\n if (this.destroyed) return cb();\n if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb));\n if (data === SIGNAL_FLUSH) return this._finish(cb);\n if (!this._writable) return cb();\n if (this._writable.write(data) === false) this._ondrain = cb;else cb();\n};\nDuplexify.prototype._finish = function (cb) {\n var self = this;\n this.emit('preend');\n onuncork(this, function () {\n end(self._forwardEnd && self._writable, function () {\n // haxx to not emit prefinish twice\n if (self._writableState.prefinished === false) self._writableState.prefinished = true;\n self.emit('prefinish');\n onuncork(self, cb);\n });\n });\n};\nDuplexify.prototype.end = function (data, enc, cb) {\n if (typeof data === 'function') return this.end(null, null, data);\n if (typeof enc === 'function') return this.end(data, null, enc);\n this._ended = true;\n if (data) this.write(data);\n if (!this._writableState.ending) this.write(SIGNAL_FLUSH);\n return stream.Writable.prototype.end.call(this, cb);\n};\nmodule.exports = Duplexify;\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node-libs-browser/node_modules/buffer/index.js */ \"./node_modules/node-libs-browser/node_modules/buffer/index.js\").Buffer, __webpack_require__(/*! ./../../../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/duplexify/index.js?");
|
|
551
|
+
|
|
552
|
+
/***/ }),
|
|
553
|
+
|
|
554
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/isarray/index.js":
|
|
555
|
+
/*!**********************************************************************************!*\
|
|
556
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/isarray/index.js ***!
|
|
557
|
+
\**********************************************************************************/
|
|
558
|
+
/*! no static exports found */
|
|
559
|
+
/***/ (function(module, exports) {
|
|
560
|
+
|
|
561
|
+
eval("var toString = {}.toString;\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/isarray/index.js?");
|
|
562
|
+
|
|
563
|
+
/***/ }),
|
|
564
|
+
|
|
565
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js":
|
|
566
|
+
/*!*******************************************************************************************************!*\
|
|
567
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js ***!
|
|
568
|
+
\*******************************************************************************************************/
|
|
569
|
+
/*! no static exports found */
|
|
570
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
571
|
+
|
|
572
|
+
"use strict";
|
|
573
|
+
eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }\n return keys;\n};\n/*</replacement>*/\n\nmodule.exports = Duplex;\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\nvar Readable = __webpack_require__(/*! ./_stream_readable */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js\");\nvar Writable = __webpack_require__(/*! ./_stream_writable */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js\");\nutil.inherits(Duplex, Readable);\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n if (options && options.readable === false) this.readable = false;\n if (options && options.writable === false) this.writable = false;\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n this.once('end', onend);\n}\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\nfunction onEndNT(self) {\n self.end();\n}\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n pna.nextTick(cb, err);\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js?");
|
|
574
|
+
|
|
575
|
+
/***/ }),
|
|
576
|
+
|
|
577
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js":
|
|
578
|
+
/*!************************************************************************************************************!*\
|
|
579
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js ***!
|
|
580
|
+
\************************************************************************************************************/
|
|
581
|
+
/*! no static exports found */
|
|
582
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
583
|
+
|
|
584
|
+
"use strict";
|
|
585
|
+
eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n\n\nmodule.exports = PassThrough;\nvar Transform = __webpack_require__(/*! ./_stream_transform */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js\");\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\nutil.inherits(PassThrough, Transform);\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js?");
|
|
586
|
+
|
|
587
|
+
/***/ }),
|
|
588
|
+
|
|
589
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js":
|
|
590
|
+
/*!*********************************************************************************************************!*\
|
|
591
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js ***!
|
|
592
|
+
\*********************************************************************************************************/
|
|
593
|
+
/*! no static exports found */
|
|
594
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
595
|
+
|
|
596
|
+
"use strict";
|
|
597
|
+
eval("/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\nmodule.exports = Readable;\n\n/*<replacement>*/\nvar isArray = __webpack_require__(/*! isarray */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/isarray/index.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n\n/*<replacement>*/\nvar EE = __webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter;\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar debugUtil = __webpack_require__(/*! util */ 6);\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/*</replacement>*/\n\nvar BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js\");\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js\");\nvar StringDecoder;\nutil.inherits(Readable, Stream);\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\nfunction ReadableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ \"./node_modules/node-libs-browser/node_modules/string_decoder/lib/string_decoder.js\").StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\nfunction Readable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n if (!(this instanceof Readable)) return new Readable(options);\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n Stream.call(this);\n}\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n return needMoreData(state);\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ \"./node_modules/node-libs-browser/node_modules/string_decoder/lib/string_decoder.js\").StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n return dest;\n};\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n return this;\n};\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\"), __webpack_require__(/*! ./../../../../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js?");
|
|
598
|
+
|
|
599
|
+
/***/ }),
|
|
600
|
+
|
|
601
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js":
|
|
602
|
+
/*!**********************************************************************************************************!*\
|
|
603
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js ***!
|
|
604
|
+
\**********************************************************************************************************/
|
|
605
|
+
/*! no static exports found */
|
|
606
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
607
|
+
|
|
608
|
+
"use strict";
|
|
609
|
+
eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n\n\nmodule.exports = Transform;\nvar Duplex = __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\nutil.inherits(Transform, Duplex);\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null)\n // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\nfunction prefinish() {\n var _this = this;\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null)\n // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n return stream.push(null);\n}\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js?");
|
|
610
|
+
|
|
611
|
+
/***/ }),
|
|
612
|
+
|
|
613
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js":
|
|
614
|
+
/*!*********************************************************************************************************!*\
|
|
615
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js ***!
|
|
616
|
+
\*********************************************************************************************************/
|
|
617
|
+
/*! no static exports found */
|
|
618
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
619
|
+
|
|
620
|
+
"use strict";
|
|
621
|
+
eval("/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\nmodule.exports = Writable;\n\n/* <replacement> */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar internalUtil = {\n deprecate: __webpack_require__(/*! util-deprecate */ \"./node_modules/util-deprecate/browser.js\")\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js\");\nutil.inherits(Writable, Stream);\nfunction nop() {}\nfunction WritableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\nfunction Writable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\nWritable.prototype.cork = function () {\n var state = this._writableState;\n state.corked++;\n};\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n return ret;\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n if (sync) {\n /*<replacement>*/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /*</replacement>*/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n if (entry === null) state.lastBufferedRequest = null;\n }\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\nWritable.prototype._writev = null;\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n};\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../process/browser.js */ \"./node_modules/process/browser.js\"), __webpack_require__(/*! ./../../../../../timers-browserify/main.js */ \"./node_modules/timers-browserify/main.js\").setImmediate, __webpack_require__(/*! ./../../../../../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js?");
|
|
622
|
+
|
|
623
|
+
/***/ }),
|
|
624
|
+
|
|
625
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js":
|
|
626
|
+
/*!********************************************************************************************************************!*\
|
|
627
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js ***!
|
|
628
|
+
\********************************************************************************************************************/
|
|
629
|
+
/*! no static exports found */
|
|
630
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
631
|
+
|
|
632
|
+
"use strict";
|
|
633
|
+
eval("\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nvar util = __webpack_require__(/*! util */ 7);\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n BufferList.prototype.push = function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n BufferList.prototype.unshift = function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }\n return ret;\n };\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n return BufferList;\n}();\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({\n length: this.length\n });\n return this.constructor.name + ' ' + obj;\n };\n}\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js?");
|
|
634
|
+
|
|
635
|
+
/***/ }),
|
|
636
|
+
|
|
637
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js":
|
|
638
|
+
/*!*****************************************************************************************************************!*\
|
|
639
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js ***!
|
|
640
|
+
\*****************************************************************************************************************/
|
|
641
|
+
/*! no static exports found */
|
|
642
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
643
|
+
|
|
644
|
+
"use strict";
|
|
645
|
+
eval("\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n pna.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, this, err);\n }\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n pna.nextTick(emitErrorNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, _this, err);\n }\n } else if (cb) {\n cb(err);\n }\n });\n return this;\n}\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js?");
|
|
646
|
+
|
|
647
|
+
/***/ }),
|
|
648
|
+
|
|
649
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js":
|
|
650
|
+
/*!************************************************************************************************************************!*\
|
|
651
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js ***!
|
|
652
|
+
\************************************************************************************************************************/
|
|
653
|
+
/*! no static exports found */
|
|
654
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
655
|
+
|
|
656
|
+
eval("module.exports = __webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter;\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js?");
|
|
657
|
+
|
|
658
|
+
/***/ }),
|
|
659
|
+
|
|
660
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/readable-browser.js":
|
|
661
|
+
/*!*****************************************************************************************************!*\
|
|
662
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/readable-browser.js ***!
|
|
663
|
+
\*****************************************************************************************************/
|
|
664
|
+
/*! no static exports found */
|
|
665
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
666
|
+
|
|
667
|
+
eval("exports = module.exports = __webpack_require__(/*! ./lib/_stream_readable.js */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js\");\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = __webpack_require__(/*! ./lib/_stream_writable.js */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js\");\nexports.Duplex = __webpack_require__(/*! ./lib/_stream_duplex.js */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\nexports.Transform = __webpack_require__(/*! ./lib/_stream_transform.js */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js\");\nexports.PassThrough = __webpack_require__(/*! ./lib/_stream_passthrough.js */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js\");\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/readable-browser.js?");
|
|
668
|
+
|
|
669
|
+
/***/ }),
|
|
670
|
+
|
|
671
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/node_modules/safe-buffer/index.js":
|
|
672
|
+
/*!**************************************************************************************!*\
|
|
673
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/node_modules/safe-buffer/index.js ***!
|
|
674
|
+
\**************************************************************************************/
|
|
675
|
+
/*! no static exports found */
|
|
676
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
677
|
+
|
|
678
|
+
eval("/* eslint-disable node/no-deprecated-api */\nvar buffer = __webpack_require__(/*! buffer */ \"./node_modules/node-libs-browser/node_modules/buffer/index.js\");\nvar Buffer = buffer.Buffer;\n\n// alternative to using Object.keys for old browsers\nfunction copyProps(src, dst) {\n for (var key in src) {\n dst[key] = src[key];\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer;\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports);\n exports.Buffer = SafeBuffer;\n}\nfunction SafeBuffer(arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length);\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer);\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number');\n }\n return Buffer(arg, encodingOrOffset, length);\n};\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number');\n }\n var buf = Buffer(size);\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding);\n } else {\n buf.fill(fill);\n }\n } else {\n buf.fill(0);\n }\n return buf;\n};\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number');\n }\n return Buffer(size);\n};\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number');\n }\n return buffer.SlowBuffer(size);\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/node_modules/safe-buffer/index.js?");
|
|
679
|
+
|
|
680
|
+
/***/ }),
|
|
681
|
+
|
|
682
|
+
/***/ "./node_modules/@httptoolkit/websocket-stream/stream.js":
|
|
683
|
+
/*!**************************************************************!*\
|
|
684
|
+
!*** ./node_modules/@httptoolkit/websocket-stream/stream.js ***!
|
|
685
|
+
\**************************************************************/
|
|
686
|
+
/*! no static exports found */
|
|
687
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
688
|
+
|
|
689
|
+
"use strict";
|
|
690
|
+
eval("/* WEBPACK VAR INJECTION */(function(process, global) {\n\nvar Transform = __webpack_require__(/*! readable-stream */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/readable-stream/readable-browser.js\").Transform;\nvar duplexify = __webpack_require__(/*! duplexify */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/duplexify/index.js\");\nvar WS = __webpack_require__(/*! isomorphic-ws */ \"./node_modules/isomorphic-ws/browser.js\");\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/@httptoolkit/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nmodule.exports = WebSocketStream;\nfunction buildProxy(options, socketWrite, socketEnd) {\n var proxy = new Transform({\n objectMode: options.objectMode\n });\n proxy._write = socketWrite;\n proxy._flush = socketEnd;\n return proxy;\n}\nfunction WebSocketStream(target, protocols, options) {\n var stream, socket;\n var isBrowser = process.title === 'browser';\n var isNative = !!global.WebSocket;\n var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode;\n if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {\n // accept the \"options\" Object as the 2nd argument\n options = protocols;\n protocols = undefined;\n if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {\n protocols = options.protocol;\n }\n }\n if (!options) options = {};\n if (options.objectMode === undefined) {\n options.objectMode = !(options.binary === true || options.binary === undefined);\n }\n var proxy = buildProxy(options, socketWrite, socketEnd);\n if (!options.objectMode) {\n proxy._writev = writev;\n }\n\n // browser only: sets the maximum socket buffer size before throttling\n var bufferSize = options.browserBufferSize || 1024 * 512;\n\n // browser only: how long to wait when throttling\n var bufferTimeout = options.browserBufferTimeout || 1000;\n\n // use existing WebSocket object that was passed in\n if (typeof target === 'object') {\n socket = target;\n // otherwise make a new one\n } else {\n // special constructor treatment for native websockets in browsers, see\n // https://github.com/maxogden/websocket-stream/issues/82\n if (isNative && isBrowser) {\n socket = new WS(target, protocols);\n } else {\n socket = new WS(target, protocols, options);\n }\n socket.binaryType = 'arraybuffer';\n }\n\n // according to https://github.com/baygeldin/ws-streamify/issues/1\n // Nodejs WebSocketServer cause memory leak\n // Handlers like onerror, onclose, onmessage and onopen are accessible via setter/getter\n // And setter first of all fires removeAllListeners, that doesnt make inner array of clients on WebSocketServer cleared ever\n var eventListenerSupport = 'undefined' === typeof socket.addEventListener;\n\n // was already open when passed in\n if (socket.readyState === socket.OPEN) {\n stream = proxy;\n } else {\n stream = duplexify(undefined, undefined, options);\n if (!options.objectMode) {\n stream._writev = writev;\n }\n if (eventListenerSupport) {\n socket.addEventListener('open', onopen);\n } else {\n socket.onopen = onopen;\n }\n }\n stream.socket = socket;\n if (eventListenerSupport) {\n socket.addEventListener('close', onclose);\n socket.addEventListener('error', onerror);\n socket.addEventListener('message', onmessage);\n } else {\n socket.onclose = onclose;\n socket.onerror = onerror;\n socket.onmessage = onmessage;\n }\n proxy.on('close', destroy);\n var coerceToBuffer = !options.objectMode;\n function socketWriteNode(chunk, enc, next) {\n // avoid errors, this never happens unless\n // destroy() is called\n if (socket.readyState !== socket.OPEN) {\n next();\n return;\n }\n if (coerceToBuffer && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, 'utf8');\n }\n socket.send(chunk, next);\n }\n function socketWriteBrowser(chunk, enc, next) {\n if (socket.bufferedAmount > bufferSize) {\n setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next);\n return;\n }\n if (coerceToBuffer && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, 'utf8');\n }\n try {\n socket.send(chunk);\n } catch (err) {\n return next(err);\n }\n next();\n }\n function socketEnd(done) {\n socket.close();\n done();\n }\n function onopen() {\n stream.setReadable(proxy);\n stream.setWritable(proxy);\n stream.emit('connect');\n }\n function onclose(closeDetails) {\n stream.emit('ws-close', closeDetails);\n stream.end();\n stream.destroy();\n }\n function onerror(err) {\n stream.destroy(err);\n }\n function onmessage(event) {\n var data = event.data;\n if (data instanceof ArrayBuffer) data = Buffer.from(data);else data = Buffer.from(data, 'utf8');\n proxy.push(data);\n }\n function destroy() {\n socket.close();\n }\n\n // this is to be enabled only if objectMode is false\n function writev(chunks, cb) {\n var buffers = new Array(chunks.length);\n for (var i = 0; i < chunks.length; i++) {\n if (typeof chunks[i].chunk === 'string') {\n buffers[i] = Buffer.from(chunks[i], 'utf8');\n } else {\n buffers[i] = chunks[i].chunk;\n }\n }\n this._write(Buffer.concat(buffers), 'binary', cb);\n }\n return stream;\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ \"./node_modules/process/browser.js\"), __webpack_require__(/*! ./../../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/@httptoolkit/websocket-stream/stream.js?");
|
|
691
|
+
|
|
692
|
+
/***/ }),
|
|
693
|
+
|
|
543
694
|
/***/ "./node_modules/array-buffer-byte-length/index.js":
|
|
544
695
|
/*!********************************************************!*\
|
|
545
696
|
!*** ./node_modules/array-buffer-byte-length/index.js ***!
|
|
@@ -604,7 +755,7 @@ eval("/* WEBPACK VAR INJECTION */(function(Buffer) {/*\n * Copyright 2010-2015 A
|
|
|
604
755
|
/*! no static exports found */
|
|
605
756
|
/***/ (function(module, exports, __webpack_require__) {
|
|
606
757
|
|
|
607
|
-
eval("/* WEBPACK VAR INJECTION */(function(process) {/*\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\n//node.js deps\nvar events = __webpack_require__(/*! events */ \"./node_modules/events/events.js\");\nvar inherits = __webpack_require__(/*! util */ \"./node_modules/util/util.js\").inherits;\n\n//npm deps\nvar mqtt = __webpack_require__(/*! mqtt */ \"./node_modules/mqtt/lib/connect/index.js\");\nvar hmacSHA256 = __webpack_require__(/*! crypto-js/hmac-sha256 */ \"./node_modules/crypto-js/hmac-sha256.js\");\nvar sha256 = __webpack_require__(/*! crypto-js/sha256 */ \"./node_modules/crypto-js/sha256.js\");\n\n//app deps\nvar exceptions = __webpack_require__(/*! ./lib/exceptions */ \"./node_modules/aws-iot-device-sdk/device/lib/exceptions.js\");\nvar isUndefined = __webpack_require__(/*! ../common/lib/is-undefined */ \"./node_modules/aws-iot-device-sdk/common/lib/is-undefined.js\");\nvar tlsReader = __webpack_require__(/*! ../common/lib/tls-reader */ \"./node_modules/aws-iot-device-sdk/common/lib/tls-reader.js\");\nvar path = __webpack_require__(/*! path */ \"./node_modules/path-browserify/index.js\");\nvar fs = __webpack_require__(/*! fs */ \"./node_modules/node-libs-browser/mock/empty.js\");\n\n//begin module\nfunction makeTwoDigits(n) {\n if (n > 9) {\n return n;\n } else {\n return '0' + n;\n }\n}\nfunction getDateTimeString() {\n var d = new Date();\n\n //\n // The additional ''s are used to force JavaScript to interpret the\n // '+' operator as string concatenation rather than arithmetic.\n //\n return d.getUTCFullYear() + '' + makeTwoDigits(d.getUTCMonth() + 1) + '' + makeTwoDigits(d.getUTCDate()) + 'T' + '' + makeTwoDigits(d.getUTCHours()) + '' + makeTwoDigits(d.getUTCMinutes()) + '' + makeTwoDigits(d.getUTCSeconds()) + 'Z';\n}\nfunction getDateString(dateTimeString) {\n return dateTimeString.substring(0, dateTimeString.indexOf('T'));\n}\nfunction getSignatureKey(key, dateStamp, regionName, serviceName) {\n var kDate = hmacSHA256(dateStamp, 'AWS4' + key, {\n asBytes: true\n });\n var kRegion = hmacSHA256(regionName, kDate, {\n asBytes: true\n });\n var kService = hmacSHA256(serviceName, kRegion, {\n asBytes: true\n });\n var kSigning = hmacSHA256('aws4_request', kService, {\n asBytes: true\n });\n return kSigning;\n}\nfunction signUrl(method, scheme, hostname, path, queryParams, accessId, secretKey, region, serviceName, payload, today, now, debug, awsSTSToken) {\n var signedHeaders = 'host';\n var canonicalHeaders = 'host:' + hostname.toLowerCase() + '\\n';\n var canonicalRequest = method + '\\n' +\n // method\n path + '\\n' +\n // path\n queryParams + '\\n' +\n // query params\n canonicalHeaders +\n // headers\n '\\n' +\n // required\n signedHeaders + '\\n' +\n // signed header list\n sha256(payload, {\n asBytes: true\n }); // hash of payload (empty string)\n\n if (debug === true) {\n console.log('canonical request: ' + canonicalRequest + '\\n');\n }\n var hashedCanonicalRequest = sha256(canonicalRequest, {\n asBytes: true\n });\n if (debug === true) {\n console.log('hashed canonical request: ' + hashedCanonicalRequest + '\\n');\n }\n var stringToSign = 'AWS4-HMAC-SHA256\\n' + now + '\\n' + today + '/' + region + '/' + serviceName + '/aws4_request\\n' + hashedCanonicalRequest;\n if (debug === true) {\n console.log('string to sign: ' + stringToSign + '\\n');\n }\n var signingKey = getSignatureKey(secretKey, today, region, serviceName);\n if (debug === true) {\n console.log('signing key: ' + signingKey + '\\n');\n }\n var signature = hmacSHA256(stringToSign, signingKey, {\n asBytes: true\n });\n if (debug === true) {\n console.log('signature: ' + signature + '\\n');\n }\n var finalParams = queryParams + '&X-Amz-Signature=' + signature;\n if (!isUndefined(awsSTSToken)) {\n finalParams += '&X-Amz-Security-Token=' + encodeURIComponent(awsSTSToken);\n }\n var url = scheme + hostname + path + '?' + finalParams;\n if (debug === true) {\n console.log('url: ' + url + '\\n');\n }\n return url;\n}\nfunction prepareWebSocketUrl(options, awsAccessId, awsSecretKey, awsSTSToken) {\n var now = getDateTimeString();\n var today = getDateString(now);\n var path = '/mqtt';\n var awsServiceName = 'iotdevicegateway';\n var queryParams = 'X-Amz-Algorithm=AWS4-HMAC-SHA256' + '&X-Amz-Credential=' + awsAccessId + '%2F' + today + '%2F' + options.region + '%2F' + awsServiceName + '%2Faws4_request' + '&X-Amz-Date=' + now + '&X-Amz-SignedHeaders=host';\n var hostName = options.host;\n\n // Include the port number in the hostname if it's not\n // the standard wss port (443).\n //\n if (!isUndefined(options.port) && options.port !== 443) {\n hostName = options.host + ':' + options.port;\n }\n return signUrl('GET', 'wss://', hostName, path, queryParams, awsAccessId, awsSecretKey, options.region, awsServiceName, '', today, now, options.debug, awsSTSToken);\n}\nfunction prepareWebSocketCustomAuthUrl(options) {\n var path = '/mqtt';\n var hostName = options.host;\n\n // Include the port number in the hostname if it's not\n // the standard wss port (443).\n //\n if (!isUndefined(options.port) && options.port !== 443) {\n hostName = options.host + ':' + options.port;\n }\n return 'wss://' + hostName + path + (options.customAuthQueryString || '');\n}\nfunction arrayEach(array, iterFunction) {\n for (var idx in array) {\n if (Object.prototype.hasOwnProperty.call(array, idx)) {\n iterFunction.call(this, array[idx], parseInt(idx, 10));\n }\n }\n}\nfunction getCredentials(ini) {\n //Get shared credential function from AWS SDK.\n var map = {};\n var currentSection = {};\n arrayEach(ini.split(/\\r?\\n/), function (line) {\n line = line.split(/(^|\\s)[;#]/)[0]; // remove comments\n var section = line.match(/^\\s*\\[([^\\[\\]]+)\\]\\s*$/);\n if (section) {\n currentSection = section[1];\n } else if (currentSection) {\n var item = line.match(/^\\s*(.+?)\\s*=\\s*(.+?)\\s*$/);\n if (item) {\n map[currentSection] = map[currentSection] || {};\n map[currentSection][item[1]] = item[2];\n }\n }\n });\n return map;\n}\n\n//\n// This method is the exposed module; it validates the mqtt options,\n// creates a secure mqtt connection via TLS, and returns the mqtt\n// connection instance.\n//\nfunction DeviceClient(options) {\n //\n // Force instantiation using the 'new' operator; this will cause inherited\n // constructors (e.g. the 'events' class) to be called.\n //\n if (!(this instanceof DeviceClient)) {\n return new DeviceClient(options);\n }\n //\n // A copy of 'this' for use inside of closures\n //\n var that = this;\n\n //\n // Offline Operation\n //\n // The connection to AWS IoT can be in one of three states:\n //\n // 1) Inactive\n // 2) Established\n // 3) Stable\n //\n // During state 1), publish operations are placed in a queue\n // (\"filling\")\n //\n // During states 2) and 3), any operations present in the queue\n // are sent to the mqtt client for completion (\"draining\").\n //\n // In all states, subscriptions are tracked in a cache\n //\n // A \"draining interval\" is used to specify the rate at which\n // which operations are drained from the queue.\n //\n // +- - - - - - - - - - - - - - - - - - - - - - - - +\n // | |\n //\n // | FILLING |\n //\n // | |\n // +-----------------------------+\n // | | | |\n // | |\n // | v | |\n // +- - Established Inactive - -+\n // | | ^ |\n // | |\n // | | | |\n // +----------> Stable ----------+\n // | |\n //\n // | DRAINING |\n //\n // | |\n // +- - - - - - - - - - - - - - - - - - - - - - - - +\n //\n //\n // Draining Operation\n //\n // During draining, existing subscriptions are re-sent,\n // followed by any publishes which occurred while offline.\n //\n\n //\n // Publish cache used during filling\n //\n var offlinePublishQueue = [];\n var offlineQueueing = true;\n var offlineQueueMaxSize = 0;\n var offlineQueueDropBehavior = 'oldest'; // oldest or newest\n offlinePublishQueue.length = 0;\n\n //\n // Subscription queue for subscribe/unsubscribe requests received when offline\n // We do not want an unbounded queue so for now limit to current max subs in AWS IoT\n //\n var offlineSubscriptionQueue = [];\n var offlineSubscriptionQueueMaxSize = 50;\n offlineSubscriptionQueue.length = 0;\n\n //\n // Subscription cache; active if autoResubscribe === true\n //\n var activeSubscriptions = [];\n var autoResubscribe = true;\n activeSubscriptions.length = 0;\n\n //\n // Cloned subscription cache; active during initial draining.\n //\n var clonedSubscriptions = [];\n clonedSubscriptions.length = 0;\n\n //\n // Contains the operational state of the connection\n //\n var connectionState = 'inactive';\n\n //\n // Used to time draining operations; active during draining.\n //\n var drainingTimer = null;\n var drainTimeMs = 250;\n\n //Default keep alive time interval in seconds.\n var defaultKeepalive = 300;\n //\n // These properties control the reconnect behavior of the MQTT Client. If\n // the MQTT client becomes disconnected, it will attempt to reconnect after\n // a quiet period; this quiet period doubles with each reconnection attempt,\n // e.g. 1 seconds, 2 seconds, 2, 8, 16, 32, etc... up until a maximum\n // reconnection time is reached.\n //\n // If a connection is active for the minimum connection time, the quiet\n // period is reset to the initial value.\n //\n // baseReconnectTime: the time in seconds to wait before the first\n // reconnect attempt\n //\n // minimumConnectionTime: the time in seconds that a connection must be\n // active before resetting the current reconnection time to the base\n // reconnection time\n //\n // maximumReconnectTime: the maximum time in seconds to wait between\n // reconnect attempts\n //\n // The defaults for these values are:\n //\n // baseReconnectTime: 1 seconds\n // minimumConnectionTime: 20 seconds\n // maximumReconnectTime: 128 seconds\n //\n var baseReconnectTimeMs = 1000;\n var minimumConnectionTimeMs = 20000;\n var maximumReconnectTimeMs = 128000;\n var currentReconnectTimeMs;\n\n //\n // Used to measure the length of time the connection has been active to\n // know if it's stable or not. Active beginning from receipt of a 'connect'\n // event (e.g. received CONNACK) until 'minimumConnectionTimeMs' has elapsed.\n //\n var connectionTimer = null;\n\n //\n // Credentials when authenticating via WebSocket/SigV4\n //\n var awsAccessId;\n var awsSecretKey;\n var awsSTSToken;\n //\n // Validate options, set default reconnect period if not specified.\n //\n var metricPrefix = \"?SDK=JavaScript&Version=\";\n var pjson = __webpack_require__(/*! ../package.json */ \"./node_modules/aws-iot-device-sdk/package.json\");\n var sdkVersion = pjson.version;\n var defaultUsername = metricPrefix + sdkVersion;\n if (isUndefined(options) || Object.keys(options).length === 0) {\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n if (isUndefined(options.keepalive)) {\n options.keepalive = defaultKeepalive;\n }\n //\n // Metrics will be enabled by default unless the user explicitly disables it\n //\n if (isUndefined(options.enableMetrics) || options.enableMetrics === true) {\n if (isUndefined(options.username)) {\n options.username = defaultUsername;\n } else {\n options.username += defaultUsername;\n }\n }\n if (!isUndefined(options.baseReconnectTimeMs)) {\n baseReconnectTimeMs = options.baseReconnectTimeMs;\n }\n if (!isUndefined(options.minimumConnectionTimeMs)) {\n minimumConnectionTimeMs = options.minimumConnectionTimeMs;\n }\n if (!isUndefined(options.maximumReconnectTimeMs)) {\n maximumReconnectTimeMs = options.maximumReconnectTimeMs;\n }\n if (!isUndefined(options.drainTimeMs)) {\n drainTimeMs = options.drainTimeMs;\n }\n if (!isUndefined(options.autoResubscribe)) {\n autoResubscribe = options.autoResubscribe;\n }\n if (!isUndefined(options.offlineQueueing)) {\n offlineQueueing = options.offlineQueueing;\n }\n if (!isUndefined(options.offlineQueueMaxSize)) {\n offlineQueueMaxSize = options.offlineQueueMaxSize;\n }\n if (!isUndefined(options.offlineQueueDropBehavior)) {\n offlineQueueDropBehavior = options.offlineQueueDropBehavior;\n }\n currentReconnectTimeMs = baseReconnectTimeMs;\n options.reconnectPeriod = currentReconnectTimeMs;\n options.fastDisconnectDetection = true;\n //\n //SDK has its own logic to deal with auto resubscribe\n //\n options.resubscribe = false;\n\n //\n // Verify that the reconnection timing parameters make sense.\n //\n if (options.baseReconnectTimeMs <= 0) {\n throw new Error(exceptions.INVALID_RECONNECT_TIMING);\n }\n if (maximumReconnectTimeMs < baseReconnectTimeMs) {\n throw new Error(exceptions.INVALID_RECONNECT_TIMING);\n }\n if (minimumConnectionTimeMs < baseReconnectTimeMs) {\n throw new Error(exceptions.INVALID_RECONNECT_TIMING);\n }\n //\n // Verify that the other optional parameters make sense.\n //\n if (offlineQueueDropBehavior !== 'newest' && offlineQueueDropBehavior !== 'oldest') {\n throw new Error(exceptions.INVALID_OFFLINE_QUEUEING_PARAMETERS);\n }\n if (offlineQueueMaxSize < 0) {\n throw new Error(exceptions.INVALID_OFFLINE_QUEUEING_PARAMETERS);\n }\n\n // set protocol, do not override existing definitions if available\n if (isUndefined(options.protocol)) {\n options.protocol = 'mqtts';\n }\n if (isUndefined(options.host)) {\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n\n // set SNI, do not override existing definitions if available\n if (isUndefined(options.servername)) {\n options.servername = options.host.split(':')[0]; // Stripping out port if it exists along with host name\n }\n if (options.protocol === 'mqtts') {\n // set port, do not override existing definitions if available\n if (isUndefined(options.port)) {\n options.port = 8883;\n }\n\n //read and map certificates\n tlsReader(options);\n } else if (options.protocol === 'wss' || options.protocol === 'wss-custom-auth') {\n if (options.protocol === 'wss') {\n //\n // AWS access id and secret key\n // It first check Input options and Environment variables\n // If that not available, it will try to load credentials from default credential file\n if (!isUndefined(options.accessKeyId)) {\n awsAccessId = options.accessKeyId;\n } else {\n awsAccessId = process.env.AWS_ACCESS_KEY_ID;\n }\n if (!isUndefined(options.secretKey)) {\n awsSecretKey = options.secretKey;\n } else {\n awsSecretKey = process.env.AWS_SECRET_ACCESS_KEY;\n }\n if (!isUndefined(options.sessionToken)) {\n awsSTSToken = options.sessionToken;\n } else {\n awsSTSToken = process.env.AWS_SESSION_TOKEN;\n }\n if (isUndefined(awsAccessId) || isUndefined(awsSecretKey)) {\n var filename;\n var user_profile = options.profile || process.env.AWS_PROFILE || 'default';\n try {\n if (!isUndefined(options.filename)) {\n filename = options.filename;\n } else {\n filename = _loadDefaultFilename();\n }\n var creds = getCredentials(fs.readFileSync(filename, 'utf-8'));\n var profile = creds[user_profile];\n awsAccessId = profile.aws_access_key_id;\n awsSecretKey = profile.aws_secret_access_key;\n awsSTSToken = profile.aws_session_token;\n } catch (e) {\n console.log(e);\n console.log('Failed to read credentials for AWS_PROFILE ' + user_profile + ' from ' + filename);\n }\n }\n // AWS Access Key ID and AWS Secret Key must be defined\n if (isUndefined(awsAccessId) || isUndefined(awsSecretKey)) {\n console.log('To connect via WebSocket/SigV4, AWS Access Key ID and AWS Secret Key must be passed either in options or as environment variables; see README.md');\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n } else {\n if (isUndefined(options.customAuthHeaders) && isUndefined(options.customAuthQueryString)) {\n console.log('To authenticate with a custom authorizer, you must provide the required HTTP headers or queryString; see README.md');\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n }\n if (!isUndefined(options.host) && isUndefined(options.region)) {\n var pattern = /[a-zA-Z0-9]+\\.iot\\.([a-z]+-[a-z]+-[0-9]+)\\.amazonaws\\..+/;\n var region = pattern.exec(options.host);\n if (region === null) {\n console.log('Host endpoint is not valid');\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n } else {\n options.region = region[1];\n }\n }\n // set port, do not override existing definitions if available\n if (isUndefined(options.port)) {\n options.port = 443;\n }\n // check websocketOptions and ensure that the protocol is defined\n if (isUndefined(options.websocketOptions)) {\n options.websocketOptions = {\n protocol: 'mqttv3.1'\n };\n } else {\n options.websocketOptions.protocol = 'mqttv3.1';\n }\n if (options.protocol === 'wss-custom-auth') {\n options.websocketOptions.headers = options.customAuthHeaders;\n }\n }\n if (!isUndefined(options) && options.debug === true) {\n console.log(options);\n console.log('attempting new mqtt connection...');\n }\n //connect and return the client instance to map all mqttjs apis\n\n var protocols = {};\n protocols.mqtts = __webpack_require__(/*! ./lib/tls */ \"./node_modules/aws-iot-device-sdk/device/lib/tls.js\");\n protocols.wss = __webpack_require__(/*! ./lib/ws */ \"./node_modules/aws-iot-device-sdk/device/lib/ws.js\");\n function _loadDefaultFilename() {\n var home = process.env.HOME || process.env.USERPROFILE || (process.env.HOMEPATH ? (process.env.HOMEDRIVE || 'C:/') + process.env.HOMEPATH : null);\n return path.join(home, '.aws', 'credentials');\n }\n function _addToSubscriptionCache(topic, options) {\n var matches = activeSubscriptions.filter(function (element) {\n return element.topic === topic;\n });\n //\n // Add the element only if it doesn't already exist.\n //\n if (matches.length === 0) {\n activeSubscriptions.push({\n topic: topic,\n options: options\n });\n }\n }\n function _deleteFromSubscriptionCache(topic, options) {\n var remaining = activeSubscriptions.filter(function (element) {\n return element.topic !== topic;\n });\n activeSubscriptions = remaining;\n }\n function _updateSubscriptionCache(operation, topics, options) {\n var opFunc = null;\n\n //\n // Don't cache subscriptions if auto-resubscribe is disabled\n //\n if (autoResubscribe === false) {\n return;\n }\n if (operation === 'subscribe') {\n opFunc = _addToSubscriptionCache;\n } else if (operation === 'unsubscribe') {\n opFunc = _deleteFromSubscriptionCache;\n }\n //\n // Test to see if 'topics' is an array and if so, iterate.\n //\n if (Object.prototype.toString.call(topics) === '[object Array]') {\n topics.forEach(function (item, index, array) {\n opFunc(item, options);\n });\n } else {\n opFunc(topics, options);\n }\n }\n\n //\n // Return true if the connection is currently in a 'filling'\n // state\n //\n function _filling() {\n return connectionState === 'inactive';\n }\n function _wrapper(client) {\n var protocol = options.protocol;\n if (protocol === 'wss') {\n var url;\n //\n // If the access id and secret key are available, prepare the URL.\n // Otherwise, set the url to an invalid value.\n //\n if (awsAccessId === '' || awsSecretKey === '') {\n url = 'wss://no-credentials-available';\n } else {\n url = prepareWebSocketUrl(options, awsAccessId, awsSecretKey, awsSTSToken);\n }\n if (options.debug === true) {\n console.log('using websockets, will connect to \\'' + url + '\\'...');\n }\n options.url = url;\n } else if (protocol === 'wss-custom-auth') {\n options.url = prepareWebSocketCustomAuthUrl(options);\n if (options.debug === true) {\n console.log('using websockets custom auth, will connect to \\'' + options.url + '\\'...');\n }\n // Treat the request as a standard websocket request from here onwards\n protocol = 'wss';\n }\n return protocols[protocol](client, options);\n }\n var device = new mqtt.MqttClient(_wrapper, options);\n\n //handle events from the mqtt client\n\n //\n // Timeout expiry function for the connection timer; once a connection\n // is stable, reset the current reconnection time to the base value.\n //\n function _markConnectionStable() {\n currentReconnectTimeMs = baseReconnectTimeMs;\n device.options.reconnectPeriod = currentReconnectTimeMs;\n //\n // Mark this timeout as expired\n //\n connectionTimer = null;\n connectionState = 'stable';\n }\n //\n // Trim the offline queue if required; returns true if another\n // element can be placed in the queue\n //\n function _trimOfflinePublishQueueIfNecessary() {\n var rc = true;\n if (offlineQueueMaxSize > 0 && offlinePublishQueue.length >= offlineQueueMaxSize) {\n //\n // The queue has reached its maximum size, trim it\n // according to the defined drop behavior.\n //\n if (offlineQueueDropBehavior === 'oldest') {\n offlinePublishQueue.shift();\n } else {\n rc = false;\n }\n }\n return rc;\n }\n\n //\n // Timeout expiry function for the drain timer; once a connection\n // has been established, begin draining cached transactions.\n //\n function _drainOperationQueue() {\n //\n // Handle our active subscriptions first, using a cloned\n // copy of the array. We shift them out one-by-one until\n // all have been processed, leaving the official record\n // of active subscriptions untouched.\n //\n var subscription = clonedSubscriptions.shift();\n if (!isUndefined(subscription)) {\n //\n // If the 3rd argument (namely callback) is not present, we will\n // use two-argument form to call mqtt.Client#subscribe(), which\n // supports both subscribe(topics, options) and subscribe(topics, callback).\n //\n if (!isUndefined(subscription.callback)) {\n device.subscribe(subscription.topic, subscription.options, subscription.callback);\n } else {\n device.subscribe(subscription.topic, subscription.options);\n }\n } else {\n //\n // If no remaining active subscriptions to process,\n // then handle subscription requests queued while offline.\n //\n var req = offlineSubscriptionQueue.shift();\n if (!isUndefined(req)) {\n _updateSubscriptionCache(req.type, req.topics, req.options);\n if (req.type === 'subscribe') {\n if (!isUndefined(req.callback)) {\n device.subscribe(req.topics, req.options, req.callback);\n } else {\n device.subscribe(req.topics, req.options);\n }\n } else if (req.type === 'unsubscribe') {\n device.unsubscribe(req.topics, req.callback);\n }\n } else {\n //\n // If no active or queued subscriptions remaining to process,\n // then handle queued publish operations.\n //\n var offlinePublishMessage = offlinePublishQueue.shift();\n if (!isUndefined(offlinePublishMessage)) {\n device.publish(offlinePublishMessage.topic, offlinePublishMessage.message, offlinePublishMessage.options, offlinePublishMessage.callback);\n }\n if (offlinePublishQueue.length === 0) {\n //\n // The subscription and offlinePublishQueue queues are fully drained,\n // cancel the draining timer.\n //\n clearInterval(drainingTimer);\n drainingTimer = null;\n }\n }\n }\n }\n //\n // Event handling - *all* events generated by the mqtt.js client must be\n // handled here, *and* propagated upwards.\n //\n\n device.on('connect', function (connack) {\n //\n // If not already running, start the connection timer.\n //\n if (connectionTimer === null) {\n connectionTimer = setTimeout(_markConnectionStable, minimumConnectionTimeMs);\n }\n connectionState = 'established';\n //\n // If not already running, start the draining timer and\n // clone the active subscriptions.\n //\n if (drainingTimer === null) {\n clonedSubscriptions = activeSubscriptions.slice(0);\n drainingTimer = setInterval(_drainOperationQueue, drainTimeMs);\n }\n that.emit('connect', connack);\n });\n device.on('close', function (err) {\n if (!isUndefined(err)) {\n that.emit('error', err);\n }\n if (!isUndefined(options) && options.debug === true) {\n console.log('connection lost - will attempt reconnection in ' + device.options.reconnectPeriod / 1000 + ' seconds...');\n }\n //\n // Clear the connection and drain timers\n //\n clearTimeout(connectionTimer);\n connectionTimer = null;\n clearInterval(drainingTimer);\n drainingTimer = null;\n\n //\n // Mark the connection state as inactive\n //\n connectionState = 'inactive';\n that.emit('close');\n });\n device.on('reconnect', function () {\n //\n // Update the current reconnect timeout; this will be the\n // next timeout value used if this connect attempt fails.\n //\n currentReconnectTimeMs = currentReconnectTimeMs * 2;\n currentReconnectTimeMs = Math.min(maximumReconnectTimeMs, currentReconnectTimeMs);\n device.options.reconnectPeriod = currentReconnectTimeMs;\n that.emit('reconnect');\n });\n device.on('end', function () {\n that.emit('end');\n });\n device.on('offline', function () {\n that.emit('offline');\n });\n device.on('error', function (error) {\n that.emit('error', error);\n });\n device.on('packetsend', function (packet) {\n that.emit('packetsend', packet);\n });\n device.on('packetreceive', function (packet) {\n that.emit('packetreceive', packet);\n });\n device.on('message', function (topic, message, packet) {\n that.emit('message', topic, message, packet);\n });\n //\n // The signatures of these methods *must* match those of the mqtt.js\n // client.\n //\n this.publish = function (topic, message, options, callback) {\n //\n // If filling or still draining, push this publish operation\n // into the offline operations queue; otherwise, perform it\n // immediately.\n //\n if (offlineQueueing === true && (_filling() || drainingTimer !== null)) {\n if (_trimOfflinePublishQueueIfNecessary()) {\n offlinePublishQueue.push({\n topic: topic,\n message: message,\n options: options,\n callback: callback\n });\n }\n } else {\n if (offlineQueueing === true || !_filling()) {\n device.publish(topic, message, options, callback);\n }\n }\n };\n this.subscribe = function (topics, options, callback) {\n if (!_filling() || autoResubscribe === false) {\n _updateSubscriptionCache('subscribe', topics, options); // we do not store callback in active cache\n //\n // If the 3rd argument (namely callback) is not present, we will\n // use two-argument form to call mqtt.Client#subscribe(), which\n // supports both subscribe(topics, options) and subscribe(topics, callback).\n //\n if (!isUndefined(callback)) {\n device.subscribe(topics, options, callback);\n } else {\n device.subscribe(topics, options);\n }\n } else {\n // we're offline - queue this subscription request\n if (offlineSubscriptionQueue.length < offlineSubscriptionQueueMaxSize) {\n offlineSubscriptionQueue.push({\n type: 'subscribe',\n topics: topics,\n options: options,\n callback: callback\n });\n } else {\n that.emit('error', new Error('Maximum queued offline subscription reached'));\n }\n }\n };\n this.unsubscribe = function (topics, callback) {\n if (!_filling() || autoResubscribe === false) {\n _updateSubscriptionCache('unsubscribe', topics);\n device.unsubscribe(topics, callback);\n } else {\n // we're offline - queue this unsubscribe request\n if (offlineSubscriptionQueue.length < offlineSubscriptionQueueMaxSize) {\n offlineSubscriptionQueue.push({\n type: 'unsubscribe',\n topics: topics,\n options: options,\n callback: callback\n });\n }\n }\n };\n this.end = function (force, callback) {\n device.end(force, callback);\n };\n this.handleMessage = device.handleMessage.bind(device);\n device.handleMessage = function (packet, callback) {\n that.handleMessage(packet, callback);\n };\n this.updateWebSocketCredentials = function (accessKeyId, secretKey, sessionToken, expiration) {\n awsAccessId = accessKeyId;\n awsSecretKey = secretKey;\n awsSTSToken = sessionToken;\n };\n this.getWebsocketHeaders = function () {\n return options.websocketOptions.headers;\n };\n //\n // Call this function to update the custom auth headers\n //\n this.updateCustomAuthHeaders = function (newHeaders) {\n options.websocketOptions.headers = newHeaders;\n };\n //\n // Used for integration testing only\n //\n this.simulateNetworkFailure = function () {\n device.stream.emit('error', new Error('simulated connection error'));\n device.stream.end();\n };\n}\n\n//\n// Allow instances to listen in on events that we produce for them\n//\ninherits(DeviceClient, events.EventEmitter);\nmodule.exports = DeviceClient;\nmodule.exports.DeviceClient = DeviceClient;\n\n//\n// Exported for unit testing only\n//\nmodule.exports.prepareWebSocketUrl = prepareWebSocketUrl;\nmodule.exports.prepareWebSocketCustomAuthUrl = prepareWebSocketCustomAuthUrl;\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/aws-iot-device-sdk/device/index.js?");
|
|
758
|
+
eval("/* WEBPACK VAR INJECTION */(function(process) {/*\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\n//node.js deps\nvar events = __webpack_require__(/*! events */ \"./node_modules/events/events.js\");\nvar inherits = __webpack_require__(/*! util */ \"./node_modules/util/util.js\").inherits;\n\n//npm deps\nvar mqtt = __webpack_require__(/*! mqtt */ \"./node_modules/mqtt/lib/connect/index.js\");\nvar hmacSHA256 = __webpack_require__(/*! crypto-js/hmac-sha256 */ \"./node_modules/crypto-js/hmac-sha256.js\");\nvar sha256 = __webpack_require__(/*! crypto-js/sha256 */ \"./node_modules/crypto-js/sha256.js\");\n\n//app deps\nvar exceptions = __webpack_require__(/*! ./lib/exceptions */ \"./node_modules/aws-iot-device-sdk/device/lib/exceptions.js\");\nvar isUndefined = __webpack_require__(/*! ../common/lib/is-undefined */ \"./node_modules/aws-iot-device-sdk/common/lib/is-undefined.js\");\nvar tlsReader = __webpack_require__(/*! ../common/lib/tls-reader */ \"./node_modules/aws-iot-device-sdk/common/lib/tls-reader.js\");\nvar path = __webpack_require__(/*! path */ \"./node_modules/path-browserify/index.js\");\nvar fs = __webpack_require__(/*! fs */ \"./node_modules/node-libs-browser/mock/empty.js\");\n\n//begin module\nfunction makeTwoDigits(n) {\n if (n > 9) {\n return n;\n } else {\n return '0' + n;\n }\n}\nfunction getDateTimeString() {\n var d = new Date();\n\n //\n // The additional ''s are used to force JavaScript to interpret the\n // '+' operator as string concatenation rather than arithmetic.\n //\n return d.getUTCFullYear() + '' + makeTwoDigits(d.getUTCMonth() + 1) + '' + makeTwoDigits(d.getUTCDate()) + 'T' + '' + makeTwoDigits(d.getUTCHours()) + '' + makeTwoDigits(d.getUTCMinutes()) + '' + makeTwoDigits(d.getUTCSeconds()) + 'Z';\n}\nfunction getDateString(dateTimeString) {\n return dateTimeString.substring(0, dateTimeString.indexOf('T'));\n}\nfunction getSignatureKey(key, dateStamp, regionName, serviceName) {\n var kDate = hmacSHA256(dateStamp, 'AWS4' + key, {\n asBytes: true\n });\n var kRegion = hmacSHA256(regionName, kDate, {\n asBytes: true\n });\n var kService = hmacSHA256(serviceName, kRegion, {\n asBytes: true\n });\n var kSigning = hmacSHA256('aws4_request', kService, {\n asBytes: true\n });\n return kSigning;\n}\nfunction signUrl(method, scheme, hostname, path, queryParams, accessId, secretKey, region, serviceName, payload, today, now, debug, awsSTSToken) {\n var signedHeaders = 'host';\n var canonicalHeaders = 'host:' + hostname.toLowerCase() + '\\n';\n var canonicalRequest = method + '\\n' +\n // method\n path + '\\n' +\n // path\n queryParams + '\\n' +\n // query params\n canonicalHeaders +\n // headers\n '\\n' +\n // required\n signedHeaders + '\\n' +\n // signed header list\n sha256(payload, {\n asBytes: true\n }); // hash of payload (empty string)\n\n if (debug === true) {\n console.log('canonical request: ' + canonicalRequest + '\\n');\n }\n var hashedCanonicalRequest = sha256(canonicalRequest, {\n asBytes: true\n });\n if (debug === true) {\n console.log('hashed canonical request: ' + hashedCanonicalRequest + '\\n');\n }\n var stringToSign = 'AWS4-HMAC-SHA256\\n' + now + '\\n' + today + '/' + region + '/' + serviceName + '/aws4_request\\n' + hashedCanonicalRequest;\n if (debug === true) {\n console.log('string to sign: ' + stringToSign + '\\n');\n }\n var signingKey = getSignatureKey(secretKey, today, region, serviceName);\n if (debug === true) {\n console.log('signing key: ' + signingKey + '\\n');\n }\n var signature = hmacSHA256(stringToSign, signingKey, {\n asBytes: true\n });\n if (debug === true) {\n console.log('signature: ' + signature + '\\n');\n }\n var finalParams = queryParams + '&X-Amz-Signature=' + signature;\n if (!isUndefined(awsSTSToken)) {\n finalParams += '&X-Amz-Security-Token=' + encodeURIComponent(awsSTSToken);\n }\n var url = scheme + hostname + path + '?' + finalParams;\n if (debug === true) {\n console.log('url: ' + url + '\\n');\n }\n return url;\n}\nfunction prepareWebSocketUrl(options, awsAccessId, awsSecretKey, awsSTSToken) {\n var now = getDateTimeString();\n var today = getDateString(now);\n var path = '/mqtt';\n var awsServiceName = 'iotdevicegateway';\n var queryParams = 'X-Amz-Algorithm=AWS4-HMAC-SHA256' + '&X-Amz-Credential=' + awsAccessId + '%2F' + today + '%2F' + options.region + '%2F' + awsServiceName + '%2Faws4_request' + '&X-Amz-Date=' + now + '&X-Amz-SignedHeaders=host';\n var hostName = options.host;\n\n // Include the port number in the hostname if it's not\n // the standard wss port (443).\n //\n if (!isUndefined(options.port) && options.port !== 443) {\n hostName = options.host + ':' + options.port;\n }\n return signUrl('GET', 'wss://', hostName, path, queryParams, awsAccessId, awsSecretKey, options.region, awsServiceName, '', today, now, options.debug, awsSTSToken);\n}\nfunction prepareWebSocketCustomAuthUrl(options) {\n var path = '/mqtt';\n var hostName = options.host;\n\n // Include the port number in the hostname if it's not\n // the standard wss port (443).\n //\n if (!isUndefined(options.port) && options.port !== 443) {\n hostName = options.host + ':' + options.port;\n }\n return 'wss://' + hostName + path + (options.customAuthQueryString || '');\n}\nfunction arrayEach(array, iterFunction) {\n for (var idx in array) {\n if (Object.prototype.hasOwnProperty.call(array, idx)) {\n iterFunction.call(this, array[idx], parseInt(idx, 10));\n }\n }\n}\nfunction getCredentials(ini) {\n //Get shared credential function from AWS SDK.\n var map = {};\n var currentSection = {};\n arrayEach(ini.split(/\\r?\\n/), function (line) {\n line = line.split(/(^|\\s)[;#]/)[0]; // remove comments\n var section = line.match(/^\\s*\\[([^\\[\\]]+)\\]\\s*$/);\n if (section) {\n currentSection = section[1];\n } else if (currentSection) {\n var item = line.match(/^\\s*(.+?)\\s*=\\s*(.+?)\\s*$/);\n if (item) {\n map[currentSection] = map[currentSection] || {};\n map[currentSection][item[1]] = item[2];\n }\n }\n });\n return map;\n}\n\n//\n// This method is the exposed module; it validates the mqtt options,\n// creates a secure mqtt connection via TLS, and returns the mqtt\n// connection instance.\n//\nfunction DeviceClient(options) {\n //\n // Force instantiation using the 'new' operator; this will cause inherited\n // constructors (e.g. the 'events' class) to be called.\n //\n if (!(this instanceof DeviceClient)) {\n return new DeviceClient(options);\n }\n //\n // A copy of 'this' for use inside of closures\n //\n var that = this;\n\n //\n // Offline Operation\n //\n // The connection to AWS IoT can be in one of three states:\n //\n // 1) Inactive\n // 2) Established\n // 3) Stable\n //\n // During state 1), publish operations are placed in a queue\n // (\"filling\")\n //\n // During states 2) and 3), any operations present in the queue\n // are sent to the mqtt client for completion (\"draining\").\n //\n // In all states, subscriptions are tracked in a cache\n //\n // A \"draining interval\" is used to specify the rate at which\n // which operations are drained from the queue.\n //\n // +- - - - - - - - - - - - - - - - - - - - - - - - +\n // | |\n //\n // | FILLING |\n //\n // | |\n // +-----------------------------+\n // | | | |\n // | |\n // | v | |\n // +- - Established Inactive - -+\n // | | ^ |\n // | |\n // | | | |\n // +----------> Stable ----------+\n // | |\n //\n // | DRAINING |\n //\n // | |\n // +- - - - - - - - - - - - - - - - - - - - - - - - +\n //\n //\n // Draining Operation\n //\n // During draining, existing subscriptions are re-sent,\n // followed by any publishes which occurred while offline.\n //\n\n //\n // Publish cache used during filling\n //\n var offlinePublishQueue = [];\n var offlineQueueing = true;\n var offlineQueueMaxSize = 0;\n var offlineQueueDropBehavior = 'oldest'; // oldest or newest\n offlinePublishQueue.length = 0;\n\n //\n // Subscription queue for subscribe/unsubscribe requests received when offline\n // We do not want an unbounded queue so for now limit to current max subs in AWS IoT\n //\n var offlineSubscriptionQueue = [];\n var offlineSubscriptionQueueMaxSize = 50;\n offlineSubscriptionQueue.length = 0;\n\n //\n // Subscription cache; active if autoResubscribe === true\n //\n var activeSubscriptions = [];\n var autoResubscribe = true;\n activeSubscriptions.length = 0;\n\n //\n // Cloned subscription cache; active during initial draining.\n //\n var clonedSubscriptions = [];\n clonedSubscriptions.length = 0;\n\n //\n // Contains the operational state of the connection\n //\n var connectionState = 'inactive';\n\n //\n // Used to time draining operations; active during draining.\n //\n var drainingTimer = null;\n var drainTimeMs = 250;\n\n //Default keep alive time interval in seconds.\n var defaultKeepalive = 300;\n //\n // These properties control the reconnect behavior of the MQTT Client. If\n // the MQTT client becomes disconnected, it will attempt to reconnect after\n // a quiet period; this quiet period doubles with each reconnection attempt,\n // e.g. 1 seconds, 2 seconds, 2, 8, 16, 32, etc... up until a maximum\n // reconnection time is reached.\n //\n // If a connection is active for the minimum connection time, the quiet\n // period is reset to the initial value.\n //\n // baseReconnectTime: the time in seconds to wait before the first\n // reconnect attempt\n //\n // minimumConnectionTime: the time in seconds that a connection must be\n // active before resetting the current reconnection time to the base\n // reconnection time\n //\n // maximumReconnectTime: the maximum time in seconds to wait between\n // reconnect attempts\n //\n // The defaults for these values are:\n //\n // baseReconnectTime: 1 seconds\n // minimumConnectionTime: 20 seconds\n // maximumReconnectTime: 128 seconds\n //\n var baseReconnectTimeMs = 1000;\n var minimumConnectionTimeMs = 20000;\n var maximumReconnectTimeMs = 128000;\n var currentReconnectTimeMs;\n\n //\n // Used to measure the length of time the connection has been active to\n // know if it's stable or not. Active beginning from receipt of a 'connect'\n // event (e.g. received CONNACK) until 'minimumConnectionTimeMs' has elapsed.\n //\n var connectionTimer = null;\n\n //\n // Credentials when authenticating via WebSocket/SigV4\n //\n var awsAccessId;\n var awsSecretKey;\n var awsSTSToken;\n //\n // Validate options, set default reconnect period if not specified.\n //\n var metricPrefix = \"?SDK=JavaScript&Version=\";\n var pjson = __webpack_require__(/*! ../package.json */ \"./node_modules/aws-iot-device-sdk/package.json\");\n var sdkVersion = pjson.version;\n var defaultUsername = metricPrefix + sdkVersion;\n if (isUndefined(options) || Object.keys(options).length === 0) {\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n if (isUndefined(options.keepalive)) {\n options.keepalive = defaultKeepalive;\n }\n //\n // Metrics will be enabled by default unless the user explicitly disables it\n //\n if (isUndefined(options.enableMetrics) || options.enableMetrics === true) {\n if (isUndefined(options.username)) {\n options.username = defaultUsername;\n } else {\n options.username += defaultUsername;\n }\n }\n if (!isUndefined(options.baseReconnectTimeMs)) {\n baseReconnectTimeMs = options.baseReconnectTimeMs;\n }\n if (!isUndefined(options.minimumConnectionTimeMs)) {\n minimumConnectionTimeMs = options.minimumConnectionTimeMs;\n }\n if (!isUndefined(options.maximumReconnectTimeMs)) {\n maximumReconnectTimeMs = options.maximumReconnectTimeMs;\n }\n if (!isUndefined(options.drainTimeMs)) {\n drainTimeMs = options.drainTimeMs;\n }\n if (!isUndefined(options.autoResubscribe)) {\n autoResubscribe = options.autoResubscribe;\n }\n if (!isUndefined(options.offlineQueueing)) {\n offlineQueueing = options.offlineQueueing;\n }\n if (!isUndefined(options.offlineQueueMaxSize)) {\n offlineQueueMaxSize = options.offlineQueueMaxSize;\n }\n if (!isUndefined(options.offlineQueueDropBehavior)) {\n offlineQueueDropBehavior = options.offlineQueueDropBehavior;\n }\n currentReconnectTimeMs = baseReconnectTimeMs;\n options.reconnectPeriod = currentReconnectTimeMs;\n options.fastDisconnectDetection = true;\n //\n //SDK has its own logic to deal with auto resubscribe\n //\n options.resubscribe = false;\n\n //\n // Verify that the reconnection timing parameters make sense.\n //\n if (options.baseReconnectTimeMs <= 0) {\n throw new Error(exceptions.INVALID_RECONNECT_TIMING);\n }\n if (maximumReconnectTimeMs < baseReconnectTimeMs) {\n throw new Error(exceptions.INVALID_RECONNECT_TIMING);\n }\n if (minimumConnectionTimeMs < baseReconnectTimeMs) {\n throw new Error(exceptions.INVALID_RECONNECT_TIMING);\n }\n //\n // Verify that the other optional parameters make sense.\n //\n if (offlineQueueDropBehavior !== 'newest' && offlineQueueDropBehavior !== 'oldest') {\n throw new Error(exceptions.INVALID_OFFLINE_QUEUEING_PARAMETERS);\n }\n if (offlineQueueMaxSize < 0) {\n throw new Error(exceptions.INVALID_OFFLINE_QUEUEING_PARAMETERS);\n }\n\n // set protocol, do not override existing definitions if available\n if (isUndefined(options.protocol)) {\n options.protocol = 'mqtts';\n }\n if (isUndefined(options.host)) {\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n\n // set SNI, do not override existing definitions if available\n if (isUndefined(options.servername)) {\n options.servername = options.host.split(':')[0]; // Stripping out port if it exists along with host name\n }\n if (options.protocol === 'mqtts') {\n // set port, do not override existing definitions if available\n if (isUndefined(options.port)) {\n options.port = 8883;\n }\n\n //read and map certificates\n tlsReader(options);\n } else if (options.protocol === 'wss' || options.protocol === 'wss-custom-auth') {\n if (options.protocol === 'wss') {\n //\n // AWS access id and secret key\n // It first check Input options and Environment variables\n // If that not available, it will try to load credentials from default credential file\n if (!isUndefined(options.accessKeyId)) {\n awsAccessId = options.accessKeyId;\n } else {\n awsAccessId = process.env.AWS_ACCESS_KEY_ID;\n }\n if (!isUndefined(options.secretKey)) {\n awsSecretKey = options.secretKey;\n } else {\n awsSecretKey = process.env.AWS_SECRET_ACCESS_KEY;\n }\n if (!isUndefined(options.sessionToken)) {\n awsSTSToken = options.sessionToken;\n } else {\n awsSTSToken = process.env.AWS_SESSION_TOKEN;\n }\n if (isUndefined(awsAccessId) || isUndefined(awsSecretKey)) {\n var filename;\n var user_profile = options.profile || process.env.AWS_PROFILE || 'default';\n try {\n if (!isUndefined(options.filename)) {\n filename = options.filename;\n } else {\n filename = _loadDefaultFilename();\n }\n var creds = getCredentials(fs.readFileSync(filename, 'utf-8'));\n var profile = creds[user_profile];\n awsAccessId = profile.aws_access_key_id;\n awsSecretKey = profile.aws_secret_access_key;\n awsSTSToken = profile.aws_session_token;\n } catch (e) {\n console.log(e);\n console.log('Failed to read credentials for AWS_PROFILE ' + user_profile + ' from ' + filename);\n }\n }\n // AWS Access Key ID and AWS Secret Key must be defined\n if (isUndefined(awsAccessId) || isUndefined(awsSecretKey)) {\n console.log('To connect via WebSocket/SigV4, AWS Access Key ID and AWS Secret Key must be passed either in options or as environment variables; see README.md');\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n } else {\n if (isUndefined(options.customAuthHeaders) && isUndefined(options.customAuthQueryString)) {\n console.log('To authenticate with a custom authorizer, you must provide the required HTTP headers or queryString; see README.md');\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n }\n }\n if (!isUndefined(options.host) && isUndefined(options.region)) {\n // extract anything in between \"iot\" and \"amazonaws\" as region\n var pattern = /[a-zA-Z0-9]+\\.iot\\.([^\\.]+)\\.amazonaws\\..+/;\n var region = pattern.exec(options.host);\n if (region === null) {\n console.log('Host endpoint is not valid');\n throw new Error(exceptions.INVALID_CONNECT_OPTIONS);\n } else {\n options.region = region[1];\n }\n }\n // set port, do not override existing definitions if available\n if (isUndefined(options.port)) {\n options.port = 443;\n }\n // check websocketOptions and ensure that the protocol is defined\n if (isUndefined(options.websocketOptions)) {\n options.websocketOptions = {\n protocol: 'mqttv3.1'\n };\n } else {\n options.websocketOptions.protocol = 'mqttv3.1';\n }\n if (options.protocol === 'wss-custom-auth') {\n options.websocketOptions.headers = options.customAuthHeaders;\n }\n }\n if (!isUndefined(options) && options.debug === true) {\n console.log(options);\n console.log('attempting new mqtt connection...');\n }\n //connect and return the client instance to map all mqttjs apis\n\n var protocols = {};\n protocols.mqtts = __webpack_require__(/*! ./lib/tls */ \"./node_modules/aws-iot-device-sdk/device/lib/tls.js\");\n protocols.wss = __webpack_require__(/*! ./lib/ws */ \"./node_modules/aws-iot-device-sdk/device/lib/ws.js\");\n function _loadDefaultFilename() {\n var home = process.env.HOME || process.env.USERPROFILE || (process.env.HOMEPATH ? (process.env.HOMEDRIVE || 'C:/') + process.env.HOMEPATH : null);\n return path.join(home, '.aws', 'credentials');\n }\n function _addToSubscriptionCache(topic, options) {\n var matches = activeSubscriptions.filter(function (element) {\n return element.topic === topic;\n });\n //\n // Add the element only if it doesn't already exist.\n //\n if (matches.length === 0) {\n activeSubscriptions.push({\n topic: topic,\n options: options\n });\n }\n }\n function _deleteFromSubscriptionCache(topic, options) {\n var remaining = activeSubscriptions.filter(function (element) {\n return element.topic !== topic;\n });\n activeSubscriptions = remaining;\n }\n function _updateSubscriptionCache(operation, topics, options) {\n var opFunc = null;\n\n //\n // Don't cache subscriptions if auto-resubscribe is disabled\n //\n if (autoResubscribe === false) {\n return;\n }\n if (operation === 'subscribe') {\n opFunc = _addToSubscriptionCache;\n } else if (operation === 'unsubscribe') {\n opFunc = _deleteFromSubscriptionCache;\n }\n //\n // Test to see if 'topics' is an array and if so, iterate.\n //\n if (Object.prototype.toString.call(topics) === '[object Array]') {\n topics.forEach(function (item, index, array) {\n opFunc(item, options);\n });\n } else {\n opFunc(topics, options);\n }\n }\n\n //\n // Return true if the connection is currently in a 'filling'\n // state\n //\n function _filling() {\n return connectionState === 'inactive';\n }\n function _wrapper(client) {\n var protocol = options.protocol;\n if (protocol === 'wss') {\n var url;\n //\n // If the access id and secret key are available, prepare the URL.\n // Otherwise, set the url to an invalid value.\n //\n if (awsAccessId === '' || awsSecretKey === '') {\n url = 'wss://no-credentials-available';\n } else {\n url = prepareWebSocketUrl(options, awsAccessId, awsSecretKey, awsSTSToken);\n }\n if (options.debug === true) {\n console.log('using websockets, will connect to \\'' + url + '\\'...');\n }\n options.url = url;\n } else if (protocol === 'wss-custom-auth') {\n options.url = prepareWebSocketCustomAuthUrl(options);\n if (options.debug === true) {\n console.log('using websockets custom auth, will connect to \\'' + options.url + '\\'...');\n }\n // Treat the request as a standard websocket request from here onwards\n protocol = 'wss';\n }\n return protocols[protocol](client, options);\n }\n var device = new mqtt.MqttClient(_wrapper, options);\n\n //handle events from the mqtt client\n\n //\n // Timeout expiry function for the connection timer; once a connection\n // is stable, reset the current reconnection time to the base value.\n //\n function _markConnectionStable() {\n currentReconnectTimeMs = baseReconnectTimeMs;\n device.options.reconnectPeriod = currentReconnectTimeMs;\n //\n // Mark this timeout as expired\n //\n connectionTimer = null;\n connectionState = 'stable';\n }\n //\n // Trim the offline queue if required; returns true if another\n // element can be placed in the queue\n //\n function _trimOfflinePublishQueueIfNecessary() {\n var rc = true;\n if (offlineQueueMaxSize > 0 && offlinePublishQueue.length >= offlineQueueMaxSize) {\n //\n // The queue has reached its maximum size, trim it\n // according to the defined drop behavior.\n //\n if (offlineQueueDropBehavior === 'oldest') {\n offlinePublishQueue.shift();\n } else {\n rc = false;\n }\n }\n return rc;\n }\n\n //\n // Timeout expiry function for the drain timer; once a connection\n // has been established, begin draining cached transactions.\n //\n function _drainOperationQueue() {\n //\n // Handle our active subscriptions first, using a cloned\n // copy of the array. We shift them out one-by-one until\n // all have been processed, leaving the official record\n // of active subscriptions untouched.\n //\n var subscription = clonedSubscriptions.shift();\n if (!isUndefined(subscription)) {\n //\n // If the 3rd argument (namely callback) is not present, we will\n // use two-argument form to call mqtt.Client#subscribe(), which\n // supports both subscribe(topics, options) and subscribe(topics, callback).\n //\n if (!isUndefined(subscription.callback)) {\n device.subscribe(subscription.topic, subscription.options, subscription.callback);\n } else {\n device.subscribe(subscription.topic, subscription.options);\n }\n } else {\n //\n // If no remaining active subscriptions to process,\n // then handle subscription requests queued while offline.\n //\n var req = offlineSubscriptionQueue.shift();\n if (!isUndefined(req)) {\n _updateSubscriptionCache(req.type, req.topics, req.options);\n if (req.type === 'subscribe') {\n if (!isUndefined(req.callback)) {\n device.subscribe(req.topics, req.options, req.callback);\n } else {\n device.subscribe(req.topics, req.options);\n }\n } else if (req.type === 'unsubscribe') {\n device.unsubscribe(req.topics, req.callback);\n }\n } else {\n //\n // If no active or queued subscriptions remaining to process,\n // then handle queued publish operations.\n //\n var offlinePublishMessage = offlinePublishQueue.shift();\n if (!isUndefined(offlinePublishMessage)) {\n device.publish(offlinePublishMessage.topic, offlinePublishMessage.message, offlinePublishMessage.options, offlinePublishMessage.callback);\n }\n if (offlinePublishQueue.length === 0) {\n //\n // The subscription and offlinePublishQueue queues are fully drained,\n // cancel the draining timer.\n //\n clearInterval(drainingTimer);\n drainingTimer = null;\n }\n }\n }\n }\n //\n // Event handling - *all* events generated by the mqtt.js client must be\n // handled here, *and* propagated upwards.\n //\n\n device.on('connect', function (connack) {\n //\n // If not already running, start the connection timer.\n //\n if (connectionTimer === null) {\n connectionTimer = setTimeout(_markConnectionStable, minimumConnectionTimeMs);\n }\n connectionState = 'established';\n //\n // If not already running, start the draining timer and\n // clone the active subscriptions.\n //\n if (drainingTimer === null) {\n clonedSubscriptions = activeSubscriptions.slice(0);\n drainingTimer = setInterval(_drainOperationQueue, drainTimeMs);\n }\n that.emit('connect', connack);\n });\n device.on('close', function (err) {\n if (!isUndefined(err)) {\n that.emit('error', err);\n }\n if (!isUndefined(options) && options.debug === true) {\n console.log('connection lost - will attempt reconnection in ' + device.options.reconnectPeriod / 1000 + ' seconds...');\n }\n //\n // Clear the connection and drain timers\n //\n clearTimeout(connectionTimer);\n connectionTimer = null;\n clearInterval(drainingTimer);\n drainingTimer = null;\n\n //\n // Mark the connection state as inactive\n //\n connectionState = 'inactive';\n that.emit('close');\n });\n device.on('reconnect', function () {\n //\n // Update the current reconnect timeout; this will be the\n // next timeout value used if this connect attempt fails.\n //\n currentReconnectTimeMs = currentReconnectTimeMs * 2;\n currentReconnectTimeMs = Math.min(maximumReconnectTimeMs, currentReconnectTimeMs);\n device.options.reconnectPeriod = currentReconnectTimeMs;\n that.emit('reconnect');\n });\n device.on('end', function () {\n that.emit('end');\n });\n device.on('offline', function () {\n that.emit('offline');\n });\n device.on('error', function (error) {\n that.emit('error', error);\n });\n device.on('packetsend', function (packet) {\n that.emit('packetsend', packet);\n });\n device.on('packetreceive', function (packet) {\n that.emit('packetreceive', packet);\n });\n device.on('message', function (topic, message, packet) {\n that.emit('message', topic, message, packet);\n });\n //\n // The signatures of these methods *must* match those of the mqtt.js\n // client.\n //\n this.publish = function (topic, message, options, callback) {\n //\n // If filling or still draining, push this publish operation\n // into the offline operations queue; otherwise, perform it\n // immediately.\n //\n if (offlineQueueing === true && (_filling() || drainingTimer !== null)) {\n if (_trimOfflinePublishQueueIfNecessary()) {\n offlinePublishQueue.push({\n topic: topic,\n message: message,\n options: options,\n callback: callback\n });\n }\n } else {\n if (offlineQueueing === true || !_filling()) {\n device.publish(topic, message, options, callback);\n }\n }\n };\n this.subscribe = function (topics, options, callback) {\n if (!_filling() || autoResubscribe === false) {\n _updateSubscriptionCache('subscribe', topics, options); // we do not store callback in active cache\n //\n // If the 3rd argument (namely callback) is not present, we will\n // use two-argument form to call mqtt.Client#subscribe(), which\n // supports both subscribe(topics, options) and subscribe(topics, callback).\n //\n if (!isUndefined(callback)) {\n device.subscribe(topics, options, callback);\n } else {\n device.subscribe(topics, options);\n }\n } else {\n // we're offline - queue this subscription request\n if (offlineSubscriptionQueue.length < offlineSubscriptionQueueMaxSize) {\n offlineSubscriptionQueue.push({\n type: 'subscribe',\n topics: topics,\n options: options,\n callback: callback\n });\n } else {\n that.emit('error', new Error('Maximum queued offline subscription reached'));\n }\n }\n };\n this.unsubscribe = function (topics, callback) {\n if (!_filling() || autoResubscribe === false) {\n _updateSubscriptionCache('unsubscribe', topics);\n device.unsubscribe(topics, callback);\n } else {\n // we're offline - queue this unsubscribe request\n if (offlineSubscriptionQueue.length < offlineSubscriptionQueueMaxSize) {\n offlineSubscriptionQueue.push({\n type: 'unsubscribe',\n topics: topics,\n options: options,\n callback: callback\n });\n }\n }\n };\n this.end = function (force, callback) {\n device.end(force, callback);\n };\n this.handleMessage = device.handleMessage.bind(device);\n device.handleMessage = function (packet, callback) {\n that.handleMessage(packet, callback);\n };\n this.updateWebSocketCredentials = function (accessKeyId, secretKey, sessionToken, expiration) {\n awsAccessId = accessKeyId;\n awsSecretKey = secretKey;\n awsSTSToken = sessionToken;\n };\n this.getWebsocketHeaders = function () {\n return options.websocketOptions.headers;\n };\n //\n // Call this function to update the custom auth headers\n //\n this.updateCustomAuthHeaders = function (newHeaders) {\n options.websocketOptions.headers = newHeaders;\n };\n //\n // Used for integration testing only\n //\n this.simulateNetworkFailure = function () {\n device.stream.emit('error', new Error('simulated connection error'));\n device.stream.end();\n };\n}\n\n//\n// Allow instances to listen in on events that we produce for them\n//\ninherits(DeviceClient, events.EventEmitter);\nmodule.exports = DeviceClient;\nmodule.exports.DeviceClient = DeviceClient;\n\n//\n// Exported for unit testing only\n//\nmodule.exports.prepareWebSocketUrl = prepareWebSocketUrl;\nmodule.exports.prepareWebSocketCustomAuthUrl = prepareWebSocketCustomAuthUrl;\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/aws-iot-device-sdk/device/index.js?");
|
|
608
759
|
|
|
609
760
|
/***/ }),
|
|
610
761
|
|
|
@@ -637,7 +788,7 @@ eval("/*\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights
|
|
|
637
788
|
/*! no static exports found */
|
|
638
789
|
/***/ (function(module, exports, __webpack_require__) {
|
|
639
790
|
|
|
640
|
-
eval("/*\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\n//node.js deps\n\n//npm deps\nvar websocket = __webpack_require__(/*! websocket-stream */ \"./node_modules/websocket-stream/stream.js\");\n\n//app deps\n\nfunction buildBuilder(client, opts) {\n return websocket(opts.url, ['mqttv3.1'], opts.websocketOptions);\n}\nmodule.exports = buildBuilder;\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/aws-iot-device-sdk/device/lib/ws.js?");
|
|
791
|
+
eval("/*\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\n//node.js deps\n\n//npm deps\nvar websocket = __webpack_require__(/*! @httptoolkit/websocket-stream */ \"./node_modules/@httptoolkit/websocket-stream/stream.js\");\n\n//app deps\n\nfunction buildBuilder(client, opts) {\n return websocket(opts.url, ['mqttv3.1'], opts.websocketOptions);\n}\nmodule.exports = buildBuilder;\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/aws-iot-device-sdk/device/lib/ws.js?");
|
|
641
792
|
|
|
642
793
|
/***/ }),
|
|
643
794
|
|
|
@@ -670,7 +821,7 @@ eval("/*\n * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights
|
|
|
670
821
|
/*! exports provided: name, description, version, author, homepage, main, engines, repository, bugs, license, keywords, dependencies, devDependencies, scripts, default */
|
|
671
822
|
/***/ (function(module) {
|
|
672
823
|
|
|
673
|
-
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"aws-iot-device-sdk\\\",\\\"description\\\":\\\"AWS IoT Node.js SDK for Embedded Devices\\\",\\\"version\\\":\\\"2.2.
|
|
824
|
+
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"aws-iot-device-sdk\\\",\\\"description\\\":\\\"AWS IoT Node.js SDK for Embedded Devices\\\",\\\"version\\\":\\\"2.2.15\\\",\\\"author\\\":{\\\"name\\\":\\\"Amazon Web Services\\\",\\\"email\\\":\\\"\\\",\\\"url\\\":\\\"http://aws.amazon.com\\\"},\\\"homepage\\\":\\\"https://github.com/aws/aws-iot-device-sdk-js\\\",\\\"main\\\":\\\"index.js\\\",\\\"engines\\\":{\\\"node\\\":\\\">=8.17.0\\\"},\\\"repository\\\":{\\\"type\\\":\\\"git\\\",\\\"url\\\":\\\"git://github.com/aws/aws-iot-device-sdk-js\\\"},\\\"bugs\\\":{\\\"url\\\":\\\"http://github.com/aws/aws-iot-device-sdk-js/issues\\\"},\\\"license\\\":\\\"Apache-2.0\\\",\\\"keywords\\\":[\\\"api\\\",\\\"amazon\\\",\\\"aws\\\",\\\"iot\\\",\\\"mqtt\\\"],\\\"dependencies\\\":{\\\"crypto-js\\\":\\\"4.2.0\\\",\\\"minimist\\\":\\\"1.2.6\\\",\\\"mqtt\\\":\\\"4.2.8\\\",\\\"@httptoolkit/websocket-stream\\\":\\\"^6.0.1\\\"},\\\"devDependencies\\\":{\\\"gulp\\\":\\\"^3.9.0\\\",\\\"gulp-beautify\\\":\\\"^2.0.0\\\",\\\"gulp-concat\\\":\\\"^2.6.0\\\",\\\"gulp-coverage\\\":\\\"^0.3.38\\\",\\\"gulp-jscs\\\":\\\"^4.0.0\\\",\\\"gulp-jshint\\\":\\\"^2.0.0\\\",\\\"gulp-mocha\\\":\\\"^3.0.1\\\",\\\"jshint\\\":\\\"^2.9.1\\\",\\\"jshint-stylish\\\":\\\"^2.2.1\\\",\\\"rewire\\\":\\\"^2.5.1\\\",\\\"sinon\\\":\\\"^1.17.3\\\"},\\\"scripts\\\":{\\\"test\\\":\\\"node ./node_modules/gulp/bin/gulp.js test --verbose\\\",\\\"browserize\\\":\\\"./scripts/browserize.sh\\\",\\\"beautify\\\":\\\"node ./node_modules/gulp/bin/gulp.js beautify\\\"}}\");\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/aws-iot-device-sdk/package.json?");
|
|
674
825
|
|
|
675
826
|
/***/ }),
|
|
676
827
|
|
|
@@ -7274,6 +7425,17 @@ eval("var toString = {}.toString;\nmodule.exports = Array.isArray || function (a
|
|
|
7274
7425
|
|
|
7275
7426
|
/***/ }),
|
|
7276
7427
|
|
|
7428
|
+
/***/ "./node_modules/isomorphic-ws/browser.js":
|
|
7429
|
+
/*!***********************************************!*\
|
|
7430
|
+
!*** ./node_modules/isomorphic-ws/browser.js ***!
|
|
7431
|
+
\***********************************************/
|
|
7432
|
+
/*! no static exports found */
|
|
7433
|
+
/***/ (function(module, exports, __webpack_require__) {
|
|
7434
|
+
|
|
7435
|
+
eval("/* WEBPACK VAR INJECTION */(function(global) {// https://github.com/maxogden/websocket-stream/blob/48dc3ddf943e5ada668c31ccd94e9186f02fafbd/ws-fallback.js\n\nvar ws = null;\nif (typeof WebSocket !== 'undefined') {\n ws = WebSocket;\n} else if (typeof MozWebSocket !== 'undefined') {\n ws = MozWebSocket;\n} else if (typeof global !== 'undefined') {\n ws = global.WebSocket || global.MozWebSocket;\n} else if (typeof window !== 'undefined') {\n ws = window.WebSocket || window.MozWebSocket;\n} else if (typeof self !== 'undefined') {\n ws = self.WebSocket || self.MozWebSocket;\n}\nmodule.exports = ws;\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/isomorphic-ws/browser.js?");
|
|
7436
|
+
|
|
7437
|
+
/***/ }),
|
|
7438
|
+
|
|
7277
7439
|
/***/ "./node_modules/js-yaml/dist/js-yaml.mjs":
|
|
7278
7440
|
/*!***********************************************!*\
|
|
7279
7441
|
!*** ./node_modules/js-yaml/dist/js-yaml.mjs ***!
|
|
@@ -9958,168 +10120,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) *
|
|
|
9958
10120
|
|
|
9959
10121
|
/***/ }),
|
|
9960
10122
|
|
|
9961
|
-
/***/ "./node_modules/websocket-stream/node_modules/duplexify/index.js":
|
|
9962
|
-
/*!***********************************************************************!*\
|
|
9963
|
-
!*** ./node_modules/websocket-stream/node_modules/duplexify/index.js ***!
|
|
9964
|
-
\***********************************************************************/
|
|
9965
|
-
/*! no static exports found */
|
|
9966
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
9967
|
-
|
|
9968
|
-
eval("/* WEBPACK VAR INJECTION */(function(Buffer, process) {var stream = __webpack_require__(/*! readable-stream */ \"./node_modules/websocket-stream/node_modules/readable-stream/readable-browser.js\");\nvar eos = __webpack_require__(/*! end-of-stream */ \"./node_modules/end-of-stream/index.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar shift = __webpack_require__(/*! stream-shift */ \"./node_modules/stream-shift/index.js\");\nvar SIGNAL_FLUSH = Buffer.from && Buffer.from !== Uint8Array.from ? Buffer.from([0]) : new Buffer([0]);\nvar onuncork = function (self, fn) {\n if (self._corked) self.once('uncork', fn);else fn();\n};\nvar autoDestroy = function (self, err) {\n if (self._autoDestroy) self.destroy(err);\n};\nvar destroyer = function (self, end) {\n return function (err) {\n if (err) autoDestroy(self, err.message === 'premature close' ? null : err);else if (end && !self._ended) self.end();\n };\n};\nvar end = function (ws, fn) {\n if (!ws) return fn();\n if (ws._writableState && ws._writableState.finished) return fn();\n if (ws._writableState) return ws.end(fn);\n ws.end();\n fn();\n};\nvar toStreams2 = function (rs) {\n return new stream.Readable({\n objectMode: true,\n highWaterMark: 16\n }).wrap(rs);\n};\nvar Duplexify = function (writable, readable, opts) {\n if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts);\n stream.Duplex.call(this, opts);\n this._writable = null;\n this._readable = null;\n this._readable2 = null;\n this._autoDestroy = !opts || opts.autoDestroy !== false;\n this._forwardDestroy = !opts || opts.destroy !== false;\n this._forwardEnd = !opts || opts.end !== false;\n this._corked = 1; // start corked\n this._ondrain = null;\n this._drained = false;\n this._forwarding = false;\n this._unwrite = null;\n this._unread = null;\n this._ended = false;\n this.destroyed = false;\n if (writable) this.setWritable(writable);\n if (readable) this.setReadable(readable);\n};\ninherits(Duplexify, stream.Duplex);\nDuplexify.obj = function (writable, readable, opts) {\n if (!opts) opts = {};\n opts.objectMode = true;\n opts.highWaterMark = 16;\n return new Duplexify(writable, readable, opts);\n};\nDuplexify.prototype.cork = function () {\n if (++this._corked === 1) this.emit('cork');\n};\nDuplexify.prototype.uncork = function () {\n if (this._corked && --this._corked === 0) this.emit('uncork');\n};\nDuplexify.prototype.setWritable = function (writable) {\n if (this._unwrite) this._unwrite();\n if (this.destroyed) {\n if (writable && writable.destroy) writable.destroy();\n return;\n }\n if (writable === null || writable === false) {\n this.end();\n return;\n }\n var self = this;\n var unend = eos(writable, {\n writable: true,\n readable: false\n }, destroyer(this, this._forwardEnd));\n var ondrain = function () {\n var ondrain = self._ondrain;\n self._ondrain = null;\n if (ondrain) ondrain();\n };\n var clear = function () {\n self._writable.removeListener('drain', ondrain);\n unend();\n };\n if (this._unwrite) process.nextTick(ondrain); // force a drain on stream reset to avoid livelocks\n\n this._writable = writable;\n this._writable.on('drain', ondrain);\n this._unwrite = clear;\n this.uncork(); // always uncork setWritable\n};\nDuplexify.prototype.setReadable = function (readable) {\n if (this._unread) this._unread();\n if (this.destroyed) {\n if (readable && readable.destroy) readable.destroy();\n return;\n }\n if (readable === null || readable === false) {\n this.push(null);\n this.resume();\n return;\n }\n var self = this;\n var unend = eos(readable, {\n writable: false,\n readable: true\n }, destroyer(this));\n var onreadable = function () {\n self._forward();\n };\n var onend = function () {\n self.push(null);\n };\n var clear = function () {\n self._readable2.removeListener('readable', onreadable);\n self._readable2.removeListener('end', onend);\n unend();\n };\n this._drained = true;\n this._readable = readable;\n this._readable2 = readable._readableState ? readable : toStreams2(readable);\n this._readable2.on('readable', onreadable);\n this._readable2.on('end', onend);\n this._unread = clear;\n this._forward();\n};\nDuplexify.prototype._read = function () {\n this._drained = true;\n this._forward();\n};\nDuplexify.prototype._forward = function () {\n if (this._forwarding || !this._readable2 || !this._drained) return;\n this._forwarding = true;\n var data;\n while (this._drained && (data = shift(this._readable2)) !== null) {\n if (this.destroyed) continue;\n this._drained = this.push(data);\n }\n this._forwarding = false;\n};\nDuplexify.prototype.destroy = function (err) {\n if (this.destroyed) return;\n this.destroyed = true;\n var self = this;\n process.nextTick(function () {\n self._destroy(err);\n });\n};\nDuplexify.prototype._destroy = function (err) {\n if (err) {\n var ondrain = this._ondrain;\n this._ondrain = null;\n if (ondrain) ondrain(err);else this.emit('error', err);\n }\n if (this._forwardDestroy) {\n if (this._readable && this._readable.destroy) this._readable.destroy();\n if (this._writable && this._writable.destroy) this._writable.destroy();\n }\n this.emit('close');\n};\nDuplexify.prototype._write = function (data, enc, cb) {\n if (this.destroyed) return cb();\n if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb));\n if (data === SIGNAL_FLUSH) return this._finish(cb);\n if (!this._writable) return cb();\n if (this._writable.write(data) === false) this._ondrain = cb;else cb();\n};\nDuplexify.prototype._finish = function (cb) {\n var self = this;\n this.emit('preend');\n onuncork(this, function () {\n end(self._forwardEnd && self._writable, function () {\n // haxx to not emit prefinish twice\n if (self._writableState.prefinished === false) self._writableState.prefinished = true;\n self.emit('prefinish');\n onuncork(self, cb);\n });\n });\n};\nDuplexify.prototype.end = function (data, enc, cb) {\n if (typeof data === 'function') return this.end(null, null, data);\n if (typeof enc === 'function') return this.end(data, null, enc);\n this._ended = true;\n if (data) this.write(data);\n if (!this._writableState.ending) this.write(SIGNAL_FLUSH);\n return stream.Writable.prototype.end.call(this, cb);\n};\nmodule.exports = Duplexify;\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node-libs-browser/node_modules/buffer/index.js */ \"./node_modules/node-libs-browser/node_modules/buffer/index.js\").Buffer, __webpack_require__(/*! ./../../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/duplexify/index.js?");
|
|
9969
|
-
|
|
9970
|
-
/***/ }),
|
|
9971
|
-
|
|
9972
|
-
/***/ "./node_modules/websocket-stream/node_modules/isarray/index.js":
|
|
9973
|
-
/*!*********************************************************************!*\
|
|
9974
|
-
!*** ./node_modules/websocket-stream/node_modules/isarray/index.js ***!
|
|
9975
|
-
\*********************************************************************/
|
|
9976
|
-
/*! no static exports found */
|
|
9977
|
-
/***/ (function(module, exports) {
|
|
9978
|
-
|
|
9979
|
-
eval("var toString = {}.toString;\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/isarray/index.js?");
|
|
9980
|
-
|
|
9981
|
-
/***/ }),
|
|
9982
|
-
|
|
9983
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js":
|
|
9984
|
-
/*!******************************************************************************************!*\
|
|
9985
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js ***!
|
|
9986
|
-
\******************************************************************************************/
|
|
9987
|
-
/*! no static exports found */
|
|
9988
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
9989
|
-
|
|
9990
|
-
"use strict";
|
|
9991
|
-
eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }\n return keys;\n};\n/*</replacement>*/\n\nmodule.exports = Duplex;\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\nvar Readable = __webpack_require__(/*! ./_stream_readable */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js\");\nvar Writable = __webpack_require__(/*! ./_stream_writable */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js\");\nutil.inherits(Duplex, Readable);\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n if (options && options.readable === false) this.readable = false;\n if (options && options.writable === false) this.writable = false;\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n this.once('end', onend);\n}\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\nfunction onEndNT(self) {\n self.end();\n}\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n pna.nextTick(cb, err);\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js?");
|
|
9992
|
-
|
|
9993
|
-
/***/ }),
|
|
9994
|
-
|
|
9995
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js":
|
|
9996
|
-
/*!***********************************************************************************************!*\
|
|
9997
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js ***!
|
|
9998
|
-
\***********************************************************************************************/
|
|
9999
|
-
/*! no static exports found */
|
|
10000
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10001
|
-
|
|
10002
|
-
"use strict";
|
|
10003
|
-
eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n\n\nmodule.exports = PassThrough;\nvar Transform = __webpack_require__(/*! ./_stream_transform */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js\");\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\nutil.inherits(PassThrough, Transform);\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js?");
|
|
10004
|
-
|
|
10005
|
-
/***/ }),
|
|
10006
|
-
|
|
10007
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js":
|
|
10008
|
-
/*!********************************************************************************************!*\
|
|
10009
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js ***!
|
|
10010
|
-
\********************************************************************************************/
|
|
10011
|
-
/*! no static exports found */
|
|
10012
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10013
|
-
|
|
10014
|
-
"use strict";
|
|
10015
|
-
eval("/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\nmodule.exports = Readable;\n\n/*<replacement>*/\nvar isArray = __webpack_require__(/*! isarray */ \"./node_modules/websocket-stream/node_modules/isarray/index.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n\n/*<replacement>*/\nvar EE = __webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter;\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar debugUtil = __webpack_require__(/*! util */ 6);\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/*</replacement>*/\n\nvar BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js\");\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js\");\nvar StringDecoder;\nutil.inherits(Readable, Stream);\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\nfunction ReadableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ \"./node_modules/node-libs-browser/node_modules/string_decoder/lib/string_decoder.js\").StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\nfunction Readable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n if (!(this instanceof Readable)) return new Readable(options);\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n Stream.call(this);\n}\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n return needMoreData(state);\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ \"./node_modules/node-libs-browser/node_modules/string_decoder/lib/string_decoder.js\").StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n return dest;\n};\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n return this;\n};\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\"), __webpack_require__(/*! ./../../../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js?");
|
|
10016
|
-
|
|
10017
|
-
/***/ }),
|
|
10018
|
-
|
|
10019
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js":
|
|
10020
|
-
/*!*********************************************************************************************!*\
|
|
10021
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js ***!
|
|
10022
|
-
\*********************************************************************************************/
|
|
10023
|
-
/*! no static exports found */
|
|
10024
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10025
|
-
|
|
10026
|
-
"use strict";
|
|
10027
|
-
eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n\n\nmodule.exports = Transform;\nvar Duplex = __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\nutil.inherits(Transform, Duplex);\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null)\n // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\nfunction prefinish() {\n var _this = this;\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null)\n // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n return stream.push(null);\n}\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js?");
|
|
10028
|
-
|
|
10029
|
-
/***/ }),
|
|
10030
|
-
|
|
10031
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js":
|
|
10032
|
-
/*!********************************************************************************************!*\
|
|
10033
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js ***!
|
|
10034
|
-
\********************************************************************************************/
|
|
10035
|
-
/*! no static exports found */
|
|
10036
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10037
|
-
|
|
10038
|
-
"use strict";
|
|
10039
|
-
eval("/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\nmodule.exports = Writable;\n\n/* <replacement> */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n\n/*<replacement>*/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\nvar internalUtil = {\n deprecate: __webpack_require__(/*! util-deprecate */ \"./node_modules/util-deprecate/browser.js\")\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js\");\nutil.inherits(Writable, Stream);\nfunction nop() {}\nfunction WritableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\nfunction Writable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\nWritable.prototype.cork = function () {\n var state = this._writableState;\n state.corked++;\n};\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n return ret;\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n if (sync) {\n /*<replacement>*/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /*</replacement>*/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n if (entry === null) state.lastBufferedRequest = null;\n }\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\nWritable.prototype._writev = null;\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n};\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../process/browser.js */ \"./node_modules/process/browser.js\"), __webpack_require__(/*! ./../../../../timers-browserify/main.js */ \"./node_modules/timers-browserify/main.js\").setImmediate, __webpack_require__(/*! ./../../../../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js?");
|
|
10040
|
-
|
|
10041
|
-
/***/ }),
|
|
10042
|
-
|
|
10043
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js":
|
|
10044
|
-
/*!*******************************************************************************************************!*\
|
|
10045
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js ***!
|
|
10046
|
-
\*******************************************************************************************************/
|
|
10047
|
-
/*! no static exports found */
|
|
10048
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10049
|
-
|
|
10050
|
-
"use strict";
|
|
10051
|
-
eval("\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nvar util = __webpack_require__(/*! util */ 7);\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n BufferList.prototype.push = function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n BufferList.prototype.unshift = function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }\n return ret;\n };\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n return BufferList;\n}();\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({\n length: this.length\n });\n return this.constructor.name + ' ' + obj;\n };\n}\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/BufferList.js?");
|
|
10052
|
-
|
|
10053
|
-
/***/ }),
|
|
10054
|
-
|
|
10055
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js":
|
|
10056
|
-
/*!****************************************************************************************************!*\
|
|
10057
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js ***!
|
|
10058
|
-
\****************************************************************************************************/
|
|
10059
|
-
/*! no static exports found */
|
|
10060
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10061
|
-
|
|
10062
|
-
"use strict";
|
|
10063
|
-
eval("\n\n/*<replacement>*/\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/*</replacement>*/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n pna.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, this, err);\n }\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n pna.nextTick(emitErrorNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, _this, err);\n }\n } else if (cb) {\n cb(err);\n }\n });\n return this;\n}\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/destroy.js?");
|
|
10064
|
-
|
|
10065
|
-
/***/ }),
|
|
10066
|
-
|
|
10067
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js":
|
|
10068
|
-
/*!***********************************************************************************************************!*\
|
|
10069
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js ***!
|
|
10070
|
-
\***********************************************************************************************************/
|
|
10071
|
-
/*! no static exports found */
|
|
10072
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10073
|
-
|
|
10074
|
-
eval("module.exports = __webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter;\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/lib/internal/streams/stream-browser.js?");
|
|
10075
|
-
|
|
10076
|
-
/***/ }),
|
|
10077
|
-
|
|
10078
|
-
/***/ "./node_modules/websocket-stream/node_modules/readable-stream/readable-browser.js":
|
|
10079
|
-
/*!****************************************************************************************!*\
|
|
10080
|
-
!*** ./node_modules/websocket-stream/node_modules/readable-stream/readable-browser.js ***!
|
|
10081
|
-
\****************************************************************************************/
|
|
10082
|
-
/*! no static exports found */
|
|
10083
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10084
|
-
|
|
10085
|
-
eval("exports = module.exports = __webpack_require__(/*! ./lib/_stream_readable.js */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_readable.js\");\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = __webpack_require__(/*! ./lib/_stream_writable.js */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_writable.js\");\nexports.Duplex = __webpack_require__(/*! ./lib/_stream_duplex.js */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_duplex.js\");\nexports.Transform = __webpack_require__(/*! ./lib/_stream_transform.js */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_transform.js\");\nexports.PassThrough = __webpack_require__(/*! ./lib/_stream_passthrough.js */ \"./node_modules/websocket-stream/node_modules/readable-stream/lib/_stream_passthrough.js\");\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/readable-stream/readable-browser.js?");
|
|
10086
|
-
|
|
10087
|
-
/***/ }),
|
|
10088
|
-
|
|
10089
|
-
/***/ "./node_modules/websocket-stream/node_modules/safe-buffer/index.js":
|
|
10090
|
-
/*!*************************************************************************!*\
|
|
10091
|
-
!*** ./node_modules/websocket-stream/node_modules/safe-buffer/index.js ***!
|
|
10092
|
-
\*************************************************************************/
|
|
10093
|
-
/*! no static exports found */
|
|
10094
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10095
|
-
|
|
10096
|
-
eval("/* eslint-disable node/no-deprecated-api */\nvar buffer = __webpack_require__(/*! buffer */ \"./node_modules/node-libs-browser/node_modules/buffer/index.js\");\nvar Buffer = buffer.Buffer;\n\n// alternative to using Object.keys for old browsers\nfunction copyProps(src, dst) {\n for (var key in src) {\n dst[key] = src[key];\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer;\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports);\n exports.Buffer = SafeBuffer;\n}\nfunction SafeBuffer(arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length);\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer);\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number');\n }\n return Buffer(arg, encodingOrOffset, length);\n};\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number');\n }\n var buf = Buffer(size);\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding);\n } else {\n buf.fill(fill);\n }\n } else {\n buf.fill(0);\n }\n return buf;\n};\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number');\n }\n return Buffer(size);\n};\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number');\n }\n return buffer.SlowBuffer(size);\n};\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/node_modules/safe-buffer/index.js?");
|
|
10097
|
-
|
|
10098
|
-
/***/ }),
|
|
10099
|
-
|
|
10100
|
-
/***/ "./node_modules/websocket-stream/stream.js":
|
|
10101
|
-
/*!*************************************************!*\
|
|
10102
|
-
!*** ./node_modules/websocket-stream/stream.js ***!
|
|
10103
|
-
\*************************************************/
|
|
10104
|
-
/*! no static exports found */
|
|
10105
|
-
/***/ (function(module, exports, __webpack_require__) {
|
|
10106
|
-
|
|
10107
|
-
"use strict";
|
|
10108
|
-
eval("/* WEBPACK VAR INJECTION */(function(process, global) {\n\nvar Transform = __webpack_require__(/*! readable-stream */ \"./node_modules/websocket-stream/node_modules/readable-stream/readable-browser.js\").Transform;\nvar duplexify = __webpack_require__(/*! duplexify */ \"./node_modules/websocket-stream/node_modules/duplexify/index.js\");\nvar WS = __webpack_require__(/*! ws */ \"./node_modules/websocket-stream/ws-fallback.js\");\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/websocket-stream/node_modules/safe-buffer/index.js\").Buffer;\nmodule.exports = WebSocketStream;\nfunction buildProxy(options, socketWrite, socketEnd) {\n var proxy = new Transform({\n objectMode: options.objectMode\n });\n proxy._write = socketWrite;\n proxy._flush = socketEnd;\n return proxy;\n}\nfunction WebSocketStream(target, protocols, options) {\n var stream, socket;\n var isBrowser = process.title === 'browser';\n var isNative = !!global.WebSocket;\n var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode;\n if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {\n // accept the \"options\" Object as the 2nd argument\n options = protocols;\n protocols = null;\n if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {\n protocols = options.protocol;\n }\n }\n if (!options) options = {};\n if (options.objectMode === undefined) {\n options.objectMode = !(options.binary === true || options.binary === undefined);\n }\n var proxy = buildProxy(options, socketWrite, socketEnd);\n if (!options.objectMode) {\n proxy._writev = writev;\n }\n\n // browser only: sets the maximum socket buffer size before throttling\n var bufferSize = options.browserBufferSize || 1024 * 512;\n\n // browser only: how long to wait when throttling\n var bufferTimeout = options.browserBufferTimeout || 1000;\n\n // use existing WebSocket object that was passed in\n if (typeof target === 'object') {\n socket = target;\n // otherwise make a new one\n } else {\n // special constructor treatment for native websockets in browsers, see\n // https://github.com/maxogden/websocket-stream/issues/82\n if (isNative && isBrowser) {\n socket = new WS(target, protocols);\n } else {\n socket = new WS(target, protocols, options);\n }\n socket.binaryType = 'arraybuffer';\n }\n\n // according to https://github.com/baygeldin/ws-streamify/issues/1\n // Nodejs WebSocketServer cause memory leak\n // Handlers like onerror, onclose, onmessage and onopen are accessible via setter/getter\n // And setter first of all fires removeAllListeners, that doesnt make inner array of clients on WebSocketServer cleared ever\n var eventListenerSupport = 'undefined' === typeof socket.addEventListener;\n\n // was already open when passed in\n if (socket.readyState === socket.OPEN) {\n stream = proxy;\n } else {\n stream = stream = duplexify(undefined, undefined, options);\n if (!options.objectMode) {\n stream._writev = writev;\n }\n if (eventListenerSupport) {\n socket.addEventListener('open', onopen);\n } else {\n socket.onopen = onopen;\n }\n }\n stream.socket = socket;\n if (eventListenerSupport) {\n socket.addEventListener('close', onclose);\n socket.addEventListener('error', onerror);\n socket.addEventListener('message', onmessage);\n } else {\n socket.onclose = onclose;\n socket.onerror = onerror;\n socket.onmessage = onmessage;\n }\n proxy.on('close', destroy);\n var coerceToBuffer = !options.objectMode;\n function socketWriteNode(chunk, enc, next) {\n // avoid errors, this never happens unless\n // destroy() is called\n if (socket.readyState !== socket.OPEN) {\n next();\n return;\n }\n if (coerceToBuffer && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, 'utf8');\n }\n socket.send(chunk, next);\n }\n function socketWriteBrowser(chunk, enc, next) {\n if (socket.bufferedAmount > bufferSize) {\n setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next);\n return;\n }\n if (coerceToBuffer && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, 'utf8');\n }\n try {\n socket.send(chunk);\n } catch (err) {\n return next(err);\n }\n next();\n }\n function socketEnd(done) {\n socket.close();\n done();\n }\n function onopen() {\n stream.setReadable(proxy);\n stream.setWritable(proxy);\n stream.emit('connect');\n }\n function onclose() {\n stream.end();\n stream.destroy();\n }\n function onerror(err) {\n stream.destroy(err);\n }\n function onmessage(event) {\n var data = event.data;\n if (data instanceof ArrayBuffer) data = Buffer.from(data);else data = Buffer.from(data, 'utf8');\n proxy.push(data);\n }\n function destroy() {\n socket.close();\n }\n\n // this is to be enabled only if objectMode is false\n function writev(chunks, cb) {\n var buffers = new Array(chunks.length);\n for (var i = 0; i < chunks.length; i++) {\n if (typeof chunks[i].chunk === 'string') {\n buffers[i] = Buffer.from(chunks[i], 'utf8');\n } else {\n buffers[i] = chunks[i].chunk;\n }\n }\n this._write(Buffer.concat(buffers), 'binary', cb);\n }\n return stream;\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ \"./node_modules/process/browser.js\"), __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/stream.js?");
|
|
10109
|
-
|
|
10110
|
-
/***/ }),
|
|
10111
|
-
|
|
10112
|
-
/***/ "./node_modules/websocket-stream/ws-fallback.js":
|
|
10113
|
-
/*!******************************************************!*\
|
|
10114
|
-
!*** ./node_modules/websocket-stream/ws-fallback.js ***!
|
|
10115
|
-
\******************************************************/
|
|
10116
|
-
/*! no static exports found */
|
|
10117
|
-
/***/ (function(module, exports) {
|
|
10118
|
-
|
|
10119
|
-
eval("var ws = null;\nif (typeof WebSocket !== 'undefined') {\n ws = WebSocket;\n} else if (typeof MozWebSocket !== 'undefined') {\n ws = MozWebSocket;\n} else if (typeof window !== 'undefined') {\n ws = window.WebSocket || window.MozWebSocket;\n}\nmodule.exports = ws;\n\n//# sourceURL=webpack://WatchTogetherSDK/./node_modules/websocket-stream/ws-fallback.js?");
|
|
10120
|
-
|
|
10121
|
-
/***/ }),
|
|
10122
|
-
|
|
10123
10123
|
/***/ "./node_modules/which-typed-array/index.js":
|
|
10124
10124
|
/*!*************************************************!*\
|
|
10125
10125
|
!*** ./node_modules/which-typed-array/index.js ***!
|
|
@@ -10510,7 +10510,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var aws_
|
|
|
10510
10510
|
/***/ (function(module, __webpack_exports__, __webpack_require__) {
|
|
10511
10511
|
|
|
10512
10512
|
"use strict";
|
|
10513
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webrtc-adapter */ \"./node_modules/webrtc-adapter/src/js/adapter_core.js\");\n/* harmony import */ var _wt_emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./wt-emitter */ \"./src/modules/wt-emitter.js\");\n/* harmony import */ var _wt_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./wt-utils */ \"./src/modules/wt-utils.js\");\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n// Watch together janus webrtc library\n\n\n\n\nclass Room {\n constructor(debug) {\n this.debug = debug;\n this.sessions = [];\n this.safariVp8 = false;\n this.browser = webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser;\n this.browserDetails = webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails;\n this.webrtcSupported = Room.isWebrtcSupported();\n this.safariVp8TestPromise = Room.testSafariVp8();\n this.safariVp8 = null;\n this.safariVp8TestPromise.then(safariVp8 => {\n this.safariVp8 = safariVp8;\n });\n\n // Let's get it started\n this.whenInitialized = this.initialize();\n }\n initialize() {\n return this.safariVp8TestPromise.then(() => this);\n }\n createSession() {\n let constructId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'reactooroom';\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return new RoomSession(constructId, type, {\n debug: this.debug,\n ...options\n });\n }\n static testSafariVp8() {\n return new Promise(resolve => {\n if (webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser === 'safari' && webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.version >= 605) {\n if (RTCRtpSender && RTCRtpSender.getCapabilities && RTCRtpSender.getCapabilities(\"video\") && RTCRtpSender.getCapabilities(\"video\").codecs && RTCRtpSender.getCapabilities(\"video\").codecs.length) {\n var isVp8 = false;\n for (var i in RTCRtpSender.getCapabilities(\"video\").codecs) {\n var codec = RTCRtpSender.getCapabilities(\"video\").codecs[i];\n if (codec && codec.mimeType && codec.mimeType.toLowerCase() === \"video/vp8\") {\n isVp8 = true;\n break;\n }\n }\n resolve(isVp8);\n } else {\n // We do it in a very ugly way, as there's no alternative...\n // We create a PeerConnection to see if VP8 is in an offer\n var testpc = new RTCPeerConnection({}, {});\n testpc.createOffer({\n offerToReceiveVideo: true\n }).then(function (offer) {\n let result = offer.sdp.indexOf(\"VP8\") !== -1;\n testpc.close();\n testpc = null;\n resolve(result);\n });\n }\n } else resolve(false);\n });\n }\n static isWebrtcSupported() {\n return window.RTCPeerConnection !== undefined && window.RTCPeerConnection !== null && navigator.mediaDevices !== undefined && navigator.mediaDevices !== null && navigator.mediaDevices.getUserMedia !== undefined && navigator.mediaDevices.getUserMedia !== null;\n }\n}\nclass RoomSession {\n static noop() {}\n static randomString(len) {\n var charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var randomString = '';\n for (var i = 0; i < len; i++) {\n var randomPoz = Math.floor(Math.random() * charSet.length);\n randomString += charSet.substring(randomPoz, randomPoz + 1);\n }\n return randomString;\n }\n constructor() {\n let constructId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'reactooroom';\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n _defineProperty(this, \"_intercomSubscribe\", stream => {\n var _JSON$parse;\n if (stream.type === 'data') {\n return true;\n }\n const intercomGroups = ((_JSON$parse = JSON.parse(stream.description || \"[]\")) === null || _JSON$parse === void 0 ? void 0 : _JSON$parse.intercomGroups) || [];\n return intercomGroups.some(g => this._listenIntercomChannels.indexOf(g) > -1);\n });\n Object.assign(this, Object(_wt_emitter__WEBPACK_IMPORTED_MODULE_1__[\"default\"])());\n this.options = {\n ...options\n };\n this.defaultDataChannelLabel = 'JanusDataChannel';\n this.server = null;\n this.iceServers = null;\n this.token = null;\n this.roomId = null;\n this.streamId = null;\n this.pin = null;\n this.userId = null;\n this.sessiontype = type;\n this.initialBitrate = 0;\n this.enableDtx = false;\n this.simulcast = false;\n this.defaultSimulcastSettings = {\n \"default\": {\n mode: \"controlled\",\n // controlled, manual, browserControlled\n defaultSubstream: 0,\n // 2 lowest quality, 0 highest quality\n bitrates: [{\n \"rid\": \"l\",\n \"active\": true,\n \"maxBitrate\": 180000,\n \"maxFramerate\": 20,\n \"scaleResolutionDownBy\": 3.3333333333333335,\n \"priority\": \"low\"\n }, {\n \"rid\": \"m\",\n \"active\": true,\n \"maxBitrate\": 500000,\n \"maxFramerate\": 25,\n \"scaleResolutionDownBy\": 1.3333333333333335,\n \"priority\": \"low\"\n }, {\n \"rid\": \"h\",\n \"active\": true,\n \"maxBitrate\": 2000000,\n \"maxFramerate\": 30,\n \"priority\": \"low\"\n }]\n }\n };\n this.recordingFilename = null;\n this.pluginName = RoomSession.sessionTypes[type];\n this.id = null;\n this.privateId = null;\n this.constructId = constructId || RoomSession.randomString(16);\n this.sessionId = null;\n this.handleId = null;\n this.ws = null;\n this.isRestarting = false;\n this.isConnecting = false;\n this.isDisconnecting = false;\n this.isConnected = false;\n this.isPublished = false;\n this.isReclaiming = false;\n this.isStreaming = false;\n this.isMuted = [];\n this.isVideoEnabled = false;\n this.isAudioEnabed = false;\n this._statsMaxLength = 31;\n this._upStatsLength = 30;\n this._downStatsLength = 5;\n this._statsTimeoutStopped = true;\n this._statsTimeoutId = null;\n this._statsInterval = 1000;\n this._aqInterval = 2500;\n this._aqIntervalCounter = 0;\n this._aqIntervalDivisor = 4;\n this._aqTimeoutId = null;\n this._sendMessageTimeout = 5000;\n this._retries = 0;\n this._maxRetries = 5;\n this._keepAliveId = null;\n this._participants = [];\n this._restrictSubscribeToUserIds = []; // all if empty\n this._talkIntercomChannels = ['participants'];\n this._listenIntercomChannels = ['participants'];\n this._roomType = 'watchparty';\n this._isDataChannelOpen = false;\n this._abortController = null;\n this._remoteUsersCache = [];\n this.userRoleSubscriptionRules = {\n ...RoomSession.userRoleSubscriptionRules,\n ...(this.options.userRoleSubscriptionRules || {})\n };\n this._log = RoomSession.noop;\n if (this.options.debug) {\n this._enableDebug();\n }\n }\n _pushToRemoteUsersCache(userId, streams, id) {\n const existingIndex = this._remoteUsersCache.findIndex(u => u.userId === userId);\n if (existingIndex > -1) {\n this._remoteUsersCache.splice(existingIndex, 1, {\n userId,\n streams,\n id\n });\n } else {\n this._remoteUsersCache.push({\n userId,\n streams,\n id\n });\n }\n }\n _removeFromRemoteUsersCache(rfid) {\n const existingIndex = this._remoteUsersCache.findIndex(u => u.id === rfid);\n if (existingIndex > -1) {\n this._remoteUsersCache.splice(existingIndex, 1);\n }\n }\n _participantShouldSubscribe(userId) {\n const myUser = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display);\n const remoteUser = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(userId);\n let localUserRole = (myUser === null || myUser === void 0 ? void 0 : myUser.role) || 'participant';\n let remoteUserRole = (remoteUser === null || remoteUser === void 0 ? void 0 : remoteUser.role) || 'participant';\n return this.userRoleSubscriptionRules[localUserRole][this._roomType || 'watchparty'].indexOf(remoteUserRole) > -1 && (this._restrictSubscribeToUserIds.length === 0 || this._restrictSubscribeToUserIds.indexOf(remoteUser === null || remoteUser === void 0 ? void 0 : remoteUser.userId) > -1);\n }\n _getAddParticipantEventName(handleId) {\n var _decodeJanusDisplay;\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'getParticipantEventName']\n });\n return;\n }\n const participantRole = (_decodeJanusDisplay = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay === void 0 ? void 0 : _decodeJanusDisplay.role;\n switch (participantRole) {\n case 'participant':\n return 'addRemoteParticipant';\n case 'talkback':\n return 'addRemoteTalkback';\n case 'monitor':\n return 'addRemoteTalkback';\n case 'observer':\n case 'observerSolo1':\n case 'observerSolo2':\n case 'observerSolo3':\n return 'addRemoteObserver';\n case 'host':\n return 'addRemoteInstructor';\n case 'companionTV':\n return 'addRemoteCompanionTV';\n case 'companionPhone':\n return 'addRemoteCompanionPhone';\n default:\n return 'addRemoteParticipant';\n }\n }\n _getRemoveParticipantEventName(handleId) {\n var _decodeJanusDisplay2;\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'getParticipantEventName']\n });\n return;\n }\n const participantRole = (_decodeJanusDisplay2 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay2 === void 0 ? void 0 : _decodeJanusDisplay2.role;\n switch (participantRole) {\n case 'participant':\n return 'removeRemoteParticipant';\n case 'talkback':\n return 'removeRemoteTalkback';\n case 'monitor':\n return 'removeRemoteTalkback';\n case 'observer':\n case 'observerSolo1':\n case 'observerSolo2':\n case 'observerSolo3':\n return 'removeRemoteObserver';\n case 'host':\n return 'removeRemoteInstructor';\n case 'companionTV':\n return 'removeRemoteCompanionTV';\n case 'companionPhone':\n return 'removeRemoteCompanionPhone';\n default:\n return 'removeRemoteParticipant';\n }\n }\n sendMessage(handleId) {\n let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n body: 'Example Body'\n };\n let dontWait = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n let dontResolveOnAck = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n let retry = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;\n return this._send({\n \"janus\": \"message\",\n \"handle_id\": handleId,\n ...message\n }, dontWait, dontResolveOnAck, retry).then(json => {\n if (json && json[\"janus\"] === \"success\") {\n let plugindata = json[\"plugindata\"] || {};\n let data = plugindata[\"data\"];\n return Promise.resolve(data);\n }\n return Promise.resolve();\n }).catch(json => {\n if (json && json[\"error\"]) {\n return Promise.reject({\n type: 'warning',\n id: 1,\n message: 'sendMessage failed',\n data: json[\"error\"]\n });\n } else {\n return Promise.reject({\n type: 'warning',\n id: 1,\n message: 'sendMessage failed',\n data: json\n });\n }\n });\n }\n _send() {\n let request = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let ignoreResponse = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n let dontResolveOnAck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n let retry = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n let transaction = RoomSession.randomString(12);\n let requestData = {\n ...request,\n transaction,\n token: this.token,\n ...(this.sessionId && {\n 'session_id': this.sessionId\n } || {})\n };\n this._log(requestData);\n const op = () => new Promise((resolve, reject) => {\n let messageTimeoutId = null;\n let abortResponse = () => {\n this._abortController.signal.removeEventListener('abort', abortResponse);\n clearTimeout(messageTimeoutId);\n this.ws.removeEventListener('message', parseResponse);\n reject({\n type: 'warning',\n id: 17,\n message: 'connection cancelled'\n });\n };\n let parseResponse = event => {\n let json = JSON.parse(event.data);\n let r_transaction = json['transaction'];\n if (r_transaction === transaction && (!dontResolveOnAck || json['janus'] !== 'ack')) {\n clearTimeout(messageTimeoutId);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n if (json['janus'] === 'error') {\n var _json$error;\n if ((json === null || json === void 0 ? void 0 : (_json$error = json.error) === null || _json$error === void 0 ? void 0 : _json$error.code) == 403) {\n this.disconnect(true);\n }\n reject({\n type: 'error',\n id: 2,\n message: 'send failed',\n data: json,\n requestData\n });\n } else {\n resolve(json);\n }\n }\n };\n if (ignoreResponse) {\n if (this.ws && this.ws.readyState === 1) {\n this.ws.send(JSON.stringify(requestData));\n }\n resolve();\n } else {\n if (this.ws && this.ws.readyState === 1) {\n this.ws.addEventListener('message', parseResponse);\n messageTimeoutId = setTimeout(() => {\n this.ws.removeEventListener('message', parseResponse);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n reject({\n type: 'warning',\n id: 3,\n message: 'send timeout',\n data: requestData\n });\n }, this._sendMessageTimeout);\n this._abortController.signal.addEventListener('abort', abortResponse);\n this.ws.send(JSON.stringify(requestData));\n } else {\n reject({\n type: 'warning',\n id: 29,\n message: 'No connection to WebSockets',\n data: requestData\n });\n }\n }\n });\n return op().catch(e => {\n if (e.id === 17) {\n return Promise.reject(e);\n } else if (e.id === 29 && retry > 0) {\n return Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"wait\"])(this._sendMessageTimeout).then(() => this._send(request, ignoreResponse, dontResolveOnAck, retry - 1));\n } else if (retry > 0) {\n return this._send(request, ignoreResponse, dontResolveOnAck, retry - 1);\n } else {\n return Promise.reject(e);\n }\n });\n }\n _connectionClosed() {\n if (!this.isConnected || this.isConnecting || this.isDisconnecting) {\n return;\n }\n if (this._retries < this._maxRetries) {\n setTimeout(() => {\n this._retries++;\n this._reconnect().catch(e => {\n this.emit('error', e);\n });\n }, 3000 * this._retries);\n } else {\n if (this.sessiontype === 'reactooroom') {\n this.disconnect(true);\n } else if (this.sessiontype === 'streaming') {\n this.stopStream();\n }\n this.emit('error', {\n type: 'error',\n id: 4,\n message: 'Lost connection to WebSockets',\n data: null\n });\n }\n }\n _wipeListeners() {\n if (this.ws) {\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n }\n }\n _startKeepAlive() {\n this._send({\n \"janus\": \"keepalive\"\n }).then(json => {\n if (json[\"janus\"] !== 'ack') {\n this.emit('error', {\n type: 'warning',\n id: 5,\n message: 'keepalive response suspicious',\n data: json[\"janus\"]\n });\n }\n }).catch(e => {\n this.emit('error', {\n type: 'warning',\n id: 6,\n message: 'keepalive dead',\n data: e\n });\n this._connectionClosed();\n });\n this._keepAliveId = setTimeout(() => {\n this._startKeepAlive();\n }, 10000);\n }\n _stopKeepAlive() {\n clearTimeout(this._keepAliveId);\n }\n _handleWsEvents(event) {\n let json = JSON.parse(event.data);\n var sender = json[\"sender\"];\n var type = json[\"janus\"];\n let handle = this._getHandle(sender);\n if (!handle) {\n return;\n }\n if (type === \"trickle\") {\n let candidate = json[\"candidate\"];\n let config = handle.webrtcStuff;\n if (config.pc && config.remoteSdp) {\n if (!candidate || candidate.completed === true) {\n config.pc.addIceCandidate(null);\n } else {\n config.pc.addIceCandidate(candidate);\n }\n } else {\n if (!config.candidates) {\n config.candidates = [];\n }\n config.candidates.push(candidate);\n }\n } else if (type === \"webrtcup\") {\n //none universal\n } else if (type === \"hangup\") {\n this._log('hangup on', handle.handleId, handle.handleId === this.handleId, json);\n this._removeParticipant(handle.handleId, null, false);\n } else if (type === \"detached\") {\n this._log('detached on', handle.handleId, handle.handleId === this.handleId, json);\n this._removeParticipant(handle.handleId, null, true);\n } else if (type === \"media\") {\n this._log('Media event:', handle.handleId, json[\"type\"], json[\"receiving\"], json[\"mid\"]);\n } else if (type === \"slowlink\") {\n this._log('Slowlink', handle.handleId, json[\"uplink\"], json[\"lost\"], json[\"mid\"]);\n } else if (type === \"event\") {\n //none universal\n } else if (type === 'timeout') {\n this._log('WebSockets Gateway timeout', json);\n this.ws.close(3504, \"Gateway timeout\");\n } else if (type === 'success' || type === 'error') {\n // we're capturing those elsewhere\n } else {\n this._log(`Unknown event: ${type} on session: ${this.sessionId}`);\n }\n\n // LOCAL\n\n if (sender === this.handleId) {\n if (type === \"event\") {\n var plugindata = json[\"plugindata\"] || {};\n var msg = plugindata[\"data\"] || {};\n var jsep = json[\"jsep\"];\n let result = msg[\"result\"] || null;\n let event = msg[\"videoroom\"] || null;\n let list = msg[\"publishers\"] || {};\n let leaving = msg[\"leaving\"];\n let kicked = msg[\"kicked\"];\n let substream = msg[\"substream\"];\n let temporal = msg[\"temporal\"];\n\n //let joining = msg[\"joining\"];\n let unpublished = msg[\"unpublished\"];\n let error = msg[\"error\"];\n if (event === \"joined\") {\n var _decodeJanusDisplay3, _decodeJanusDisplay4;\n this.id = msg[\"id\"];\n this.privateId = msg[\"private_id\"];\n this.isConnected = true;\n this._log('We have successfully joined Room');\n this.emit('joined', true, this.constructId);\n this.emit('addLocalParticipant', {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay3 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay3 === void 0 ? void 0 : _decodeJanusDisplay3.userId,\n role: (_decodeJanusDisplay4 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display)) === null || _decodeJanusDisplay4 === void 0 ? void 0 : _decodeJanusDisplay4.role,\n track: null,\n stream: null,\n streamMap: {},\n source: null,\n adding: false,\n removing: false,\n hasAudioTrack: false,\n hasVideoTrack: false\n });\n for (let f in list) {\n let userId = list[f][\"display\"];\n let streams = list[f][\"streams\"] || [];\n let id = list[f][\"id\"];\n for (let i in streams) {\n streams[i][\"id\"] = id;\n streams[i][\"display\"] = userId;\n }\n this._log('Remote userId: ', userId);\n this._pushToRemoteUsersCache(userId, streams, id);\n if (this._participantShouldSubscribe(userId)) {\n this._log('Creating user: ', userId);\n this._createParticipant(userId, id).then(handle => {\n this._updateParticipantsTrackData(handle.handleId, streams);\n const subscribe = streams.filter(s => !s.disabled && this._intercomSubscribe(s)).map(stream => ({\n feed: stream.id,\n mid: stream.mid\n }));\n handle.webrtcStuff.subscribeMap = structuredClone(subscribe);\n return this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": this.roomId,\n \"ptype\": \"subscriber\",\n \"private_id\": this.privateId,\n streams: subscribe,\n //\"feed\": id,\n ...(this.webrtcVersion > 1000 ? {\n id: this.userId\n } : {}),\n pin: this.pin\n }\n });\n }).catch(err => {\n this.emit('error', err);\n });\n }\n }\n } else if (event === \"event\") {\n if (substream !== undefined && substream !== null) {\n this._log('Substream event:', substream, sender);\n }\n if (temporal !== undefined && temporal !== null) {\n this._log('Temporal event:', temporal);\n }\n if (msg[\"streams\"] !== undefined && msg[\"streams\"] !== null) {\n this._log('Got my own streams back', msg[\"streams\"]);\n }\n for (let f in list) {\n let userId = list[f][\"display\"];\n let streams = list[f][\"streams\"] || [];\n let id = list[f][\"id\"];\n for (let i in streams) {\n streams[i][\"id\"] = id;\n streams[i][\"display\"] = userId;\n }\n this._log('Remote userId: ', userId);\n this._pushToRemoteUsersCache(userId, streams, id);\n if (this._participantShouldSubscribe(userId)) {\n let handle = this._getHandle(null, id);\n if (handle) {\n this._updateParticipantsTrackData(handle.handleId, streams);\n let subscribe = streams.filter(stream => !stream.disabled && this._intercomSubscribe(stream) && !this._isAlreadySubscribed(handle.handleId, stream.id, stream.mid)).map(s => ({\n feed: s.id,\n mid: s.mid\n }));\n let unsubscribe = streams.filter(stream => stream.disabled || !this._intercomSubscribe(stream)).map(s => ({\n feed: s.id,\n mid: s.mid\n }));\n this._updateSubscribeMap(handle.handleId, subscribe, unsubscribe);\n this._log('Already subscribed to user: ', userId, 'Update streams', subscribe, unsubscribe);\n if (subscribe.length || unsubscribe.length) {\n this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"update\",\n ...(subscribe.length ? {\n subscribe\n } : {}),\n ...(unsubscribe.length ? {\n unsubscribe\n } : {})\n }\n });\n }\n } else {\n this._log('Creating user: ', userId, streams);\n this._createParticipant(userId, id).then(handle => {\n this._updateParticipantsTrackData(handle.handleId, streams);\n const subscribe = streams.filter(s => !s.disabled && this._intercomSubscribe(s)).map(stream => ({\n feed: stream.id,\n mid: stream.mid\n }));\n handle.webrtcStuff.subscribeMap = structuredClone(subscribe);\n return this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": this.roomId,\n \"ptype\": \"subscriber\",\n \"private_id\": this.privateId,\n streams: subscribe,\n ...(this.webrtcVersion > 1000 ? {\n id: this.userId\n } : {}),\n pin: this.pin\n }\n });\n }).catch(err => {\n this.emit('error', err);\n });\n }\n }\n }\n if (leaving === 'ok') {\n this._log('leaving', this.handleId, 'this is us');\n this._removeParticipant(this.handleId);\n if (msg['reason'] === 'kicked') {\n this.emit('kicked');\n this.disconnect().catch(() => {});\n }\n } else if (leaving) {\n //TODO: in 1 PeerConnection case we only unsubscribe from streams, this may not be true, check janus docs\n this._log('leaving', leaving);\n this._removeFromRemoteUsersCache(leaving);\n this._removeParticipant(null, leaving, true);\n }\n if (unpublished === 'ok') {\n this._log('unpublished', this.handleId, 'this is us');\n this._removeParticipant(this.handleId, null, false); // we do just hangup\n } else if (unpublished) {\n //TODO: in 1 PeerConnection case we only unsubscribe from streams\n this._log('unpublished', unpublished);\n this._removeFromRemoteUsersCache(unpublished);\n this._removeParticipant(null, unpublished, true); // we do hangup and detach\n }\n if (kicked === 'ok') {\n // this case shouldn't exist\n } else if (kicked) {\n this._log('kicked', kicked);\n this._removeFromRemoteUsersCache(kicked);\n this._removeParticipant(null, kicked, true); // we do hangup and detach\n }\n if (error) {\n this.emit('error', {\n type: 'error',\n id: 7,\n message: 'local participant error',\n data: [sender, msg]\n });\n }\n }\n\n // Streaming related\n else if (result && result[\"status\"]) {\n this.emit('streamingStatus', result[\"status\"]);\n if (result[\"status\"] === 'stopped') {\n this.stopStream();\n }\n if (result[\"status\"] === 'started') {\n this.emit('streaming', true);\n this.isStreaming = true;\n }\n }\n if (jsep !== undefined && jsep !== null) {\n if (this.sessiontype === 'reactooroom') {\n this._webrtcPeer(this.handleId, jsep).catch(err => {\n this.emit('error', err);\n });\n } else if (this.sessiontype === 'streaming') {\n this._publishRemote(this.handleId, jsep).catch(err => {\n this.emit('error', err);\n });\n }\n }\n } else if (type === \"webrtcup\") {\n if (this.simulcast) {\n return;\n }\n this._log('Configuring bitrate: ' + this.initialBitrate);\n if (this.initialBitrate > 0) {\n this.sendMessage(this.handleId, {\n \"body\": {\n \"request\": \"configure\",\n \"bitrate\": this.initialBitrate\n }\n }).catch(() => null);\n }\n }\n }\n\n //REMOTE\n else {\n let plugindata = json[\"plugindata\"] || {};\n let msg = plugindata[\"data\"] || {};\n let jsep = json[\"jsep\"];\n let event = msg[\"videoroom\"];\n let error = msg[\"error\"];\n let substream = msg[\"substream\"];\n let mid = msg[\"mid\"];\n let temporal = msg[\"temporal\"];\n if (substream !== undefined && substream !== null) {\n this._log('Substream: ', sender, mid, substream);\n this._setSelectedSubstream(sender, mid, substream);\n this._resetStats(sender, mid);\n this.requestKeyFrame(sender, mid);\n }\n if (temporal !== undefined && temporal !== null) {\n this._log('Temporal: ', temporal);\n }\n if (type === \"webrtcup\") {\n this.requestKeyFrame(handle.handleId);\n }\n if (event === \"updated\") {\n this._log('Remote has updated tracks', msg);\n if (msg[\"streams\"]) {\n this._updateTransceiverMap(handle.handleId, msg[\"streams\"]);\n }\n }\n if (event === \"attached\") {\n var _decodeJanusDisplay5, _decodeJanusDisplay6, _handle$webrtcStuff, _handle$webrtcStuff2, _handle$webrtcStuff3;\n this._log('Remote have successfully joined Room', msg);\n if (msg[\"streams\"]) {\n this._updateTransceiverMap(handle.handleId, msg[\"streams\"] || []);\n }\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay5 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay5 === void 0 ? void 0 : _decodeJanusDisplay5.userId,\n role: (_decodeJanusDisplay6 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay6 === void 0 ? void 0 : _decodeJanusDisplay6.role,\n stream: null,\n streamMap: structuredClone((_handle$webrtcStuff = handle.webrtcStuff) === null || _handle$webrtcStuff === void 0 ? void 0 : _handle$webrtcStuff.streamMap),\n tracksMap: structuredClone((_handle$webrtcStuff2 = handle.webrtcStuff) === null || _handle$webrtcStuff2 === void 0 ? void 0 : _handle$webrtcStuff2.tracksMap),\n transceiverMap: structuredClone((_handle$webrtcStuff3 = handle.webrtcStuff) === null || _handle$webrtcStuff3 === void 0 ? void 0 : _handle$webrtcStuff3.transceiverMap),\n source: null,\n track: null,\n adding: false,\n removing: false,\n constructId: this.constructId,\n hasAudioTrack: false,\n hasVideoTrack: false\n });\n }\n if (error) {\n this.emit('error', {\n type: 'warning',\n id: 8,\n message: 'remote participant error',\n data: [sender, msg]\n });\n }\n if (jsep) {\n this._publishRemote(handle.handleId, jsep).catch(err => {\n this.emit('error', err);\n });\n }\n }\n }\n _handleDataEvents(handleId, type, data) {\n let handle = this._getHandle(handleId);\n if (type === 'state') {\n this._log(` - Data channel status - `, `UID: ${handleId}`, `STATUS: ${JSON.stringify(data)}`, `ME: ${handleId === this.handleId}`);\n if (handle) {\n let config = handle.webrtcStuff;\n config.dataChannelOpen = this.defaultDataChannelLabel === (data === null || data === void 0 ? void 0 : data.label) && (data === null || data === void 0 ? void 0 : data.state) === 'open';\n }\n if (handleId === this.handleId && this.defaultDataChannelLabel === (data === null || data === void 0 ? void 0 : data.label)) {\n this._isDataChannelOpen = (data === null || data === void 0 ? void 0 : data.state) === 'open';\n this.emit('dataChannel', (data === null || data === void 0 ? void 0 : data.state) === 'open');\n }\n }\n if (type === 'error') {\n this.emit('error', {\n type: 'warning',\n id: 9,\n message: 'data event warning',\n data: [handleId, data]\n });\n if (handle) {\n let config = handle.webrtcStuff;\n if (this.defaultDataChannelLabel === data.label) {\n config.dataChannelOpen = false;\n }\n }\n if (handleId === this.handleId && this.defaultDataChannelLabel === data.label) {\n this._isDataChannelOpen = false;\n this.emit('dataChannel', false);\n }\n }\n if (handleId === this.handleId && type === 'message') {\n let d = null;\n try {\n d = JSON.parse(data);\n } catch (e) {\n this.emit('error', {\n type: 'warning',\n id: 10,\n message: 'data message parse error',\n data: [handleId, e]\n });\n return;\n }\n this.emit('data', d);\n }\n }\n\n //removeHandle === true -> hangup, detach, removeHandle === false -> hangup\n _removeParticipant(handleId, rfid) {\n let removeHandle = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n let handle = this._getHandle(handleId, rfid);\n if (!handle) {\n return Promise.resolve();\n } else {\n handleId = handle.handleId;\n }\n return this._send({\n \"janus\": \"hangup\",\n \"handle_id\": handleId\n }, true).then(() => removeHandle ? this._send({\n \"janus\": \"detach\",\n \"handle_id\": handleId\n }, true) : Promise.resolve()).finally(() => {\n try {\n if (handle.webrtcStuff.stream) {\n if (!this.isRestarting) {\n var _handle$webrtcStuff$s;\n (_handle$webrtcStuff$s = handle.webrtcStuff.stream) === null || _handle$webrtcStuff$s === void 0 ? void 0 : _handle$webrtcStuff$s.getTracks().forEach(track => track.stop());\n } else {\n var _handle$webrtcStuff$s2;\n (_handle$webrtcStuff$s2 = handle.webrtcStuff.stream) === null || _handle$webrtcStuff$s2 === void 0 ? void 0 : _handle$webrtcStuff$s2.getTracks().forEach(track => track.onended = null);\n }\n }\n } catch (e) {\n // Do nothing\n }\n if (handle.webrtcStuff.stream) {\n handle.webrtcStuff.stream.onremovetrack = null;\n handle.webrtcStuff.stream = null;\n }\n if (handle.webrtcStuff.dataChannel) {\n Object.keys(handle.webrtcStuff.dataChannel).forEach(label => {\n handle.webrtcStuff.dataChannel[label].onmessage = null;\n handle.webrtcStuff.dataChannel[label].onopen = null;\n handle.webrtcStuff.dataChannel[label].onclose = null;\n handle.webrtcStuff.dataChannel[label].onerror = null;\n });\n }\n if (handle.webrtcStuff.pc) {\n handle.webrtcStuff.pc.onicecandidate = null;\n handle.webrtcStuff.pc.ontrack = null;\n handle.webrtcStuff.pc.ondatachannel = null;\n handle.webrtcStuff.pc.onconnectionstatechange = null;\n handle.webrtcStuff.pc.oniceconnectionstatechange = null;\n }\n try {\n handle.webrtcStuff.pc.close();\n } catch (e) {}\n handle.webrtcStuff = {\n stream: null,\n streamMap: {},\n tracksMap: [],\n transceiverMap: [],\n subscribeMap: [],\n mySdp: null,\n mediaConstraints: null,\n pc: null,\n dataChannelOpen: false,\n dataChannel: null,\n dtmfSender: null,\n trickle: true,\n iceDone: false,\n isIceRestarting: false,\n stats: {},\n selectedSubstream: {},\n initialSimulcastSubstreamBeenSet: {},\n overriddenSimulcastMode: {}\n };\n if (handleId === this.handleId) {\n var _decodeJanusDisplay7, _decodeJanusDisplay8;\n this._isDataChannelOpen = false;\n this.isPublished = false;\n this.emit('published', {\n status: false,\n hasStream: false\n });\n this.emit('removeLocalParticipant', {\n id: handleId,\n userId: (_decodeJanusDisplay7 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay7 === void 0 ? void 0 : _decodeJanusDisplay7.userId,\n role: (_decodeJanusDisplay8 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay8 === void 0 ? void 0 : _decodeJanusDisplay8.role\n });\n } else {\n var _decodeJanusDisplay9, _decodeJanusDisplay10;\n this.emit(this._getRemoveParticipantEventName(handleId), {\n id: handleId,\n userId: (_decodeJanusDisplay9 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay9 === void 0 ? void 0 : _decodeJanusDisplay9.userId,\n role: (_decodeJanusDisplay10 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay10 === void 0 ? void 0 : _decodeJanusDisplay10.role\n });\n }\n if (removeHandle) {\n let handleIndex = this._participants.findIndex(p => p.handleId === handleId);\n this._participants.splice(handleIndex, 1);\n }\n return true;\n });\n }\n _createParticipant() {\n let userId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let rfid = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n return this._send({\n \"janus\": \"attach\",\n \"plugin\": this.pluginName\n }).then(json => {\n let handleId = json.data[\"id\"];\n let handle = {\n handleId,\n rfid,\n userId,\n webrtcStuff: {\n stream: null,\n streamMap: {},\n tracksMap: [],\n transceiverMap: [],\n subscribeMap: [],\n mySdp: null,\n mediaConstraints: null,\n pc: null,\n dataChannelOpen: false,\n dataChannel: null,\n dtmfSender: null,\n trickle: true,\n iceDone: false,\n isIceRestarting: false,\n stats: {},\n selectedSubstream: {},\n initialSimulcastSubstreamBeenSet: {},\n overriddenSimulcastMode: {}\n }\n };\n this._participants.push(handle);\n return handle;\n });\n }\n _updateSubscribeMap(handleId, subscribe, unsubscribe) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateSubscribeMap']\n });\n return;\n }\n let currentSubscribeMap = handle.webrtcStuff.subscribeMap;\n subscribe.forEach(s => {\n if (!currentSubscribeMap.find(c => c.feed === s.feed && c.mid === s.mid)) {\n currentSubscribeMap.push(s);\n }\n });\n unsubscribe.forEach(s => {\n let index = currentSubscribeMap.findIndex(c => c.feed === s.feed && c.mid === s.mid);\n if (index > -1) {\n currentSubscribeMap.splice(index, 1);\n }\n });\n }\n _isAlreadySubscribed(handleId, feed, mid) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'isAlreadySubscribed']\n });\n return false;\n }\n return handle.webrtcStuff.subscribeMap.findIndex(t => t.mid === mid && t.feed === feed) > -1;\n }\n _updateTransceiverMap(handleId, streams) {\n this._log('Updating current transceiver map', handleId, streams);\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateTransceiverMap']\n });\n return;\n }\n let config = handle.webrtcStuff;\n config.transceiverMap = structuredClone(streams);\n }\n _updateParticipantsTrackData(handleId, streams) {\n this._log('Updating participants track data', handleId, streams);\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateParticipantsTrackData']\n });\n return;\n }\n let config = handle.webrtcStuff;\n config.tracksMap = structuredClone(streams.map(s => {\n let source = null;\n let simulcastBitrates = null;\n try {\n const description = JSON.parse(s.description);\n source = description === null || description === void 0 ? void 0 : description.source;\n simulcastBitrates = description === null || description === void 0 ? void 0 : description.simulcastBitrates;\n } catch (e) {}\n return {\n active: !s.disabled,\n description: s.description,\n source: source,\n simulcastBitrates: simulcastBitrates,\n display: s.display,\n id: s.id,\n mid: s.mid,\n mindex: s.mindex,\n codec: s.codec,\n type: s.type\n };\n }));\n }\n _updateRemoteParticipantStreamMap(handleId) {\n this._log('Updating participants stream map', handleId);\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateRemoteParticipantStreamMap']\n });\n return;\n }\n let config = handle.webrtcStuff;\n config.streamMap = {};\n config.transceiverMap.forEach(tItem => {\n var _JSON$parse2, _config$pc$getTransce, _config$pc$getTransce2, _config$pc$getTransce3;\n if (tItem.type === 'data') {\n return;\n }\n if (tItem.active === false) {\n return;\n }\n const source = (_JSON$parse2 = JSON.parse(tItem.feed_description)) === null || _JSON$parse2 === void 0 ? void 0 : _JSON$parse2.source;\n if (!config.streamMap[source]) {\n config.streamMap[source] = [];\n }\n let trackId = (_config$pc$getTransce = config.pc.getTransceivers().find(t => t.mid === tItem.mid)) === null || _config$pc$getTransce === void 0 ? void 0 : (_config$pc$getTransce2 = _config$pc$getTransce.receiver) === null || _config$pc$getTransce2 === void 0 ? void 0 : (_config$pc$getTransce3 = _config$pc$getTransce2.track) === null || _config$pc$getTransce3 === void 0 ? void 0 : _config$pc$getTransce3.id;\n if (trackId) {\n config.streamMap[source].push(trackId);\n }\n });\n }\n _joinRoom(roomId, pin, userId, display) {\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": roomId,\n \"pin\": pin,\n \"ptype\": \"publisher\",\n \"display\": display,\n ...(this.webrtcVersion > 1000 ? {\n id: userId\n } : {})\n }\n }, false, true);\n }\n _watchStream(id) {\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"watch\",\n id: String(id)\n }\n }, false, true);\n }\n _leaveRoom() {\n let dontWait = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n return this.isConnected ? this.sendMessage(this.handleId, {\n body: {\n \"request\": \"leave\"\n }\n }, dontWait).finally(() => {\n this.isConnected = false;\n this.emit('joined', false);\n }) : Promise.resolve();\n }\n\n // internal reconnect\n\n _reconnect() {\n if (this.isReclaiming) {\n return Promise.resolve();\n }\n if (this.ws) {\n this._wipeListeners();\n if (this.ws.readyState === 1) {\n this.ws.close();\n }\n }\n this._stopKeepAlive();\n this.isReclaiming = true;\n this.emit('joining', true);\n return new Promise((resolve, reject) => {\n let abortReconnect = () => {\n this._abortController.signal.removeEventListener('abort', abortReconnect);\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = null;\n this.ws.onerror = null;\n this.isReclaiming = false;\n this.emit('joining', false);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled',\n data: e\n });\n };\n this.ws = new WebSocket(this.server, 'janus-protocol');\n this.__connectionClosedBoundFn = this._connectionClosed.bind(this);\n this.__handleWsEventsBoundFn = this._handleWsEvents.bind(this);\n this.ws.addEventListener('close', this.__connectionClosedBoundFn);\n this.ws.addEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = () => {\n this._abortController.signal.removeEventListener('abort', abortReconnect);\n this._send({\n \"janus\": \"claim\"\n }).then(json => {\n this.sessionId = json[\"session_id\"] ? json[\"session_id\"] : json.data[\"id\"];\n this._startKeepAlive();\n this.isReclaiming = false;\n this.emit('joining', false);\n this._retries = 0;\n resolve(json);\n }).catch(error => {\n this.isReclaiming = false;\n this.emit('joining', false);\n reject({\n type: 'error',\n id: 11,\n message: 'reconnection error',\n data: error\n });\n });\n };\n\n // this is called before 'close' event callback so it doesn't break reconnect loop\n this.ws.onerror = e => {\n this._abortController.signal.removeEventListener('abort', abortReconnect);\n this.isReclaiming = false;\n this.emit('joining', false);\n reject({\n type: 'warning',\n id: 12,\n message: 'ws reconnection error',\n data: e\n });\n };\n this._abortController.signal.addEventListener('abort', abortReconnect);\n });\n }\n connect(roomId, pin, server, iceServers, token, display, userId) {\n let webrtcVersion = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0;\n let initialBitrate = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0;\n let recordingFilename = arguments.length > 9 ? arguments[9] : undefined;\n let simulcast = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : false;\n let simulcastSettings = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : this.defaultSimulcastSettings;\n let enableDtx = arguments.length > 12 && arguments[12] !== undefined ? arguments[12] : false;\n if (this.isConnecting) {\n return Promise.reject({\n type: 'warning',\n id: 16,\n message: 'connection already in progress'\n });\n }\n if (this.ws) {\n this._wipeListeners();\n }\n this._stopKeepAlive();\n this._abortController = new AbortController();\n this.sessionId = null;\n this.server = server;\n this.iceServers = iceServers;\n this.token = token;\n this.roomId = roomId;\n this.pin = pin;\n this.display = display;\n this.userId = userId;\n this.webrtcVersion = webrtcVersion;\n this.initialBitrate = initialBitrate;\n this.recordingFilename = recordingFilename;\n this.isConnecting = true;\n this.enableDtx = enableDtx;\n this.simulcast = simulcast;\n this.simulcastSettings = structuredClone(simulcastSettings);\n\n // sort simulcast bitrates\n if (this.simulcastSettings && typeof this.simulcastSettings === 'object' && Object.keys(this.simulcastSettings).length) {\n Object.keys(this.simulcastSettings).forEach(k => {\n this.simulcastSettings[k].bitrates = this.simulcastSettings[k].bitrates.sort((a, b) => {\n if (a.maxBitrate === b.maxBitrate) {\n return a.maxFramerate - b.maxFramerate;\n }\n return a.maxBitrate - b.maxBitrate;\n });\n });\n }\n this.emit('joining', true);\n return new Promise((resolve, reject) => {\n this.ws = new WebSocket(this.server, 'janus-protocol');\n this.__connectionClosedBoundFn = this._connectionClosed.bind(this);\n this.__handleWsEventsBoundFn = this._handleWsEvents.bind(this);\n let abortConnect = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = null;\n this.ws.onerror = null;\n this.isConnecting = false;\n this.emit('joining', false);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled'\n });\n };\n this.ws.addEventListener('close', this.__connectionClosedBoundFn);\n this.ws.addEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this._retries = 0;\n this._send({\n \"janus\": \"create\"\n }).then(json => {\n this.sessionId = json[\"session_id\"] ? json[\"session_id\"] : json.data[\"id\"];\n this._startKeepAlive();\n return 1;\n }).then(() => this._createParticipant(userId)).then(handle => {\n this.handleId = handle.handleId;\n return 1;\n }).then(() => this._joinRoom(roomId, pin, userId, display)).then(() => {\n this._enableStatsWatch();\n this._enableSubstreamAutoSelect();\n this.isConnecting = false;\n this.emit('joining', false);\n resolve(this);\n }).catch(error => {\n this.isConnecting = false;\n this.emit('joining', false);\n reject({\n type: (error === null || error === void 0 ? void 0 : error.type) === 'warning' ? 'warning' : 'error',\n id: 13,\n message: 'connection error',\n data: error\n });\n });\n };\n this.ws.onerror = e => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.isConnecting = false;\n this.emit('joining', false);\n reject({\n type: 'error',\n id: 14,\n message: 'ws connection error',\n data: e\n });\n };\n this._abortController.signal.addEventListener('abort', abortConnect);\n });\n }\n disconnect() {\n var _this$_abortControlle, _this$_abortControlle2;\n if (this.isDisconnecting) {\n return Promise.resolve();\n }\n (_this$_abortControlle = this._abortController) === null || _this$_abortControlle === void 0 ? void 0 : (_this$_abortControlle2 = _this$_abortControlle.abort) === null || _this$_abortControlle2 === void 0 ? void 0 : _this$_abortControlle2.call(_this$_abortControlle);\n this.isDisconnecting = true;\n this._stopKeepAlive();\n this._disableStatsWatch();\n this._disableSubstreamAutoSelect();\n let isConnected = this.isConnected;\n return Promise.all(this._participants.map(p => this._removeParticipant(p.handleId))).finally(() => {\n this._wipeListeners();\n if (this.ws && this.ws.readyState === 1) {\n this._send({\n \"janus\": \"destroy\"\n }, true);\n this.ws.close();\n }\n this.sessionId = null;\n this.isPublished = false;\n this.isConnected = false;\n this.isDisconnecting = false;\n this.emit('publishing', false);\n this.emit('published', {\n status: false,\n hasStream: false\n });\n this.emit('joining', false);\n this.emit('joined', false);\n this.emit('disconnect', isConnected);\n return Promise.resolve('Disconnected');\n });\n }\n startStream(streamId, server, iceServers, token, userId) {\n if (this.isConnecting) {\n return Promise.reject({\n type: 'warning',\n id: 16,\n message: 'connection error',\n data: 'Connection is in progress'\n });\n }\n if (this.ws) {\n this._wipeListeners();\n }\n this._stopKeepAlive();\n this._abortController = new AbortController();\n this.server = server;\n this.iceServers = iceServers;\n this.token = token;\n this.streamId = streamId;\n this.userId = userId;\n this.sessionId = null;\n this.isConnecting = true;\n this.emit('streamStarting', true);\n return new Promise((resolve, reject) => {\n this.ws = new WebSocket(this.server, 'janus-protocol');\n this.__connectionClosedBoundFn = this._connectionClosed.bind(this);\n this.__handleWsEventsBoundFn = this._handleWsEvents.bind(this);\n let abortConnect = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = null;\n this.ws.onerror = null;\n this.isConnecting = false;\n this.emit('streamStarting', false);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled'\n });\n };\n this.ws.addEventListener('close', this.__connectionClosedBoundFn);\n this.ws.addEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this._retries = 0;\n this._send({\n \"janus\": \"create\"\n }).then(json => {\n this.sessionId = json[\"session_id\"] ? json[\"session_id\"] : json.data[\"id\"];\n this._startKeepAlive();\n return 1;\n }).then(() => this._createParticipant(userId)).then(handle => {\n this.handleId = handle.handleId;\n return 1;\n }).then(() => this._watchStream(streamId)).then(() => {\n this.isConnecting = false;\n this.emit('streamStarting', false);\n resolve(this);\n }).catch(error => {\n this.isConnecting = false;\n this.emit('streamStarting', false);\n reject({\n type: 'error',\n id: 13,\n message: 'connection error',\n data: error\n });\n });\n };\n this.ws.onerror = e => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.isConnecting = false;\n this.emit('streamStarting', false);\n reject({\n type: 'error',\n id: 14,\n message: 'ws connection error',\n data: e\n });\n };\n this._abortController.signal.addEventListener('abort', abortConnect);\n });\n }\n stopStream() {\n var _this$_abortControlle3, _this$_abortControlle4;\n if (this.isDisconnecting) {\n return Promise.resolve();\n }\n (_this$_abortControlle3 = this._abortController) === null || _this$_abortControlle3 === void 0 ? void 0 : (_this$_abortControlle4 = _this$_abortControlle3.abort) === null || _this$_abortControlle4 === void 0 ? void 0 : _this$_abortControlle4.call(_this$_abortControlle3);\n this._stopKeepAlive();\n let isStreaming = this.isStreaming;\n this.isDisconnecting = true;\n return this._removeParticipant(this.handleId).finally(() => {\n this.sendMessage(this.handleId, {\n body: {\n \"request\": \"stop\"\n }\n }, true);\n this._wipeListeners();\n this._send({\n \"janus\": \"destroy\"\n }, true);\n if (this.ws && this.ws.readyState === 1) {\n this.ws.close();\n }\n this.sessionId = null;\n this.isDisconnecting = false;\n this.isStreaming = false;\n this.emit('streamStarting', false);\n this.emit('streaming', false);\n this.emit('disconnect', isStreaming);\n return Promise.resolve('Disconnected');\n });\n }\n destroy() {\n if (this.sessiontype === 'reactooroom') {\n return this.disconnect().then(() => {\n this.clear();\n return true;\n });\n } else if (this.sessiontype === 'streaming') {\n return this.stopStream().then(() => {\n this.clear();\n return true;\n });\n }\n }\n _enableDebug() {\n this._log = console.log.bind(console);\n }\n _getHandle(handleId) {\n let rfid = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n let userId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n return this._participants.find(p => {\n var _decodeJanusDisplay11;\n return p.handleId === handleId || rfid && p.rfid === rfid || userId && ((_decodeJanusDisplay11 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(p.userId)) === null || _decodeJanusDisplay11 === void 0 ? void 0 : _decodeJanusDisplay11.userId) === userId;\n });\n }\n _findSimulcastConfig(source, settings) {\n return Object.keys(settings).reduce((acc, key) => {\n var _key$match;\n if (settings[source]) {\n return settings[source];\n } else if (source.indexOf((_key$match = key.match(/\\*(.*?)\\*/)) === null || _key$match === void 0 ? void 0 : _key$match[1]) > -1) {\n return settings[key];\n } else return acc;\n }, settings['default']);\n }\n _disableStatsWatch() {\n if (this._statsTimeoutId) {\n clearInterval(this._statsTimeout);\n this._statsTimeoutStopped = true;\n this._statsTimeoutId = null;\n }\n }\n _enableStatsWatch() {\n if (this._statsTimeoutId) {\n clearTimeout(this._statsTimeoutId);\n this._statsTimeoutId = null;\n }\n this._statsTimeoutStopped = false;\n const loop = () => {\n let startTime = performance.now();\n let endTime = null;\n this._getStats('video').then(participantsStats => {\n endTime = performance.now();\n this._parseVideoStats(participantsStats);\n }).finally(() => {\n if (!this._statsTimeoutStopped) {\n this._statsTimeoutId = setTimeout(loop, this._statsInterval - Math.min(endTime - startTime, this._statsInterval));\n }\n });\n };\n loop();\n }\n\n // This method completely ignores temporal layers\n // We prefer higher fps and lower resolution so if the fps in not in the range of 0.7 of the max fps we go to the next lower resolution\n\n _enableSubstreamAutoSelect() {\n if (!this.simulcast) {\n return;\n }\n if (this._aqTimeoutId) {\n clearTimeout(this._aqTimeoutId);\n this._aqTimeoutId = null;\n this._aqIntervalCounter = 0;\n }\n const checkStats = () => {\n this._participants.forEach(p => {\n if (p.handleId !== this.handleId) {\n var _p$webrtcStuff, _p$webrtcStuff$pc, _transceivers$filter;\n const transceivers = (_p$webrtcStuff = p.webrtcStuff) === null || _p$webrtcStuff === void 0 ? void 0 : (_p$webrtcStuff$pc = _p$webrtcStuff.pc) === null || _p$webrtcStuff$pc === void 0 ? void 0 : _p$webrtcStuff$pc.getTransceivers();\n const mids = (transceivers === null || transceivers === void 0 ? void 0 : (_transceivers$filter = transceivers.filter(t => t.receiver.track.kind === \"video\")) === null || _transceivers$filter === void 0 ? void 0 : _transceivers$filter.map(t => t.mid)) || [];\n mids.forEach(mid => {\n var _p$webrtcStuff2, _p$webrtcStuff2$overr, _p$webrtcStuff3, _p$webrtcStuff3$overr;\n const {\n source,\n simulcastBitrates\n } = p.webrtcStuff.tracksMap.find(t => t.mid === mid) || {};\n\n // track is gone\n if (!simulcastBitrates) {\n return;\n }\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n const initialSubstreamBeenSet = !!p.webrtcStuff.initialSimulcastSubstreamBeenSet[mid];\n const defaultSelectedSubstream = ((_p$webrtcStuff2 = p.webrtcStuff) === null || _p$webrtcStuff2 === void 0 ? void 0 : (_p$webrtcStuff2$overr = _p$webrtcStuff2.overriddenSimulcastMode[mid]) === null || _p$webrtcStuff2$overr === void 0 ? void 0 : _p$webrtcStuff2$overr.defaultSubstream) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.defaultSubstream);\n const simulcastMode = ((_p$webrtcStuff3 = p.webrtcStuff) === null || _p$webrtcStuff3 === void 0 ? void 0 : (_p$webrtcStuff3$overr = _p$webrtcStuff3.overriddenSimulcastMode[mid]) === null || _p$webrtcStuff3$overr === void 0 ? void 0 : _p$webrtcStuff3$overr.mode) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.mode);\n if (simulcastMode === 'browserControlled') {\n // do nothing\n } else if (simulcastMode === 'manual' && this._aqIntervalCounter % this._aqIntervalDivisor === 0 || !initialSubstreamBeenSet) {\n p.webrtcStuff.initialSimulcastSubstreamBeenSet[mid] = true;\n const currentSubstream = p.webrtcStuff.selectedSubstream[mid];\n if (defaultSelectedSubstream !== undefined && defaultSelectedSubstream !== null && defaultSelectedSubstream !== currentSubstream) {\n this._log('Attempting to force substream quality', defaultSelectedSubstream);\n this.selectSubStream(p.handleId, defaultSelectedSubstream, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n } else if (simulcastMode === 'controlled') {\n var _p$webrtcStuff4, _p$webrtcStuff4$stats, _p$webrtcStuff4$stats2, _p$webrtcStuff5, _p$webrtcStuff5$stats, _p$webrtcStuff5$stats2;\n const currentSubstream = p.webrtcStuff.selectedSubstream[mid];\n const settingsForCurrentSubstream = simulcastBitrates === null || simulcastBitrates === void 0 ? void 0 : simulcastBitrates[simulcastBitrates.length - 1 - currentSubstream];\n let directionDecision = 0;\n if (((_p$webrtcStuff4 = p.webrtcStuff) === null || _p$webrtcStuff4 === void 0 ? void 0 : (_p$webrtcStuff4$stats = _p$webrtcStuff4.stats) === null || _p$webrtcStuff4$stats === void 0 ? void 0 : (_p$webrtcStuff4$stats2 = _p$webrtcStuff4$stats[mid]) === null || _p$webrtcStuff4$stats2 === void 0 ? void 0 : _p$webrtcStuff4$stats2.length) > this._upStatsLength) {\n const upMedianStats = this._calculateMedianStats(p.webrtcStuff.stats[mid].slice(this._upStatsLength * -1));\n if ((upMedianStats === null || upMedianStats === void 0 ? void 0 : upMedianStats.framesPerSecond) >= Math.floor(((settingsForCurrentSubstream === null || settingsForCurrentSubstream === void 0 ? void 0 : settingsForCurrentSubstream.maxFramerate) || 30) * 0.7) && (upMedianStats === null || upMedianStats === void 0 ? void 0 : upMedianStats.freezeDurationSinceLast) < this._upStatsLength * this._statsInterval * 0.33 / 1000 /* && upMedianStats?.freezeCountSinceLast < 3 */) {\n directionDecision = 1;\n }\n }\n if (((_p$webrtcStuff5 = p.webrtcStuff) === null || _p$webrtcStuff5 === void 0 ? void 0 : (_p$webrtcStuff5$stats = _p$webrtcStuff5.stats) === null || _p$webrtcStuff5$stats === void 0 ? void 0 : (_p$webrtcStuff5$stats2 = _p$webrtcStuff5$stats[mid]) === null || _p$webrtcStuff5$stats2 === void 0 ? void 0 : _p$webrtcStuff5$stats2.length) > this._downStatsLength) {\n const downMedianStats = this._calculateMedianStats(p.webrtcStuff.stats[mid].slice(this._downStatsLength * -1));\n if ((downMedianStats === null || downMedianStats === void 0 ? void 0 : downMedianStats.framesPerSecond) < Math.floor(((settingsForCurrentSubstream === null || settingsForCurrentSubstream === void 0 ? void 0 : settingsForCurrentSubstream.maxFramerate) || 30) * 0.7) || (downMedianStats === null || downMedianStats === void 0 ? void 0 : downMedianStats.freezeDurationSinceLast) > this._downStatsLength * this._statsInterval * 0.33 / 1000 /* || downMedianStats?.freezeCountSinceLast > 5 || downMedianStats?.jitter > maxJitter(settingsForCurrentSubstream.maxFramerate) */) {\n directionDecision = -1;\n }\n }\n if (directionDecision === -1) {\n if (currentSubstream < simulcastBitrates.length - 1) {\n this._log('Attempting to down the quality for mid: ', mid, ' quality:', currentSubstream + 1);\n this._resetStats(p.handleId, mid);\n this.selectSubStream(p.handleId, currentSubstream + 1, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n } else if (directionDecision === 1) {\n if (currentSubstream > 0) {\n this._log('Attempting to up the quality for mid: ', mid, ' quality:', currentSubstream - 1);\n this._resetStats(p.handleId, mid);\n this.selectSubStream(p.handleId, currentSubstream - 1, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n } else {\n this._log('No quality change for mid: ', mid);\n }\n }\n });\n }\n });\n this._aqIntervalCounter++;\n this._aqTimeoutId = setTimeout(checkStats, this._aqInterval);\n };\n checkStats();\n }\n _disableSubstreamAutoSelect() {\n if (this._aqTimeoutId) {\n clearTimeout(this._aqTimeoutId);\n this._aqTimeoutId = null;\n this._aqIntervalCounter = 0;\n }\n }\n _calculateMedianStats(stats) {\n let medianStats = {\n framesPerSecond: null,\n jitter: null,\n roundTripTime: null,\n freezeDurationSinceLast: null,\n freezeCountSinceLast: null\n };\n let keys = Object.keys(medianStats);\n keys.forEach(key => {\n if (key === 'freezeDurationSinceLast' || key === 'freezeCountSinceLast') {\n medianStats[key] = stats.reduce((acc, cur) => acc + cur[key], 0);\n }\n // median but ignore first value of stats array\n else {\n let values = stats.map(s => s[key]);\n medianStats[key] = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"median\"])(values);\n }\n });\n medianStats.statsLength = stats.length;\n return medianStats;\n }\n _parseVideoStats(participantsStats) {\n participantsStats.forEach(sourceStats => {\n sourceStats.forEach(participantStats => {\n var _participantStats$han;\n if (participantStats !== null && (participantStats === null || participantStats === void 0 ? void 0 : (_participantStats$han = participantStats.handle) === null || _participantStats$han === void 0 ? void 0 : _participantStats$han.handleId) !== this.handleId) {\n let handle = this._getHandle(participantStats.handle.handleId);\n if (handle) {\n var _decodeJanusDisplay12;\n if (!handle.webrtcStuff.stats[participantStats.mid]) {\n handle.webrtcStuff.stats[participantStats.mid] = [];\n }\n const stats = {\n framesPerSecond: null,\n framesDropped: null,\n totalFreezesDuration: null,\n freezeDurationSinceLast: null,\n freezeCount: null,\n jitter: null,\n packetsLost: null,\n nackCount: null,\n roundTripTime: null,\n width: null,\n height: null,\n networkType: null,\n powerEfficientDecoder: null\n };\n participantStats.stats.forEach(report => {\n var _handle$webrtcStuff4, _handle$webrtcStuff4$;\n const simulcastConfigForSource = this._findSimulcastConfig(participantStats.source, this.simulcastSettings);\n const simulcastMode = ((_handle$webrtcStuff4 = handle.webrtcStuff) === null || _handle$webrtcStuff4 === void 0 ? void 0 : (_handle$webrtcStuff4$ = _handle$webrtcStuff4.overriddenSimulcastMode[participantStats.mid]) === null || _handle$webrtcStuff4$ === void 0 ? void 0 : _handle$webrtcStuff4$.mode) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.mode);\n if (report.type === 'inbound-rtp' && report.kind === 'video') {\n var _handle$webrtcStuff$s3, _handle$webrtcStuff$s4, _handle$webrtcStuff$s5, _handle$webrtcStuff$s6, _handle$webrtcStuff$s7, _handle$webrtcStuff$s8, _handle$webrtcStuff$s9, _handle$webrtcStuff$s10, _handle$webrtcStuff$s11, _handle$webrtcStuff$s12;\n stats.framesPerSecond = report.framesPerSecond || 0;\n stats.framesDropped = report.framesDropped || 0;\n stats.totalFreezesDuration = report.totalFreezesDuration || 0;\n stats.freezeDurationSinceLast = (report.totalFreezesDuration || 0) - (((_handle$webrtcStuff$s3 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s3 === void 0 ? void 0 : (_handle$webrtcStuff$s4 = _handle$webrtcStuff$s3[participantStats.mid]) === null || _handle$webrtcStuff$s4 === void 0 ? void 0 : (_handle$webrtcStuff$s5 = _handle$webrtcStuff$s4[((_handle$webrtcStuff$s6 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s6 === void 0 ? void 0 : (_handle$webrtcStuff$s7 = _handle$webrtcStuff$s6[participantStats.mid]) === null || _handle$webrtcStuff$s7 === void 0 ? void 0 : _handle$webrtcStuff$s7.length) - 1]) === null || _handle$webrtcStuff$s5 === void 0 ? void 0 : _handle$webrtcStuff$s5.totalFreezesDuration) || 0);\n stats.freezeCount = report.freezeCount || 0;\n stats.freezeCountSinceLast = (report.freezeCount || 0) - (((_handle$webrtcStuff$s8 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s8 === void 0 ? void 0 : (_handle$webrtcStuff$s9 = _handle$webrtcStuff$s8[participantStats.mid]) === null || _handle$webrtcStuff$s9 === void 0 ? void 0 : (_handle$webrtcStuff$s10 = _handle$webrtcStuff$s9[((_handle$webrtcStuff$s11 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s11 === void 0 ? void 0 : (_handle$webrtcStuff$s12 = _handle$webrtcStuff$s11[participantStats.mid]) === null || _handle$webrtcStuff$s12 === void 0 ? void 0 : _handle$webrtcStuff$s12.length) - 1]) === null || _handle$webrtcStuff$s10 === void 0 ? void 0 : _handle$webrtcStuff$s10.freezeCount) || 0);\n stats.jitter = report.jitter;\n stats.packetsLost = report.packetsLost;\n stats.nackCount = report.nackCount;\n stats.width = report.frameWidth;\n stats.height = report.frameHeight;\n stats.powerEfficientDecoder = report.powerEfficientDecoder;\n }\n if (report.type === 'candidate-pair') {\n stats.roundTripTime = report.currentRoundTripTime;\n }\n if (report.type === 'local-candidate') {\n stats.networkType = report.networkType;\n }\n stats.selectedSubstream = handle.webrtcStuff.selectedSubstream[participantStats.mid];\n stats.simulcastMode = simulcastMode;\n });\n\n // pushing stats into handle stats array but keeping only 6 last stats\n handle.webrtcStuff.stats[participantStats.mid].push(stats);\n if (handle.webrtcStuff.stats[participantStats.mid].length > this._statsMaxLength) {\n handle.webrtcStuff.stats[participantStats.mid].shift();\n }\n this.emit('rtcStats', {\n handleId: participantStats.handle.handleId,\n stats,\n userId: (_decodeJanusDisplay12 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(participantStats.handle.userId)) === null || _decodeJanusDisplay12 === void 0 ? void 0 : _decodeJanusDisplay12.userId,\n source: participantStats.source,\n mid: participantStats.mid\n });\n }\n }\n });\n });\n }\n _getStats() {\n let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n return Promise.all(this._participants.map(participant => {\n let mediaTrack = [];\n if (type === 'video') {\n var _participant$webrtcSt, _participant$webrtcSt2;\n mediaTrack = (participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt = participant.webrtcStuff) === null || _participant$webrtcSt === void 0 ? void 0 : (_participant$webrtcSt2 = _participant$webrtcSt.stream) === null || _participant$webrtcSt2 === void 0 ? void 0 : _participant$webrtcSt2.getVideoTracks()) || [];\n } else if (type === 'audio') {\n var _participant$webrtcSt3, _participant$webrtcSt4;\n mediaTrack = (participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt3 = participant.webrtcStuff) === null || _participant$webrtcSt3 === void 0 ? void 0 : (_participant$webrtcSt4 = _participant$webrtcSt3.stream) === null || _participant$webrtcSt4 === void 0 ? void 0 : _participant$webrtcSt4.getAudioTracks()) || [];\n }\n if (type !== null) {\n var _participant$webrtcSt5, _participant$webrtcSt6;\n const transceivers = participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt5 = participant.webrtcStuff) === null || _participant$webrtcSt5 === void 0 ? void 0 : (_participant$webrtcSt6 = _participant$webrtcSt5.pc) === null || _participant$webrtcSt6 === void 0 ? void 0 : _participant$webrtcSt6.getTransceivers();\n return Promise.all(mediaTrack.map(track => {\n var _transceivers$find;\n const source = Object.keys(participant.webrtcStuff.streamMap).find(s => participant.webrtcStuff.streamMap[s].find(t => t === track.id));\n const mid = (_transceivers$find = transceivers.find(t => {\n var _t$receiver, _t$receiver$track, _t$sender, _t$sender$track;\n return ((_t$receiver = t.receiver) === null || _t$receiver === void 0 ? void 0 : (_t$receiver$track = _t$receiver.track) === null || _t$receiver$track === void 0 ? void 0 : _t$receiver$track.id) === track.id || ((_t$sender = t.sender) === null || _t$sender === void 0 ? void 0 : (_t$sender$track = _t$sender.track) === null || _t$sender$track === void 0 ? void 0 : _t$sender$track.id) === track.id;\n })) === null || _transceivers$find === void 0 ? void 0 : _transceivers$find.mid;\n return participant.webrtcStuff.pc.getStats(track).then(r => ({\n stats: r,\n source,\n mid,\n handle: participant\n })).catch(e => Promise.reject({\n stats: null,\n error: e,\n handle: participant,\n source,\n mid\n }));\n }));\n } else {\n var _participant$webrtcSt7, _participant$webrtcSt8;\n return participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt7 = participant.webrtcStuff) === null || _participant$webrtcSt7 === void 0 ? void 0 : (_participant$webrtcSt8 = _participant$webrtcSt7.pc) === null || _participant$webrtcSt8 === void 0 ? void 0 : _participant$webrtcSt8.getStats(null).then(r => ({\n handle: participant,\n stats: r\n })).catch(e => Promise.reject({\n handle: participant,\n error: e\n }));\n }\n }));\n }\n _resetStats(handleId, mid) {\n let handle = this._getHandle(handleId);\n if (handle) {\n let config = handle.webrtcStuff;\n if (!mid) {\n Object.keys(config.stats).forEach(mid => {\n config.stats[mid] = [config.stats[mid][config.stats[mid].length - 1]];\n });\n } else {\n // clearing stats for the new substream\n if (config.stats[mid]) {\n config.stats[mid] = [config.stats[mid][config.stats[mid].length - 1]];\n }\n }\n }\n }\n _sendTrickleCandidate(handleId, candidate) {\n return this._send({\n \"janus\": \"trickle\",\n \"candidate\": candidate,\n \"handle_id\": handleId\n }, false, false, 5);\n }\n _webrtc(handleId) {\n let enableOntrack = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'error',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'create rtc connection']\n });\n return;\n }\n let config = handle.webrtcStuff;\n if (!config.pc) {\n let pc_config = {\n \"iceServers\": this.iceServers,\n \"iceTransportPolicy\": 'all',\n \"bundlePolicy\": undefined\n };\n pc_config[\"sdpSemantics\"] = \"unified-plan\";\n let pc_constraints = {};\n if (webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser === \"edge\") {\n // This is Edge, enable BUNDLE explicitly\n pc_config.bundlePolicy = \"max-bundle\";\n }\n\n // pc_config.bundlePolicy = 'balanced';\n // pc_config.iceTransportPolicy = 'relay';\n // pc_config.rtcpMuxPolicy = \"negotiate\";\n\n this._log('new RTCPeerConnection', pc_config, pc_constraints);\n config.pc = new RTCPeerConnection(pc_config, pc_constraints);\n config.pc.onnegotiationneeded = () => {\n this._log('onnegotiationneeded');\n };\n config.pc.onconnectionstatechange = () => {\n if (config.pc.connectionState === 'failed') {\n this._log('connectionState failed');\n this._iceRestart(handleId);\n }\n this.emit('connectionState', [handleId, handleId === this.handleId, config.pc.connectionState]);\n if (handleId !== this.handleId && config.pc.connectionState === 'connected') {\n var _decodeJanusDisplay13, _decodeJanusDisplay14;\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay13 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay13 === void 0 ? void 0 : _decodeJanusDisplay13.userId,\n role: (_decodeJanusDisplay14 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay14 === void 0 ? void 0 : _decodeJanusDisplay14.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n track: null,\n source: null,\n constructId: this.constructId,\n adding: false,\n removing: false,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n }\n };\n config.pc.oniceconnectionstatechange = () => {\n if (config.pc.iceConnectionState === 'failed') {\n this._log('iceConnectionState failed');\n this._iceRestart(handleId);\n }\n this.emit('iceState', [handleId, handleId === this.handleId, config.pc.iceConnectionState]);\n if (handleId !== this.handleId && (config.pc.iceConnectionState === 'completed' || config.pc.iceConnectionState === 'connected')) {\n var _decodeJanusDisplay15, _decodeJanusDisplay16;\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay15 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay15 === void 0 ? void 0 : _decodeJanusDisplay15.userId,\n role: (_decodeJanusDisplay16 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay16 === void 0 ? void 0 : _decodeJanusDisplay16.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n track: null,\n source: null,\n constructId: this.constructId,\n adding: false,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n }\n };\n config.pc.onicecandidate = event => {\n if (event.candidate == null || webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser === 'edge' && event.candidate.candidate.indexOf('endOfCandidates') > 0) {\n config.iceDone = true;\n this._sendTrickleCandidate(handleId, {\n \"completed\": true\n }).catch(e => {\n this.emit('error', e);\n });\n } else {\n // JSON.stringify doesn't work on some WebRTC objects anymore\n // See https://code.google.com/p/chromium/issues/detail?id=467366\n var candidate = {\n \"candidate\": event.candidate.candidate,\n \"sdpMid\": event.candidate.sdpMid,\n \"sdpMLineIndex\": event.candidate.sdpMLineIndex\n };\n this._sendTrickleCandidate(handleId, candidate).catch(e => {\n this.emit('error', e);\n });\n }\n };\n if (enableOntrack) {\n config.pc.ontrack = event => {\n var _event$streams, _event$streams$;\n if (!event.streams) return;\n if (!config.stream) {\n config.stream = new MediaStream();\n }\n if (!((_event$streams = event.streams) !== null && _event$streams !== void 0 && (_event$streams$ = _event$streams[0]) !== null && _event$streams$ !== void 0 && _event$streams$.onremovetrack)) {\n event.streams[0].onremovetrack = ev => {\n var _config$stream, _config$pc, _config$pc$getTransce4, _decodeJanusDisplay17, _decodeJanusDisplay18;\n this._log('Remote track removed', ev);\n (_config$stream = config.stream) === null || _config$stream === void 0 ? void 0 : _config$stream.removeTrack(ev.track);\n\n // check if handle still exists\n if (!this._getHandle(handle.handleId)) {\n return;\n }\n this._updateRemoteParticipantStreamMap(handle.handleId);\n let transceiver = (_config$pc = config.pc) === null || _config$pc === void 0 ? void 0 : (_config$pc$getTransce4 = _config$pc.getTransceivers()) === null || _config$pc$getTransce4 === void 0 ? void 0 : _config$pc$getTransce4.find(t => t.receiver.track === ev.track);\n let mid = (transceiver === null || transceiver === void 0 ? void 0 : transceiver.mid) || ev.track.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.track.id));\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay17 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay17 === void 0 ? void 0 : _decodeJanusDisplay17.userId,\n role: (_decodeJanusDisplay18 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay18 === void 0 ? void 0 : _decodeJanusDisplay18.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n source,\n track: ev.track,\n adding: false,\n removing: true,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n };\n }\n if (event.track) {\n var _config$stream2, _decodeJanusDisplay19, _decodeJanusDisplay20;\n (_config$stream2 = config.stream) === null || _config$stream2 === void 0 ? void 0 : _config$stream2.addTrack(event.track);\n this._updateRemoteParticipantStreamMap(handle.handleId);\n let mid = event.transceiver ? event.transceiver.mid : event.track.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(event.track.id));\n if (event.track.kind === 'video') {\n this.requestKeyFrame(handle.handleId, mid);\n }\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n mid,\n id: handle.handleId,\n userId: (_decodeJanusDisplay19 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay19 === void 0 ? void 0 : _decodeJanusDisplay19.userId,\n role: (_decodeJanusDisplay20 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay20 === void 0 ? void 0 : _decodeJanusDisplay20.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n source,\n track: event.track,\n constructId: this.constructId,\n adding: true,\n removing: false,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n if (event.track.onended) return;\n event.track.onended = ev => {\n var _config$stream3, _config$pc2, _config$pc2$getTransc, _decodeJanusDisplay21, _decodeJanusDisplay22;\n this._log('Remote track ended');\n (_config$stream3 = config.stream) === null || _config$stream3 === void 0 ? void 0 : _config$stream3.removeTrack(ev.target);\n // check if handle still exists\n if (!this._getHandle(handle.handleId)) {\n return;\n }\n this._updateRemoteParticipantStreamMap(handle.handleId);\n let transceiver = (_config$pc2 = config.pc) === null || _config$pc2 === void 0 ? void 0 : (_config$pc2$getTransc = _config$pc2.getTransceivers()) === null || _config$pc2$getTransc === void 0 ? void 0 : _config$pc2$getTransc.find(t => t.receiver.track === ev.target);\n let mid = (transceiver === null || transceiver === void 0 ? void 0 : transceiver.mid) || ev.target.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.target.id));\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay21 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay21 === void 0 ? void 0 : _decodeJanusDisplay21.userId,\n role: (_decodeJanusDisplay22 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay22 === void 0 ? void 0 : _decodeJanusDisplay22.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n source,\n track: ev.target,\n adding: false,\n removing: true,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n };\n let mutedTimerId = {};\n let waitPeriod = 300; // ms\n let screenShareWaitPeriod = 5000; // ms\n\n event.track.onmute = ev => {\n var _decodeJanusDisplay23, _decodeJanusDisplay24;\n this._log('Remote track muted');\n let transceiver = config.pc.getTransceivers().find(t => t.receiver.track === ev.target);\n let mid = transceiver.mid || ev.target.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.target.id));\n this.emit('remoteTrackMuted', {\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay23 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay23 === void 0 ? void 0 : _decodeJanusDisplay23.userId,\n role: (_decodeJanusDisplay24 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay24 === void 0 ? void 0 : _decodeJanusDisplay24.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n source,\n kind: ev.target.kind,\n track: ev.target,\n muted: true\n });\n\n // when a track is muted, we try to switch to lower quality substream, but not for screen sharing\n\n if (!this.simulcast) {\n return;\n }\n const wPeriod = source.indexOf('screen') > -1 ? screenShareWaitPeriod : waitPeriod;\n if (!mutedTimerId[mid]) {\n mutedTimerId[mid] = setTimeout(() => {\n var _handle$webrtcStuff5, _handle$webrtcStuff5$;\n mutedTimerId[mid] = null;\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n const simulcastMode = ((_handle$webrtcStuff5 = handle.webrtcStuff) === null || _handle$webrtcStuff5 === void 0 ? void 0 : (_handle$webrtcStuff5$ = _handle$webrtcStuff5.overriddenSimulcastMode[mid]) === null || _handle$webrtcStuff5$ === void 0 ? void 0 : _handle$webrtcStuff5$.mode) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.mode);\n const {\n simulcastBitrates\n } = handle.webrtcStuff.tracksMap.find(t => t.mid === mid) || {};\n\n // track is gone\n if (!simulcastBitrates) {\n return;\n }\n const currentSubstream = handle.webrtcStuff.selectedSubstream[mid];\n if (!(simulcastMode === 'browserControlled') && ev.target.kind === 'video' && currentSubstream < simulcastBitrates.length - 1) {\n this._log('Attempting to down the quality due to track muted');\n this.selectSubStream(handle.handleId, currentSubstream + 1, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n }, wPeriod);\n }\n };\n event.track.onunmute = ev => {\n var _decodeJanusDisplay25, _decodeJanusDisplay26;\n this._log('Remote track unmuted');\n let transceiver = config.pc.getTransceivers().find(t => t.receiver.track === ev.target);\n let mid = transceiver.mid || ev.target.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.target.id));\n if (mutedTimerId[mid]) {\n clearTimeout(mutedTimerId[mid]);\n mutedTimerId[mid] = null;\n }\n this.emit('remoteTrackMuted', {\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay25 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay25 === void 0 ? void 0 : _decodeJanusDisplay25.userId,\n role: (_decodeJanusDisplay26 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay26 === void 0 ? void 0 : _decodeJanusDisplay26.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n source,\n kind: ev.target.kind,\n track: ev.target,\n muted: false\n });\n };\n }\n };\n }\n }\n if (!config.dataChannel || !config.dataChannelOpen) {\n config.dataChannel = {};\n var onDataChannelMessage = event => {\n this._handleDataEvents(handleId, 'message', event.data);\n };\n var onDataChannelStateChange = event => {\n let label = event.target.label;\n let protocol = event.target.protocol;\n let state = config.dataChannel[label] ? config.dataChannel[label].readyState : \"null\";\n this._handleDataEvents(handleId, 'state', {\n state,\n label\n });\n };\n var onDataChannelError = error => {\n var _error$channel;\n this._handleDataEvents(handleId, 'error', {\n label: error === null || error === void 0 ? void 0 : (_error$channel = error.channel) === null || _error$channel === void 0 ? void 0 : _error$channel.label,\n error\n });\n };\n const createDataChannel = (label, protocol, incoming) => {\n let options = {\n ordered: true\n };\n if (!incoming) {\n if (protocol) {\n options = {\n ...options,\n protocol\n };\n }\n config.dataChannel[label] = config.pc.createDataChannel(label, options);\n } else {\n config.dataChannel[label] = incoming;\n }\n config.dataChannel[label].onmessage = onDataChannelMessage;\n config.dataChannel[label].onopen = onDataChannelStateChange;\n config.dataChannel[label].onclose = onDataChannelStateChange;\n config.dataChannel[label].onerror = onDataChannelError;\n };\n createDataChannel(this.defaultDataChannelLabel, null, null);\n config.pc.ondatachannel = function (event) {\n createDataChannel(event.channel.label, event.channel.protocol, event.channel);\n };\n }\n }\n _webrtcPeer(handleId, jsep) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.reject({\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'rtc peer']\n });\n }\n var config = handle.webrtcStuff;\n if (jsep !== undefined && jsep !== null) {\n if (config.pc === null) {\n this._log(\"No PeerConnection: if this is an answer, use createAnswer and not _webrtcPeer\");\n return Promise.resolve(null);\n }\n return config.pc.setRemoteDescription(jsep).then(() => {\n config.remoteSdp = jsep.sdp;\n // Any trickle candidate we cached?\n if (config.candidates && config.candidates.length > 0) {\n for (var i = 0; i < config.candidates.length; i++) {\n var candidate = config.candidates[i];\n if (!candidate || candidate.completed === true) {\n config.pc.addIceCandidate(null);\n } else {\n config.pc.addIceCandidate(candidate);\n }\n }\n config.candidates = [];\n }\n // Done\n return true;\n }).catch(e => {\n return Promise.reject({\n type: 'warning',\n id: 32,\n message: 'rtc peer',\n data: [handleId, e]\n });\n });\n } else {\n return Promise.reject({\n type: 'warning',\n id: 22,\n message: 'rtc peer',\n data: [handleId, 'invalid jsep']\n });\n }\n }\n _iceRestart(handleId) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n return;\n }\n var config = handle.webrtcStuff;\n\n // Already restarting;\n if (config.isIceRestarting) {\n return;\n }\n config.isIceRestarting = true;\n if (this.handleId === handleId) {\n this._log('Performing local ICE restart');\n let hasAudio = !!(config.stream && config.stream.getAudioTracks().length > 0);\n let hasVideo = !!(config.stream && config.stream.getVideoTracks().length > 0);\n this._createAO('offer', handleId, true).then(jsep => {\n if (!jsep) {\n return null;\n }\n return this.sendMessage(handleId, {\n body: {\n \"request\": \"configure\",\n \"keyframe\": true,\n \"audio\": hasAudio,\n \"video\": hasVideo,\n \"data\": true,\n ...(this.recordingFilename ? {\n filename: this.recordingFilename\n } : {})\n },\n jsep\n }, false, false, 5);\n }).then(r => {\n config.isIceRestarting = false;\n this._log('ICE restart success');\n }).catch(e => {\n config.isIceRestarting = false;\n this.emit('error', {\n type: 'warning',\n id: 28,\n message: 'iceRestart failed',\n data: e\n });\n });\n } else {\n this._log('Performing remote ICE restart', handleId);\n return this.sendMessage(handleId, {\n body: {\n \"request\": \"configure\",\n \"restart\": true\n }\n }, false, false, 5).then(() => {}).then(() => {\n config.isIceRestarting = false;\n this._log('ICE restart success');\n }).catch(() => {\n config.isIceRestarting = false;\n });\n }\n }\n _setupTransceivers(handleId, _ref) {\n let [audioSend, audioRecv, videoSend, videoRecv, audioTransceiver = null, videoTransceiver = null] = _ref;\n //TODO: this should be refactored to use handle's trackMap so we dont have to pass any parameters\n\n let handle = this._getHandle(handleId);\n if (!handle) {\n return null;\n }\n let config = handle.webrtcStuff;\n const setTransceiver = function (transceiver, send, recv) {\n let kind = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'audio';\n if (!send && !recv) {\n // disabled: have we removed it?\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"inactive\");\n } else {\n transceiver.direction = \"inactive\";\n }\n }\n } else {\n if (send && recv) {\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"sendrecv\");\n } else {\n transceiver.direction = \"sendrecv\";\n }\n }\n } else if (send && !recv) {\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"sendonly\");\n } else {\n transceiver.direction = \"sendonly\";\n }\n }\n } else if (!send && recv) {\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"recvonly\");\n } else {\n transceiver.direction = \"recvonly\";\n }\n } else {\n // In theory, this is the only case where we might not have a transceiver yet\n config.pc.addTransceiver(kind, {\n direction: \"recvonly\"\n });\n }\n }\n }\n };\n\n // if we're passing any transceivers, we work only on them, doesn't matter if one of them is null\n if (audioTransceiver || videoTransceiver) {\n if (audioTransceiver) {\n setTransceiver(audioTransceiver, audioSend, audioRecv, 'audio');\n }\n if (videoTransceiver) {\n setTransceiver(videoTransceiver, videoSend, videoRecv, 'video');\n }\n }\n // else we work on all transceivers\n else {\n let transceivers = config.pc.getTransceivers();\n if (transceivers && transceivers.length > 0) {\n for (let i in transceivers) {\n let t = transceivers[i];\n if (t.sender && t.sender.track && t.sender.track.kind === \"audio\" || t.receiver && t.receiver.track && t.receiver.track.kind === \"audio\") {\n setTransceiver(t, audioSend, audioRecv, 'audio');\n }\n if (t.sender && t.sender.track && t.sender.track.kind === \"video\" || t.receiver && t.receiver.track && t.receiver.track.kind === \"video\") {\n setTransceiver(t, videoSend, videoRecv, 'video');\n }\n }\n }\n }\n }\n _createAO() {\n let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'offer';\n let handleId = arguments.length > 1 ? arguments[1] : undefined;\n let iceRestart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.reject({\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'createAO', type]\n });\n }\n let methodName = null;\n if (type === 'offer') {\n methodName = 'createOffer';\n } else {\n methodName = 'createAnswer';\n }\n let config = handle.webrtcStuff;\n let mediaConstraints = {};\n if (iceRestart) {\n mediaConstraints[\"iceRestart\"] = true;\n }\n return config.pc[methodName](mediaConstraints).then(response => {\n // if type offer and its me and we want dtx we mungle the sdp\n if (handleId === this.handleId && type === 'offer' && this.enableDtx) {\n // enable DTX\n response.sdp = response.sdp.replace(\"useinbandfec=1\", \"useinbandfec=1;usedtx=1\");\n }\n config.mySdp = response.sdp;\n let _p = config.pc.setLocalDescription(response).catch(e => {\n return Promise.reject({\n type: 'warning',\n id: 24,\n message: 'setLocalDescription',\n data: [handleId, e]\n });\n });\n config.mediaConstraints = mediaConstraints;\n if (!config.iceDone && !config.trickle) {\n // Don't do anything until we have all candidates\n return Promise.resolve(null);\n }\n\n // JSON.stringify doesn't work on some WebRTC objects anymore\n // See https://code.google.com/p/chromium/issues/detail?id=467366\n var jsep = {\n \"type\": response.type,\n \"sdp\": response.sdp\n };\n if (response.e2ee) jsep.e2ee = true;\n if (response.rid_order === \"hml\" || response.rid_order === \"lmh\") jsep.rid_order = response.rid_order;\n if (response.force_relay) jsep.force_relay = true;\n return _p.then(() => jsep);\n }, e => {\n return Promise.reject({\n type: 'warning',\n id: 25,\n message: methodName,\n data: [handleId, e]\n });\n });\n }\n _publishRemote(handleId, jsep) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.reject({\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'publish remote participant']\n });\n }\n this._webrtc(handleId, true);\n let config = handle.webrtcStuff;\n if (jsep) {\n return config.pc.setRemoteDescription(jsep).then(() => {\n config.remoteSdp = jsep.sdp;\n // Any trickle candidate we cached?\n if (config.candidates && config.candidates.length > 0) {\n for (var i = 0; i < config.candidates.length; i++) {\n var candidate = config.candidates[i];\n if (!candidate || candidate.completed === true) {\n // end-of-candidates\n config.pc.addIceCandidate(null);\n } else {\n // New candidate\n config.pc.addIceCandidate(candidate);\n }\n }\n config.candidates = [];\n }\n this._setupTransceivers(handleId, [false, true, false, true]);\n\n // Create the answer now\n return this._createAO('answer', handleId, false).then(_jsep => {\n if (!_jsep) {\n this.emit('error', {\n type: 'warning',\n id: 19,\n message: 'publish remote participant',\n data: [handleId, 'no jsep']\n });\n return Promise.resolve();\n }\n return this.sendMessage(handleId, {\n \"body\": {\n \"request\": \"start\",\n ...(this.roomId && {\n \"room\": this.roomId\n }),\n ...(this.pin && {\n pin: this.pin\n })\n },\n \"jsep\": _jsep\n });\n });\n }, e => Promise.reject({\n type: 'warning',\n id: 23,\n message: 'setRemoteDescription',\n data: [handleId, e]\n }));\n } else {\n return Promise.resolve();\n }\n }\n\n //Public methods\n _republishOnTrackEnded(source) {\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return;\n }\n let config = handle.webrtcStuff;\n if (!config.stream) {\n return;\n }\n let sourceTrackIds = config.streamMap[source] || [];\n let remainingTracks = [];\n for (let i = 0; i < sourceTrackIds.length; i++) {\n let foundTrack = config.stream.getTracks().find(t => t.id === sourceTrackIds[i]);\n if (foundTrack) {\n remainingTracks.push(foundTrack);\n }\n }\n if (remainingTracks.length) {\n let stream = new MediaStream();\n remainingTracks.forEach(track => stream.addTrack(track));\n return this.publishLocal(stream, source);\n } else {\n return this.publishLocal(null, source);\n }\n }\n publishLocal() {\n var _stream$getVideoTrack, _stream$getAudioTrack, _config$stream4, _config$stream4$getAu, _config$stream5, _config$stream5$getVi, _stream$getAudioTrack2, _stream$getVideoTrack2;\n let stream = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'camera0';\n if (this.isDisconnecting || !this.isConnected) {\n return Promise.reject({\n type: 'warning',\n id: 18,\n message: 'Either not connected or disconnecting'\n });\n }\n if ((stream === null || stream === void 0 ? void 0 : (_stream$getVideoTrack = stream.getVideoTracks()) === null || _stream$getVideoTrack === void 0 ? void 0 : _stream$getVideoTrack.length) > 1) {\n return Promise.reject({\n type: 'warning',\n id: 30,\n message: 'multiple video tracks not supported',\n data: null\n });\n }\n if ((stream === null || stream === void 0 ? void 0 : (_stream$getAudioTrack = stream.getAudioTracks()) === null || _stream$getAudioTrack === void 0 ? void 0 : _stream$getAudioTrack.length) > 1) {\n return Promise.reject({\n type: 'warning',\n id: 30,\n message: 'multiple audio tracks not supported',\n data: null\n });\n }\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return Promise.reject({\n type: 'error',\n id: 31,\n message: 'no local id, connect before publishing',\n data: null\n });\n }\n this.emit('publishing', true);\n this._webrtc(this.handleId);\n let config = handle.webrtcStuff;\n if (!config.stream) {\n config.stream = new MediaStream();\n }\n let needsNegotiation = !this.isPublished;\n let transceivers = config.pc.getTransceivers();\n let existingTracks = [...(config.streamMap[source] || [])];\n if (stream !== null && stream !== void 0 && stream.getTracks().length) {\n var _stream$getTracks;\n config.streamMap[source] = (stream === null || stream === void 0 ? void 0 : (_stream$getTracks = stream.getTracks()) === null || _stream$getTracks === void 0 ? void 0 : _stream$getTracks.map(track => track.id)) || [];\n } else {\n delete config.streamMap[source];\n }\n\n // remove old audio track related to this source\n let oldAudioStream = config === null || config === void 0 ? void 0 : (_config$stream4 = config.stream) === null || _config$stream4 === void 0 ? void 0 : (_config$stream4$getAu = _config$stream4.getAudioTracks()) === null || _config$stream4$getAu === void 0 ? void 0 : _config$stream4$getAu.find(track => existingTracks.includes(track.id));\n if (oldAudioStream) {\n try {\n oldAudioStream.stop();\n } catch (e) {\n this._log(e);\n }\n config.stream.removeTrack(oldAudioStream);\n }\n\n // remove old video track related to this source\n let oldVideoStream = config === null || config === void 0 ? void 0 : (_config$stream5 = config.stream) === null || _config$stream5 === void 0 ? void 0 : (_config$stream5$getVi = _config$stream5.getVideoTracks()) === null || _config$stream5$getVi === void 0 ? void 0 : _config$stream5$getVi.find(track => existingTracks.includes(track.id));\n if (oldVideoStream) {\n try {\n oldVideoStream.stop();\n } catch (e) {\n this._log(e);\n }\n config.stream.removeTrack(oldVideoStream);\n }\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n let audioTrackReplacePromise = Promise.resolve();\n let videoTrackReplacePromise = Promise.resolve();\n let audioTransceiver = null;\n let videoTransceiver = null;\n let replaceAudio = stream === null || stream === void 0 ? void 0 : (_stream$getAudioTrack2 = stream.getAudioTracks()) === null || _stream$getAudioTrack2 === void 0 ? void 0 : _stream$getAudioTrack2.length;\n let replaceVideo = stream === null || stream === void 0 ? void 0 : (_stream$getVideoTrack2 = stream.getVideoTracks()) === null || _stream$getVideoTrack2 === void 0 ? void 0 : _stream$getVideoTrack2.length;\n for (const transceiver of transceivers) {\n var _transceiver$sender, _transceiver$sender$t, _transceiver$sender2, _transceiver$sender2$, _transceiver$sender3, _transceiver$sender3$, _transceiver$sender4, _transceiver$sender4$, _transceiver$sender5, _transceiver$sender5$, _transceiver$sender5$2, _transceiver$sender6, _transceiver$sender6$, _transceiver$sender6$2;\n if (['sendonly', 'sendrecv'].includes(transceiver.currentDirection) && ((_transceiver$sender = transceiver.sender) === null || _transceiver$sender === void 0 ? void 0 : (_transceiver$sender$t = _transceiver$sender.track) === null || _transceiver$sender$t === void 0 ? void 0 : _transceiver$sender$t.kind) === 'audio' && existingTracks.includes((_transceiver$sender2 = transceiver.sender) === null || _transceiver$sender2 === void 0 ? void 0 : (_transceiver$sender2$ = _transceiver$sender2.track) === null || _transceiver$sender2$ === void 0 ? void 0 : _transceiver$sender2$.id)) {\n audioTransceiver = transceiver;\n } else if (['sendonly', 'sendrecv'].includes(transceiver.currentDirection) && ((_transceiver$sender3 = transceiver.sender) === null || _transceiver$sender3 === void 0 ? void 0 : (_transceiver$sender3$ = _transceiver$sender3.track) === null || _transceiver$sender3$ === void 0 ? void 0 : _transceiver$sender3$.kind) === 'video' && existingTracks.includes((_transceiver$sender4 = transceiver.sender) === null || _transceiver$sender4 === void 0 ? void 0 : (_transceiver$sender4$ = _transceiver$sender4.track) === null || _transceiver$sender4$ === void 0 ? void 0 : _transceiver$sender4$.id)) {\n videoTransceiver = transceiver;\n }\n\n // Reusing existing transceivers\n // TODO: if we start using different codecs for different sources, we need to check for that here\n else if (transceiver.currentDirection === 'inactive' && (_transceiver$sender5 = transceiver.sender) !== null && _transceiver$sender5 !== void 0 && (_transceiver$sender5$ = _transceiver$sender5.getParameters()) !== null && _transceiver$sender5$ !== void 0 && (_transceiver$sender5$2 = _transceiver$sender5$.codecs) !== null && _transceiver$sender5$2 !== void 0 && _transceiver$sender5$2.find(c => c.mimeType.indexOf('audio') > -1) && replaceAudio && !audioTransceiver) {\n audioTransceiver = transceiver;\n needsNegotiation = true;\n } else if (transceiver.currentDirection === 'inactive' && (_transceiver$sender6 = transceiver.sender) !== null && _transceiver$sender6 !== void 0 && (_transceiver$sender6$ = _transceiver$sender6.getParameters()) !== null && _transceiver$sender6$ !== void 0 && (_transceiver$sender6$2 = _transceiver$sender6$.codecs) !== null && _transceiver$sender6$2 !== void 0 && _transceiver$sender6$2.find(c => c.mimeType.indexOf('video') > -1) && replaceVideo && !videoTransceiver) {\n videoTransceiver = transceiver;\n needsNegotiation = true;\n }\n }\n if (replaceAudio) {\n config.stream.addTrack(stream.getAudioTracks()[0]);\n if (audioTransceiver && audioTransceiver.sender) {\n audioTrackReplacePromise = audioTransceiver.sender.replaceTrack(stream.getAudioTracks()[0]);\n } else {\n config.pc.addTrack(stream.getAudioTracks()[0], config.stream);\n needsNegotiation = true;\n }\n } else {\n if (audioTransceiver && audioTransceiver.sender) {\n audioTrackReplacePromise = audioTransceiver.sender.replaceTrack(null);\n needsNegotiation = true;\n }\n }\n if (replaceVideo) {\n config.stream.addTrack(stream.getVideoTracks()[0]);\n if (videoTransceiver && videoTransceiver.sender) {\n videoTrackReplacePromise = videoTransceiver.sender.replaceTrack(stream.getVideoTracks()[0]);\n } else {\n if (!this.simulcast) {\n config.pc.addTrack(stream.getVideoTracks()[0], config.stream);\n } else {\n if (webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser !== 'firefox') {\n // standard\n config.pc.addTransceiver(stream.getVideoTracks()[0], {\n direction: 'sendonly',\n streams: [config.stream],\n sendEncodings: structuredClone(simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates)\n });\n } else {\n // firefox\n let transceiver = config.pc.addTransceiver(stream.getVideoTracks()[0], {\n direction: 'sendonly',\n streams: [config.stream]\n });\n let sender = transceiver ? transceiver.sender : null;\n if (sender) {\n let parameters = sender.getParameters() || {};\n parameters.encodings = stream.getVideoTracks()[0].sendEncodings || structuredClone(simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates);\n sender.setParameters(parameters);\n }\n }\n }\n needsNegotiation = true;\n }\n } else {\n if (videoTransceiver && videoTransceiver.sender) {\n videoTrackReplacePromise = videoTransceiver.sender.replaceTrack(null);\n needsNegotiation = true;\n }\n }\n this.isAudioEnabed = !!(config.stream && config.stream.getAudioTracks().length > 0);\n this.isVideoEnabled = !!(config.stream && config.stream.getVideoTracks().length > 0);\n\n // we possibly created new transceivers, so we need to get them again\n transceivers = config.pc.getTransceivers();\n existingTracks = [...(config.streamMap[source] || [])];\n if (!audioTransceiver) {\n audioTransceiver = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'audio' && existingTracks.includes(transceiver.sender.track.id));\n }\n if (!videoTransceiver) {\n videoTransceiver = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'video' && existingTracks.includes(transceiver.sender.track.id));\n }\n let hasAudio = !!(stream && stream.getAudioTracks().length > 0);\n let hasVideo = !!(stream && stream.getVideoTracks().length > 0);\n this._setupTransceivers(this.handleId, [hasAudio, false, hasVideo, false, audioTransceiver, videoTransceiver]);\n const emitEvents = () => {\n var _decodeJanusDisplay27, _decodeJanusDisplay28;\n this.isPublished = true;\n if (!config.stream.onremovetrack) {\n config.stream.onremovetrack = ev => {};\n }\n let republishTimeoutId = null;\n let tracks = config.stream.getTracks();\n this.emit('addLocalParticipant', {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay27 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay27 === void 0 ? void 0 : _decodeJanusDisplay27.userId,\n role: (_decodeJanusDisplay28 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display)) === null || _decodeJanusDisplay28 === void 0 ? void 0 : _decodeJanusDisplay28.role,\n stream: tracks.length ? config.stream : null,\n // that null is there due to backward compatibility\n track: null,\n streamMap: structuredClone(config.streamMap),\n source,\n adding: false,\n removing: false,\n constructId: this.constructId,\n hasAudioTrack: hasAudio,\n hasVideoTrack: hasVideo\n });\n if (tracks.length) {\n tracks.forEach(track => {\n // used as a flag to not emit tracks that been already emitted\n if (!track.onended) {\n var _decodeJanusDisplay29, _decodeJanusDisplay30;\n this.emit('addLocalParticipant', {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay29 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay29 === void 0 ? void 0 : _decodeJanusDisplay29.userId,\n role: (_decodeJanusDisplay30 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display)) === null || _decodeJanusDisplay30 === void 0 ? void 0 : _decodeJanusDisplay30.role,\n track,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n source,\n adding: true,\n removing: false,\n constructId: this.constructId,\n hasAudioTrack: hasAudio,\n hasVideoTrack: hasVideo\n });\n track.onended = ev => {\n config.stream.removeTrack(track);\n clearTimeout(republishTimeoutId);\n republishTimeoutId = setTimeout(() => {\n this._republishOnTrackEnded(source);\n }, 100);\n };\n }\n });\n }\n this.isMuted = [];\n for (const source of Object.keys(config.streamMap)) {\n var _config$stream6, _config$stream6$getAu, _config$stream7, _config$stream7$getVi, _transceivers$find2, _transceivers$find3;\n const audioTrack = (_config$stream6 = config.stream) === null || _config$stream6 === void 0 ? void 0 : (_config$stream6$getAu = _config$stream6.getAudioTracks()) === null || _config$stream6$getAu === void 0 ? void 0 : _config$stream6$getAu.find(track => config.streamMap[source].includes(track.id));\n const videoTrack = (_config$stream7 = config.stream) === null || _config$stream7 === void 0 ? void 0 : (_config$stream7$getVi = _config$stream7.getVideoTracks()) === null || _config$stream7$getVi === void 0 ? void 0 : _config$stream7$getVi.find(track => config.streamMap[source].includes(track.id));\n this.isMuted.push({\n type: 'audio',\n value: !audioTrack || !audioTrack.enabled,\n source,\n mid: (_transceivers$find2 = transceivers.find(transceiver => {\n var _transceiver$sender7, _transceiver$sender7$, _transceiver$sender8, _transceiver$sender8$;\n return ((_transceiver$sender7 = transceiver.sender) === null || _transceiver$sender7 === void 0 ? void 0 : (_transceiver$sender7$ = _transceiver$sender7.track) === null || _transceiver$sender7$ === void 0 ? void 0 : _transceiver$sender7$.kind) === 'audio' && ((_transceiver$sender8 = transceiver.sender) === null || _transceiver$sender8 === void 0 ? void 0 : (_transceiver$sender8$ = _transceiver$sender8.track) === null || _transceiver$sender8$ === void 0 ? void 0 : _transceiver$sender8$.id) === (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.id);\n })) === null || _transceivers$find2 === void 0 ? void 0 : _transceivers$find2.mid\n });\n this.isMuted.push({\n type: 'video',\n value: !videoTrack || !videoTrack.enabled,\n source,\n mid: (_transceivers$find3 = transceivers.find(transceiver => {\n var _transceiver$sender9, _transceiver$sender9$, _transceiver$sender10, _transceiver$sender11;\n return ((_transceiver$sender9 = transceiver.sender) === null || _transceiver$sender9 === void 0 ? void 0 : (_transceiver$sender9$ = _transceiver$sender9.track) === null || _transceiver$sender9$ === void 0 ? void 0 : _transceiver$sender9$.kind) === 'video' && ((_transceiver$sender10 = transceiver.sender) === null || _transceiver$sender10 === void 0 ? void 0 : (_transceiver$sender11 = _transceiver$sender10.track) === null || _transceiver$sender11 === void 0 ? void 0 : _transceiver$sender11.id) === (videoTrack === null || videoTrack === void 0 ? void 0 : videoTrack.id);\n })) === null || _transceivers$find3 === void 0 ? void 0 : _transceivers$find3.mid\n });\n this.emit('localHasVideo', !!videoTrack, source);\n this.emit('localHasAudio', !!audioTrack, source);\n }\n for (const val of this.isMuted) {\n this.emit('localMuted', {\n ...val\n });\n }\n this.emit('published', {\n status: true,\n hasStream: tracks.length > 0\n });\n this.emit('publishing', false);\n return this;\n };\n\n // this should be enough\n if (!needsNegotiation) {\n return Promise.all([audioTrackReplacePromise, videoTrackReplacePromise]).then(() => emitEvents());\n }\n this._log('Starting negotiation');\n return Promise.all([audioTrackReplacePromise, videoTrackReplacePromise]).then(() => this._createAO('offer', this.handleId, false)).then(jsep => {\n if (!jsep) {\n return null;\n }\n //HOTFIX: Temporary fix for Safari 13\n if (jsep.sdp && jsep.sdp.indexOf(\"\\r\\na=ice-ufrag\") === -1) {\n jsep.sdp = jsep.sdp.replace(\"\\na=ice-ufrag\", \"\\r\\na=ice-ufrag\");\n }\n let descriptions = [];\n Object.keys(config.streamMap).forEach(source => {\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n config.streamMap[source].forEach(trackId => {\n let t = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.id === trackId);\n if (t) {\n descriptions.push({\n mid: t.mid,\n description: JSON.stringify({\n source,\n simulcastBitrates: simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates,\n intercomGroups: this._talkIntercomChannels\n })\n });\n }\n });\n });\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"configure\",\n \"audio\": this.isAudioEnabed,\n \"video\": this.isVideoEnabled,\n \"data\": true,\n ...(this.recordingFilename ? {\n filename: this.recordingFilename\n } : {}),\n descriptions: descriptions\n },\n jsep\n });\n }).then(r => {\n if (this._isDataChannelOpen === true) {\n return Promise.resolve(r);\n } else {\n return new Promise((resolve, reject) => {\n let dataChannelTimeoutId = null;\n let _resolve = val => {\n if (val) {\n clearTimeout(dataChannelTimeoutId);\n this._abortController.signal.removeEventListener('abort', _rejectAbort);\n this.off('dataChannel', _resolve, this);\n resolve(this);\n }\n };\n let _rejectTimeout = () => {\n this.off('dataChannel', _resolve, this);\n this._abortController.signal.removeEventListener('abort', _rejectAbort);\n reject({\n type: 'error',\n id: 27,\n message: 'Data channel did not open',\n data: null\n });\n };\n let _rejectAbort = () => {\n this._abortController.signal.removeEventListener('abort', _rejectAbort);\n clearTimeout(dataChannelTimeoutId);\n this.off('dataChannel', _resolve, this);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled'\n });\n };\n dataChannelTimeoutId = setTimeout(_rejectTimeout, 10000);\n this._abortController.signal.addEventListener('abort', _rejectAbort);\n this.on('dataChannel', _resolve, this);\n });\n }\n }).then(() => emitEvents()).catch(e => {\n this.emit('publishing', false);\n return Promise.reject(e);\n });\n }\n unpublishLocal() {\n let dontWait = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n return this.isPublished ? this.sendMessage(this.handleId, {\n body: {\n \"request\": \"unpublish\"\n }\n }, dontWait).finally(r => {\n this.isPublished = false;\n this.emit('published', {\n status: false,\n hasStream: false\n });\n return r;\n }) : Promise.resolve();\n }\n getUserTalkIntercomChannels(userId) {\n let talkIntercomChannels = [];\n let handle = this._getHandle(null, null, userId);\n if (handle) {\n let config = handle.webrtcStuff;\n talkIntercomChannels = config.tracksMap.reduce((acc, val) => {\n if (val.description) {\n try {\n let description = JSON.parse(val.description);\n if (description.intercomGroups) {\n description.intercomGroups.forEach(group => {\n if (!acc.includes(group)) {\n acc.push(group);\n }\n });\n }\n } catch (e) {}\n }\n return acc;\n }, []);\n }\n return talkIntercomChannels;\n }\n toggleAudio() {\n var _config$pc3;\n let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'camera0';\n let mid = arguments.length > 2 ? arguments[2] : undefined;\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 21,\n message: 'no local id, connect first',\n data: null\n });\n return;\n }\n let config = handle.webrtcStuff;\n let transceivers = (_config$pc3 = config.pc) === null || _config$pc3 === void 0 ? void 0 : _config$pc3.getTransceivers();\n let transceiver = null;\n if (source) {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"audio\" && (config.streamMap[source] || []).includes(t.sender.track.id));\n } else {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"audio\" && (mid ? t.mid === mid : true));\n }\n if (transceiver) {\n transceiver.sender.track.enabled = value !== null ? !!value : !transceiver.sender.track.enabled;\n }\n this.isMuted = [];\n for (const source of Object.keys(config.streamMap)) {\n var _config$stream8, _config$stream8$getAu, _config$stream9, _config$stream9$getVi, _audioTransceiver$sen, _audioTransceiver$sen2, _videoTransceiver$sen, _videoTransceiver$sen2;\n const audioTrack = (_config$stream8 = config.stream) === null || _config$stream8 === void 0 ? void 0 : (_config$stream8$getAu = _config$stream8.getAudioTracks()) === null || _config$stream8$getAu === void 0 ? void 0 : _config$stream8$getAu.find(track => config.streamMap[source].includes(track.id));\n const audioTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'audio' && transceiver.sender.track.id === (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.id));\n const videoTrack = (_config$stream9 = config.stream) === null || _config$stream9 === void 0 ? void 0 : (_config$stream9$getVi = _config$stream9.getVideoTracks()) === null || _config$stream9$getVi === void 0 ? void 0 : _config$stream9$getVi.find(track => config.streamMap[source].includes(track.id));\n const videoTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'video' && transceiver.sender.track.id === (videoTrack === null || videoTrack === void 0 ? void 0 : videoTrack.id));\n this.isMuted.push({\n type: 'audio',\n value: !audioTrack || !audioTransceiver || !(audioTransceiver !== null && audioTransceiver !== void 0 && (_audioTransceiver$sen = audioTransceiver.sender) !== null && _audioTransceiver$sen !== void 0 && (_audioTransceiver$sen2 = _audioTransceiver$sen.track) !== null && _audioTransceiver$sen2 !== void 0 && _audioTransceiver$sen2.enabled),\n source,\n mid: audioTransceiver === null || audioTransceiver === void 0 ? void 0 : audioTransceiver.mid\n });\n this.isMuted.push({\n type: 'video',\n value: !videoTrack || !videoTransceiver || !(videoTransceiver !== null && videoTransceiver !== void 0 && (_videoTransceiver$sen = videoTransceiver.sender) !== null && _videoTransceiver$sen !== void 0 && (_videoTransceiver$sen2 = _videoTransceiver$sen.track) !== null && _videoTransceiver$sen2 !== void 0 && _videoTransceiver$sen2.enabled),\n source,\n mid: videoTransceiver === null || videoTransceiver === void 0 ? void 0 : videoTransceiver.mid\n });\n }\n for (let val of this.isMuted) {\n this.emit('localMuted', {\n ...val\n });\n }\n }\n toggleVideo() {\n var _config$pc4;\n let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'camera0';\n let mid = arguments.length > 2 ? arguments[2] : undefined;\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 21,\n message: 'no local id, connect first',\n data: null\n });\n return;\n }\n let config = handle.webrtcStuff;\n let transceivers = (_config$pc4 = config.pc) === null || _config$pc4 === void 0 ? void 0 : _config$pc4.getTransceivers();\n let transceiver = null;\n if (source) {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"video\" && (config.streamMap[source] || []).includes(t.sender.track.id));\n } else {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"video\" && (mid ? t.mid === mid : true));\n }\n if (transceiver) {\n transceiver.sender.track.enabled = value !== null ? !!value : !transceiver.sender.track.enabled;\n }\n this.isMuted = [];\n for (const source of Object.keys(config.streamMap)) {\n var _config$stream10, _config$stream10$getA, _config$stream11, _config$stream11$getV, _audioTransceiver$sen3, _audioTransceiver$sen4, _videoTransceiver$sen3, _videoTransceiver$sen4;\n const audioTrack = (_config$stream10 = config.stream) === null || _config$stream10 === void 0 ? void 0 : (_config$stream10$getA = _config$stream10.getAudioTracks()) === null || _config$stream10$getA === void 0 ? void 0 : _config$stream10$getA.find(track => config.streamMap[source].includes(track.id));\n const audioTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'audio' && transceiver.sender.track.id === (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.id));\n const videoTrack = (_config$stream11 = config.stream) === null || _config$stream11 === void 0 ? void 0 : (_config$stream11$getV = _config$stream11.getVideoTracks()) === null || _config$stream11$getV === void 0 ? void 0 : _config$stream11$getV.find(track => config.streamMap[source].includes(track.id));\n const videoTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'video' && transceiver.sender.track.id === (videoTrack === null || videoTrack === void 0 ? void 0 : videoTrack.id));\n this.isMuted.push({\n type: 'audio',\n value: !audioTrack || !audioTransceiver || !(audioTransceiver !== null && audioTransceiver !== void 0 && (_audioTransceiver$sen3 = audioTransceiver.sender) !== null && _audioTransceiver$sen3 !== void 0 && (_audioTransceiver$sen4 = _audioTransceiver$sen3.track) !== null && _audioTransceiver$sen4 !== void 0 && _audioTransceiver$sen4.enabled),\n source,\n mid: audioTransceiver === null || audioTransceiver === void 0 ? void 0 : audioTransceiver.mid\n });\n this.isMuted.push({\n type: 'video',\n value: !videoTrack || !videoTransceiver || !(videoTransceiver !== null && videoTransceiver !== void 0 && (_videoTransceiver$sen3 = videoTransceiver.sender) !== null && _videoTransceiver$sen3 !== void 0 && (_videoTransceiver$sen4 = _videoTransceiver$sen3.track) !== null && _videoTransceiver$sen4 !== void 0 && _videoTransceiver$sen4.enabled),\n source,\n mid: videoTransceiver === null || videoTransceiver === void 0 ? void 0 : videoTransceiver.mid\n });\n }\n for (let val of this.isMuted) {\n this.emit('localMuted', {\n ...val\n });\n }\n }\n requestKeyFrame(handleId, mid) {\n this.sendMessage(handleId, {\n \"body\": {\n \"request\": \"configure\",\n \"keyframe\": true,\n ...(mid !== undefined ? {\n streams: [{\n mid,\n keyframe: true\n }]\n } : {})\n }\n }).catch(() => null);\n }\n _setSelectedSubstream(handleId, mid, substream) {\n let handle = this._getHandle(handleId);\n if (handle) {\n let config = handle.webrtcStuff;\n if (!mid) {\n Object.keys(config.selectedSubstream).forEach(mid => {\n config.selectedSubstream[mid] = substream;\n });\n } else {\n config.selectedSubstream[mid] = substream;\n }\n }\n }\n overrideSimulcastSettings(handleId, mid, source) {\n let settings = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n const {\n mode,\n defaultSubstream\n } = settings;\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let config = handle.webrtcStuff;\n if (source !== undefined || mid !== undefined) {\n if (mid === undefined) {\n let transceivers = config.pc.getTransceivers();\n for (let trackId of config.streamMap[source]) {\n let transceiver = transceivers.find(transceiver => transceiver.receiver.track && transceiver.receiver.track.kind === 'video' && transceiver.receiver.track.id === trackId);\n if (transceiver) {\n mid = transceiver.mid;\n break;\n }\n }\n }\n if (mid !== undefined) {\n if (!config.overriddenSimulcastMode[mid]) {\n config.overriddenSimulcastMode[mid] = {};\n }\n config.overriddenSimulcastMode[mid]['defaultSubstream'] = defaultSubstream;\n config.overriddenSimulcastMode[mid]['mode'] = mode;\n return true;\n } else {\n return false;\n }\n }\n }\n selectSubStream(handleId) {\n let substream = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;\n let source = arguments.length > 2 ? arguments[2] : undefined;\n let mid = arguments.length > 3 ? arguments[3] : undefined;\n let manual = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;\n this._log('Select substream called for handle:', handleId, 'Source or mid:', source ? source : mid, 'Substream:', substream);\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let config = handle.webrtcStuff;\n return new Promise((resolve, reject) => {\n let messageTimeoutId;\n let abortResponse = () => {\n clearTimeout(messageTimeoutId);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n reject('aborted');\n };\n let parseResponse = event => {\n let json = JSON.parse(event.data);\n var sender = json[\"sender\"];\n if (sender === handleId) {\n let plugindata = json[\"plugindata\"] || {};\n let msg = plugindata[\"data\"] || {};\n let substream = msg[\"substream\"];\n if (substream !== undefined && substream !== null && (mid !== undefined ? msg[\"mid\"] === mid : true)) {\n clearTimeout(messageTimeoutId);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n resolve({\n substream,\n sender\n });\n }\n }\n };\n if (source !== undefined || mid !== undefined) {\n if (mid === undefined) {\n let transceivers = config.pc.getTransceivers();\n for (let trackId of config.streamMap[source]) {\n let transceiver = transceivers.find(transceiver => transceiver.receiver.track && transceiver.receiver.track.kind === 'video' && transceiver.receiver.track.id === trackId);\n if (transceiver) {\n mid = transceiver.mid;\n break;\n }\n }\n }\n if (mid !== undefined) {\n if (!config.overriddenSimulcastMode[mid]) {\n config.overriddenSimulcastMode[mid] = {};\n }\n if (substream === null) {\n if (manual) {\n // reset to previous state\n config.overriddenSimulcastMode[mid]['defaultSubstream'] = null;\n config.overriddenSimulcastMode[mid]['mode'] = null;\n }\n resolve({\n substream,\n sender: handleId\n });\n return;\n }\n if (manual) {\n config.overriddenSimulcastMode[mid]['defaultSubstream'] = substream;\n config.overriddenSimulcastMode[mid]['mode'] = \"manual\";\n }\n this.ws.addEventListener('message', parseResponse);\n this._abortController.signal.addEventListener('abort', abortResponse);\n messageTimeoutId = setTimeout(() => {\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n reject('timeout');\n }, 10000);\n this.sendMessage(handleId, {\n \"body\": {\n \"request\": \"configure\",\n \"streams\": [{\n mid,\n substream: parseInt(substream)\n }]\n }\n });\n } else {\n reject('no mid found');\n }\n } else {\n reject('no source or mid');\n }\n });\n }\n setTalkIntercomChannels() {\n let groups = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['participants'];\n if (typeof groups !== 'object' || !(\"length\" in groups)) {\n this._log('setTalkIntercomChannels: groups must be an array');\n groups = [groups];\n }\n this._talkIntercomChannels = structuredClone(groups);\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let config = handle.webrtcStuff;\n let transceivers = config.pc.getTransceivers();\n let descriptions = [];\n Object.keys(config.streamMap).forEach(source => {\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n config.streamMap[source].forEach(trackId => {\n let t = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.id === trackId);\n if (t) {\n descriptions.push({\n mid: t.mid,\n description: JSON.stringify({\n simulcastBitrates: simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates,\n intercomGroups: groups,\n source: source\n })\n });\n }\n });\n });\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"configure\",\n descriptions: descriptions\n }\n });\n }\n setListenIntercomChannels() {\n let groups = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['participants'];\n if (typeof groups !== 'object' || !(\"length\" in groups)) {\n this._log('setListenIntercomChannels: groups must be an array');\n groups = [groups];\n }\n this._listenIntercomChannels = structuredClone(groups);\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let promises = [];\n this._participants.forEach(participant => {\n if (participant.handleId === this.handleId) {\n return;\n }\n let handle = this._getHandle(participant.handleId);\n if (handle) {\n const tracksMap = handle.webrtcStuff.tracksMap.filter(t => t.active);\n const subscribe = [];\n const unsubscribe = [];\n tracksMap.forEach(track => {\n if (track.type === 'data') {\n return;\n }\n const description = JSON.parse(track.description);\n const intercomGroups = (description === null || description === void 0 ? void 0 : description.intercomGroups) || [];\n if (this._listenIntercomChannels.some(g => intercomGroups.includes(g))) {\n if (!this._isAlreadySubscribed(participant.handleId, track.id, track.mid)) {\n subscribe.push({\n feed: track.id,\n mid: track.mid\n });\n }\n } else {\n unsubscribe.push({\n feed: track.id,\n mid: track.mid\n });\n }\n });\n this._updateSubscribeMap(participant.handleId, subscribe, unsubscribe);\n if (subscribe.length || unsubscribe.length) {\n promises.push(this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"update\",\n ...(subscribe.length ? {\n subscribe\n } : {}),\n ...(unsubscribe.length ? {\n unsubscribe\n } : {})\n }\n }));\n }\n }\n });\n return Promise.all(promises);\n }\n setRoomType() {\n let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'watchparty';\n this._roomType = type;\n return this._roomType;\n }\n setRestrictSubscribeToUserIds() {\n let userIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n this._restrictSubscribeToUserIds = structuredClone(userIds);\n if (!this.isConnected) {\n return Promise.resolve(this._restrictSubscribeToUserIds);\n }\n // sanity check by getting listparticipants and comparing it to _remoteUsersCache\n this.sendMessage(this.handleId, {\n body: {\n request: 'listparticipants',\n room: this.roomId\n }\n }).then(r => {\n let participants = r.participants;\n let remoteUsersCache = this._remoteUsersCache;\n let handle = this._getHandle(this.handleId);\n\n // filter out my user id from response and compare it to remoteUsersCache\n participants = participants.filter(p => p.id !== handle.userId);\n\n // get rid of participants that are in participants but not in remoteUsersCache\n remoteUsersCache = remoteUsersCache.filter(r => participants.find(p => p.id === r.id));\n remoteUsersCache.forEach(r => {\n var _decodeJanusDisplay31;\n const handle = this._getHandle(null, null, (_decodeJanusDisplay31 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(r.userId)) === null || _decodeJanusDisplay31 === void 0 ? void 0 : _decodeJanusDisplay31.userId);\n if (this._participantShouldSubscribe(r.userId)) {\n var _handle$webrtcStuff6;\n // todo: do a nicer flag to indicate inactive handle than just checking for pc\n if (!handle || !((_handle$webrtcStuff6 = handle.webrtcStuff) !== null && _handle$webrtcStuff6 !== void 0 && _handle$webrtcStuff6.pc)) {\n this._log('Subscribing to ', r.userId);\n this._createParticipant(r.userId, r.id).then(handle => {\n this._updateParticipantsTrackData(handle.handleId, r.streams);\n const subscribe = r.streams.filter(s => !s.disabled && this._intercomSubscribe(s)).map(stream => ({\n feed: stream.id,\n mid: stream.mid\n }));\n handle.webrtcStuff.subscribeMap = structuredClone(subscribe);\n return this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": this.roomId,\n \"ptype\": \"subscriber\",\n \"private_id\": this.privateId,\n streams: subscribe,\n //\"feed\": id,\n ...(this.webrtcVersion > 1000 ? {\n id: this.userId\n } : {}),\n pin: this.pin\n }\n });\n }).catch(err => {\n this.emit('error', err);\n });\n } else {\n this._log('Already subscribed to ', r.userId);\n }\n } else if (handle) {\n this._log('Unsubscribing from ', r.userId);\n this._removeParticipant(handle.handleId);\n }\n });\n });\n }\n}\n_defineProperty(RoomSession, \"sessionTypes\", {\n 'reactooroom': 'janus.plugin.reactooroom',\n 'streaming': 'janus.plugin.streaming'\n});\n_defineProperty(RoomSession, \"userRoleSubscriptionRules\", {\n participant: {\n \"watchparty\": ['participant', 'talkback'],\n \"studio\": ['participant', 'talkback', 'host', 'observer'],\n \"commentary\": ['participant', 'talkback', 'host'],\n \"intercom\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3'],\n \"videowall\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3'],\n \"videowall-queue\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3'],\n \"videowall-queue-video\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3']\n },\n monitor: {\n \"watchparty\": ['participant', 'host'],\n \"studio\": ['participant', 'host', 'observer'],\n \"commentary\": ['participant', 'host'],\n \"intercom\": ['host', 'participant'],\n \"videowall\": ['host', 'participant'],\n \"videowall-queue\": ['host', 'participant'],\n \"videowall-queue-video\": ['host', 'participant']\n },\n talkback: {\n \"watchparty\": ['participant', 'host', 'talkback'],\n \"studio\": ['participant', 'host', 'observer', 'talkback'],\n \"commentary\": ['host', 'participant', 'talkback'],\n \"intercom\": ['host', 'participant', 'talkback'],\n \"videowall\": ['host', 'participant', 'talkback'],\n \"videowall-queue\": ['host', 'participant', 'talkback'],\n \"videowall-queue-video\": ['host', 'participant', 'talkback']\n },\n observer: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n observerSolo1: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n observerSolo2: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n observerSolo3: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n host: {\n \"watchparty\": [],\n \"studio\": [],\n \"commentary\": [],\n \"intercom\": [],\n \"videowall\": [],\n \"videowall-queue\": [],\n \"videowall-queue-video\": []\n },\n companionTV: {},\n companionPhone: {}\n});\n/* harmony default export */ __webpack_exports__[\"default\"] = (Room);\n\n//# sourceURL=webpack://WatchTogetherSDK/./src/modules/wt-room.js?");
|
|
10513
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webrtc-adapter */ \"./node_modules/webrtc-adapter/src/js/adapter_core.js\");\n/* harmony import */ var _wt_emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./wt-emitter */ \"./src/modules/wt-emitter.js\");\n/* harmony import */ var _wt_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./wt-utils */ \"./src/modules/wt-utils.js\");\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n// Watch together janus webrtc library\n\n\n\n\nclass Room {\n constructor(debug) {\n this.debug = debug;\n this.sessions = [];\n this.safariVp8 = false;\n this.browser = webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser;\n this.browserDetails = webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails;\n this.webrtcSupported = Room.isWebrtcSupported();\n this.safariVp8TestPromise = Room.testSafariVp8();\n this.safariVp8 = null;\n this.safariVp8TestPromise.then(safariVp8 => {\n this.safariVp8 = safariVp8;\n });\n\n // Let's get it started\n this.whenInitialized = this.initialize();\n }\n initialize() {\n return this.safariVp8TestPromise.then(() => this);\n }\n createSession() {\n let constructId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'reactooroom';\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return new RoomSession(constructId, type, {\n debug: this.debug,\n ...options\n });\n }\n static testSafariVp8() {\n return new Promise(resolve => {\n if (webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser === 'safari' && webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.version >= 605) {\n if (RTCRtpSender && RTCRtpSender.getCapabilities && RTCRtpSender.getCapabilities(\"video\") && RTCRtpSender.getCapabilities(\"video\").codecs && RTCRtpSender.getCapabilities(\"video\").codecs.length) {\n var isVp8 = false;\n for (var i in RTCRtpSender.getCapabilities(\"video\").codecs) {\n var codec = RTCRtpSender.getCapabilities(\"video\").codecs[i];\n if (codec && codec.mimeType && codec.mimeType.toLowerCase() === \"video/vp8\") {\n isVp8 = true;\n break;\n }\n }\n resolve(isVp8);\n } else {\n // We do it in a very ugly way, as there's no alternative...\n // We create a PeerConnection to see if VP8 is in an offer\n var testpc = new RTCPeerConnection({}, {});\n testpc.createOffer({\n offerToReceiveVideo: true\n }).then(function (offer) {\n let result = offer.sdp.indexOf(\"VP8\") !== -1;\n testpc.close();\n testpc = null;\n resolve(result);\n });\n }\n } else resolve(false);\n });\n }\n static isWebrtcSupported() {\n return window.RTCPeerConnection !== undefined && window.RTCPeerConnection !== null && navigator.mediaDevices !== undefined && navigator.mediaDevices !== null && navigator.mediaDevices.getUserMedia !== undefined && navigator.mediaDevices.getUserMedia !== null;\n }\n}\nclass RoomSession {\n static noop() {}\n static randomString(len) {\n var charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var randomString = '';\n for (var i = 0; i < len; i++) {\n var randomPoz = Math.floor(Math.random() * charSet.length);\n randomString += charSet.substring(randomPoz, randomPoz + 1);\n }\n return randomString;\n }\n constructor() {\n let constructId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'reactooroom';\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n _defineProperty(this, \"_intercomSubscribe\", stream => {\n var _JSON$parse;\n if (stream.type === 'data') {\n return true;\n }\n const intercomGroups = ((_JSON$parse = JSON.parse(stream.description || \"[]\")) === null || _JSON$parse === void 0 ? void 0 : _JSON$parse.intercomGroups) || [];\n return intercomGroups.some(g => this._listenIntercomChannels.indexOf(g) > -1);\n });\n Object.assign(this, Object(_wt_emitter__WEBPACK_IMPORTED_MODULE_1__[\"default\"])());\n this.options = {\n ...options\n };\n this.defaultDataChannelLabel = 'JanusDataChannel';\n this.server = null;\n this.iceServers = null;\n this.token = null;\n this.roomId = null;\n this.streamId = null;\n this.pin = null;\n this.userId = null;\n this.sessiontype = type;\n this.initialBitrate = 0;\n this.enableDtx = false;\n this.simulcast = false;\n this.defaultSimulcastSettings = {\n \"default\": {\n mode: \"controlled\",\n // controlled, manual, browserControlled\n defaultSubstream: 0,\n // 2 lowest quality, 0 highest quality\n bitrates: [{\n \"rid\": \"l\",\n \"active\": true,\n \"maxBitrate\": 180000,\n \"maxFramerate\": 20,\n \"scaleResolutionDownBy\": 3.3333333333333335,\n \"priority\": \"low\"\n }, {\n \"rid\": \"m\",\n \"active\": true,\n \"maxBitrate\": 500000,\n \"maxFramerate\": 25,\n \"scaleResolutionDownBy\": 1.3333333333333335,\n \"priority\": \"low\"\n }, {\n \"rid\": \"h\",\n \"active\": true,\n \"maxBitrate\": 2000000,\n \"maxFramerate\": 30,\n \"priority\": \"low\"\n }]\n }\n };\n this.recordingFilename = null;\n this.pluginName = RoomSession.sessionTypes[type];\n this.id = null;\n this.privateId = null;\n this.constructId = constructId || RoomSession.randomString(16);\n this.sessionId = null;\n this.handleId = null;\n this.ws = null;\n this.isRestarting = false;\n this.isConnecting = false;\n this.isDisconnecting = false;\n this.isConnected = false;\n this.isPublished = false;\n this.isReclaiming = false;\n this.isStreaming = false;\n this.isMuted = [];\n this.isVideoEnabled = false;\n this.isAudioEnabed = false;\n this._statsMaxLength = 31;\n this._upStatsLength = 30;\n this._downStatsLength = 5;\n this._statsTimeoutStopped = true;\n this._statsTimeoutId = null;\n this._statsInterval = 1000;\n this._aqInterval = 2500;\n this._aqIntervalCounter = 0;\n this._aqIntervalDivisor = 4;\n this._aqTimeoutId = null;\n this._sendMessageTimeout = 5000;\n this._retries = 0;\n this._maxRetries = 5;\n this._keepAliveId = null;\n this._participants = [];\n this._restrictSubscribeToUserIds = []; // all if empty\n this._talkIntercomChannels = ['participants'];\n this._listenIntercomChannels = ['participants'];\n this._roomType = 'watchparty';\n this._isDataChannelOpen = false;\n this._abortController = null;\n this._remoteUsersCache = [];\n this.userRoleSubscriptionRules = {\n ...RoomSession.userRoleSubscriptionRules,\n ...(this.options.userRoleSubscriptionRules || {})\n };\n this._log = RoomSession.noop;\n if (this.options.debug) {\n this._enableDebug();\n }\n }\n _pushToRemoteUsersCache(userId, streams, id) {\n const existingIndex = this._remoteUsersCache.findIndex(u => u.userId === userId);\n if (existingIndex > -1) {\n this._remoteUsersCache.splice(existingIndex, 1, {\n userId,\n streams,\n id\n });\n } else {\n this._remoteUsersCache.push({\n userId,\n streams,\n id\n });\n }\n }\n _removeFromRemoteUsersCache(rfid) {\n const existingIndex = this._remoteUsersCache.findIndex(u => u.id === rfid);\n if (existingIndex > -1) {\n this._remoteUsersCache.splice(existingIndex, 1);\n }\n }\n _participantShouldSubscribe(userId) {\n const myUser = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display);\n const remoteUser = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(userId);\n let localUserRole = (myUser === null || myUser === void 0 ? void 0 : myUser.role) || 'participant';\n let remoteUserRole = (remoteUser === null || remoteUser === void 0 ? void 0 : remoteUser.role) || 'participant';\n return this.userRoleSubscriptionRules[localUserRole][this._roomType || 'watchparty'].indexOf(remoteUserRole) > -1 && (this._restrictSubscribeToUserIds.length === 0 || this._restrictSubscribeToUserIds.indexOf(remoteUser === null || remoteUser === void 0 ? void 0 : remoteUser.userId) > -1);\n }\n _getAddParticipantEventName(handleId) {\n var _decodeJanusDisplay;\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'getParticipantEventName']\n });\n return;\n }\n const participantRole = (_decodeJanusDisplay = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay === void 0 ? void 0 : _decodeJanusDisplay.role;\n switch (participantRole) {\n case 'participant':\n return 'addRemoteParticipant';\n case 'talkback':\n return 'addRemoteTalkback';\n case 'monitor':\n return 'addRemoteTalkback';\n case 'observer':\n case 'observerSolo1':\n case 'observerSolo2':\n case 'observerSolo3':\n return 'addRemoteObserver';\n case 'host':\n return 'addRemoteInstructor';\n case 'companionTV':\n return 'addRemoteCompanionTV';\n case 'companionPhone':\n return 'addRemoteCompanionPhone';\n default:\n return 'addRemoteParticipant';\n }\n }\n _getRemoveParticipantEventName(handleId) {\n var _decodeJanusDisplay2;\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'getParticipantEventName']\n });\n return;\n }\n const participantRole = (_decodeJanusDisplay2 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay2 === void 0 ? void 0 : _decodeJanusDisplay2.role;\n switch (participantRole) {\n case 'participant':\n return 'removeRemoteParticipant';\n case 'talkback':\n return 'removeRemoteTalkback';\n case 'monitor':\n return 'removeRemoteTalkback';\n case 'observer':\n case 'observerSolo1':\n case 'observerSolo2':\n case 'observerSolo3':\n return 'removeRemoteObserver';\n case 'host':\n return 'removeRemoteInstructor';\n case 'companionTV':\n return 'removeRemoteCompanionTV';\n case 'companionPhone':\n return 'removeRemoteCompanionPhone';\n default:\n return 'removeRemoteParticipant';\n }\n }\n sendMessage(handleId) {\n let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n body: 'Example Body'\n };\n let dontWait = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n let dontResolveOnAck = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n let retry = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;\n return this._send({\n \"janus\": \"message\",\n \"handle_id\": handleId,\n ...message\n }, dontWait, dontResolveOnAck, retry).then(json => {\n if (json && json[\"janus\"] === \"success\") {\n let plugindata = json[\"plugindata\"] || {};\n let data = plugindata[\"data\"];\n return Promise.resolve(data);\n }\n return Promise.resolve();\n }).catch(json => {\n if (json && json[\"error\"]) {\n return Promise.reject({\n type: 'warning',\n id: 1,\n message: 'sendMessage failed',\n data: json[\"error\"]\n });\n } else {\n return Promise.reject({\n type: 'warning',\n id: 1,\n message: 'sendMessage failed',\n data: json\n });\n }\n });\n }\n _send() {\n let request = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let ignoreResponse = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n let dontResolveOnAck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n let retry = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n let transaction = RoomSession.randomString(12);\n let requestData = {\n ...request,\n transaction,\n token: this.token,\n ...(this.sessionId && {\n 'session_id': this.sessionId\n } || {})\n };\n this._log(requestData);\n const op = () => new Promise((resolve, reject) => {\n let messageTimeoutId = null;\n let abortResponse = () => {\n this._abortController.signal.removeEventListener('abort', abortResponse);\n clearTimeout(messageTimeoutId);\n this.ws.removeEventListener('message', parseResponse);\n reject({\n type: 'warning',\n id: 17,\n message: 'connection cancelled'\n });\n };\n let parseResponse = event => {\n let json = JSON.parse(event.data);\n let r_transaction = json['transaction'];\n if (r_transaction === transaction && (!dontResolveOnAck || json['janus'] !== 'ack')) {\n clearTimeout(messageTimeoutId);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n if (json['janus'] === 'error') {\n var _json$error;\n if ((json === null || json === void 0 ? void 0 : (_json$error = json.error) === null || _json$error === void 0 ? void 0 : _json$error.code) == 403) {\n this.disconnect(true);\n }\n reject({\n type: 'error',\n id: 2,\n message: 'send failed',\n data: json,\n requestData\n });\n } else {\n resolve(json);\n }\n }\n };\n if (ignoreResponse) {\n if (this.ws && this.ws.readyState === 1) {\n this.ws.send(JSON.stringify(requestData));\n }\n resolve();\n } else {\n if (this.ws && this.ws.readyState === 1) {\n this.ws.addEventListener('message', parseResponse);\n messageTimeoutId = setTimeout(() => {\n this.ws.removeEventListener('message', parseResponse);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n reject({\n type: 'warning',\n id: 3,\n message: 'send timeout',\n data: requestData\n });\n }, this._sendMessageTimeout);\n this._abortController.signal.addEventListener('abort', abortResponse);\n this.ws.send(JSON.stringify(requestData));\n } else {\n reject({\n type: 'warning',\n id: 29,\n message: 'No connection to WebSockets',\n data: requestData\n });\n }\n }\n });\n return op().catch(e => {\n if (e.id === 17) {\n return Promise.reject(e);\n } else if (e.id === 29 && retry > 0) {\n return Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"wait\"])(this._sendMessageTimeout).then(() => this._send(request, ignoreResponse, dontResolveOnAck, retry - 1));\n } else if (retry > 0) {\n return this._send(request, ignoreResponse, dontResolveOnAck, retry - 1);\n } else {\n return Promise.reject(e);\n }\n });\n }\n _connectionClosed() {\n if (!this.isConnected || this.isConnecting || this.isDisconnecting) {\n return;\n }\n if (this._retries < this._maxRetries) {\n setTimeout(() => {\n this._retries++;\n this._reconnect().catch(e => {\n this.emit('error', e);\n });\n }, 3000 * this._retries);\n } else {\n if (this.sessiontype === 'reactooroom') {\n this.disconnect(true);\n } else if (this.sessiontype === 'streaming') {\n this.stopStream();\n }\n this.emit('error', {\n type: 'error',\n id: 4,\n message: 'Lost connection to WebSockets',\n data: null\n });\n }\n }\n _wipeListeners() {\n if (this.ws) {\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n }\n }\n _startKeepAlive() {\n this._send({\n \"janus\": \"keepalive\"\n }).then(json => {\n if (json[\"janus\"] !== 'ack') {\n this.emit('error', {\n type: 'warning',\n id: 5,\n message: 'keepalive response suspicious',\n data: json[\"janus\"]\n });\n }\n }).catch(e => {\n this.emit('error', {\n type: 'warning',\n id: 6,\n message: 'keepalive dead',\n data: e\n });\n this._connectionClosed();\n });\n this._keepAliveId = setTimeout(() => {\n this._startKeepAlive();\n }, 10000);\n }\n _stopKeepAlive() {\n clearTimeout(this._keepAliveId);\n }\n _handleWsEvents(event) {\n let json = JSON.parse(event.data);\n var sender = json[\"sender\"];\n var type = json[\"janus\"];\n let handle = this._getHandle(sender);\n if (!handle) {\n return;\n }\n if (type === \"trickle\") {\n let candidate = json[\"candidate\"];\n let config = handle.webrtcStuff;\n if (config.pc && config.remoteSdp) {\n if (!candidate || candidate.completed === true) {\n config.pc.addIceCandidate(null);\n } else {\n config.pc.addIceCandidate(candidate);\n }\n } else {\n if (!config.candidates) {\n config.candidates = [];\n }\n config.candidates.push(candidate);\n }\n } else if (type === \"webrtcup\") {\n //none universal\n } else if (type === \"hangup\") {\n this._log('hangup on', handle.handleId, handle.handleId === this.handleId, json);\n this._removeParticipant(handle.handleId, null, false);\n } else if (type === \"detached\") {\n this._log('detached on', handle.handleId, handle.handleId === this.handleId, json);\n this._removeParticipant(handle.handleId, null, true);\n } else if (type === \"media\") {\n this._log('Media event:', handle.handleId, json[\"type\"], json[\"receiving\"], json[\"mid\"]);\n } else if (type === \"slowlink\") {\n this._log('Slowlink', handle.handleId, json[\"uplink\"], json[\"lost\"], json[\"mid\"]);\n } else if (type === \"event\") {\n //none universal\n } else if (type === 'timeout') {\n this._log('WebSockets Gateway timeout', json);\n this.ws.close(3504, \"Gateway timeout\");\n } else if (type === 'success' || type === 'error') {\n // we're capturing those elsewhere\n } else {\n this._log(`Unknown event: ${type} on session: ${this.sessionId}`);\n }\n\n // LOCAL\n\n if (sender === this.handleId) {\n if (type === \"event\") {\n var plugindata = json[\"plugindata\"] || {};\n var msg = plugindata[\"data\"] || {};\n var jsep = json[\"jsep\"];\n let result = msg[\"result\"] || null;\n let event = msg[\"videoroom\"] || null;\n let list = msg[\"publishers\"] || {};\n let leaving = msg[\"leaving\"];\n let kicked = msg[\"kicked\"];\n let substream = msg[\"substream\"];\n let temporal = msg[\"temporal\"];\n\n //let joining = msg[\"joining\"];\n let unpublished = msg[\"unpublished\"];\n let error = msg[\"error\"];\n if (event === \"joined\") {\n var _decodeJanusDisplay3, _decodeJanusDisplay4;\n this.id = msg[\"id\"];\n this.privateId = msg[\"private_id\"];\n this.isConnected = true;\n this._log('We have successfully joined Room');\n this.emit('joined', true, this.constructId);\n this.emit('addLocalParticipant', {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay3 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay3 === void 0 ? void 0 : _decodeJanusDisplay3.userId,\n role: (_decodeJanusDisplay4 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display)) === null || _decodeJanusDisplay4 === void 0 ? void 0 : _decodeJanusDisplay4.role,\n track: null,\n stream: null,\n streamMap: {},\n source: null,\n adding: false,\n removing: false,\n hasAudioTrack: false,\n hasVideoTrack: false\n });\n for (let f in list) {\n let userId = list[f][\"display\"];\n let streams = list[f][\"streams\"] || [];\n let id = list[f][\"id\"];\n for (let i in streams) {\n streams[i][\"id\"] = id;\n streams[i][\"display\"] = userId;\n }\n this._log('Remote userId: ', userId);\n this._pushToRemoteUsersCache(userId, streams, id);\n if (this._participantShouldSubscribe(userId)) {\n this._log('Creating user: ', userId);\n this._createParticipant(userId, id).then(handle => {\n this._updateParticipantsTrackData(handle.handleId, streams);\n const subscribe = streams.filter(s => !s.disabled && this._intercomSubscribe(s)).map(stream => ({\n feed: stream.id,\n mid: stream.mid\n }));\n handle.webrtcStuff.subscribeMap = structuredClone(subscribe);\n return this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": this.roomId,\n \"ptype\": \"subscriber\",\n \"private_id\": this.privateId,\n streams: subscribe,\n //\"feed\": id,\n ...(this.webrtcVersion > 1000 ? {\n id: this.userId\n } : {}),\n pin: this.pin\n }\n });\n }).catch(err => {\n this.emit('error', err);\n });\n }\n }\n } else if (event === \"event\") {\n if (substream !== undefined && substream !== null) {\n this._log('Substream event:', substream, sender);\n }\n if (temporal !== undefined && temporal !== null) {\n this._log('Temporal event:', temporal);\n }\n if (msg[\"streams\"] !== undefined && msg[\"streams\"] !== null) {\n this._log('Got my own streams back', msg[\"streams\"]);\n }\n for (let f in list) {\n let userId = list[f][\"display\"];\n let streams = list[f][\"streams\"] || [];\n let id = list[f][\"id\"];\n for (let i in streams) {\n streams[i][\"id\"] = id;\n streams[i][\"display\"] = userId;\n }\n this._log('Remote userId: ', userId);\n this._pushToRemoteUsersCache(userId, streams, id);\n if (this._participantShouldSubscribe(userId)) {\n let handle = this._getHandle(null, id);\n if (handle) {\n this._updateParticipantsTrackData(handle.handleId, streams);\n let subscribe = streams.filter(stream => !stream.disabled && this._intercomSubscribe(stream) && !this._isAlreadySubscribed(handle.handleId, stream.id, stream.mid)).map(s => ({\n feed: s.id,\n mid: s.mid\n }));\n let unsubscribe = streams.filter(stream => stream.disabled || !this._intercomSubscribe(stream)).map(s => ({\n feed: s.id,\n mid: s.mid\n }));\n this._updateSubscribeMap(handle.handleId, subscribe, unsubscribe);\n this._log('Already subscribed to user: ', userId, 'Update streams', subscribe, unsubscribe);\n if (subscribe.length || unsubscribe.length) {\n this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"update\",\n ...(subscribe.length ? {\n subscribe\n } : {}),\n ...(unsubscribe.length ? {\n unsubscribe\n } : {})\n }\n });\n }\n } else {\n this._log('Creating user: ', userId, streams);\n this._createParticipant(userId, id).then(handle => {\n this._updateParticipantsTrackData(handle.handleId, streams);\n const subscribe = streams.filter(s => !s.disabled && this._intercomSubscribe(s)).map(stream => ({\n feed: stream.id,\n mid: stream.mid\n }));\n handle.webrtcStuff.subscribeMap = structuredClone(subscribe);\n return this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": this.roomId,\n \"ptype\": \"subscriber\",\n \"private_id\": this.privateId,\n streams: subscribe,\n ...(this.webrtcVersion > 1000 ? {\n id: this.userId\n } : {}),\n pin: this.pin\n }\n });\n }).catch(err => {\n this.emit('error', err);\n });\n }\n }\n }\n if (leaving === 'ok') {\n this._log('leaving', this.handleId, 'this is us');\n this._removeParticipant(this.handleId);\n if (msg['reason'] === 'kicked') {\n this.emit('kicked');\n this.disconnect().catch(() => {});\n }\n } else if (leaving) {\n //TODO: in 1 PeerConnection case we only unsubscribe from streams, this may not be true, check janus docs\n this._log('leaving', leaving);\n this._removeFromRemoteUsersCache(leaving);\n this._removeParticipant(null, leaving, true);\n }\n if (unpublished === 'ok') {\n this._log('unpublished', this.handleId, 'this is us');\n this._removeParticipant(this.handleId, null, false); // we do just hangup\n } else if (unpublished) {\n //TODO: in 1 PeerConnection case we only unsubscribe from streams\n this._log('unpublished', unpublished);\n this._removeFromRemoteUsersCache(unpublished);\n this._removeParticipant(null, unpublished, true); // we do hangup and detach\n }\n if (kicked === 'ok') {\n // this case shouldn't exist\n } else if (kicked) {\n this._log('kicked', kicked);\n this._removeFromRemoteUsersCache(kicked);\n this._removeParticipant(null, kicked, true); // we do hangup and detach\n }\n if (error) {\n this.emit('error', {\n type: 'error',\n id: 7,\n message: 'local participant error',\n data: [sender, msg]\n });\n }\n }\n\n // Streaming related\n else if (result && result[\"status\"]) {\n this.emit('streamingStatus', result[\"status\"]);\n if (result[\"status\"] === 'stopped') {\n this.stopStream();\n }\n if (result[\"status\"] === 'started') {\n this.emit('streaming', true);\n this.isStreaming = true;\n }\n }\n if (jsep !== undefined && jsep !== null) {\n if (this.sessiontype === 'reactooroom') {\n this._webrtcPeer(this.handleId, jsep).catch(err => {\n this.emit('error', err);\n });\n } else if (this.sessiontype === 'streaming') {\n this._publishRemote(this.handleId, jsep).catch(err => {\n this.emit('error', err);\n });\n }\n }\n } else if (type === \"webrtcup\") {\n if (this.simulcast) {\n return;\n }\n this._log('Configuring bitrate: ' + this.initialBitrate);\n if (this.initialBitrate > 0) {\n this.sendMessage(this.handleId, {\n \"body\": {\n \"request\": \"configure\",\n \"bitrate\": this.initialBitrate\n }\n }).catch(() => null);\n }\n }\n }\n\n //REMOTE\n else {\n let plugindata = json[\"plugindata\"] || {};\n let msg = plugindata[\"data\"] || {};\n let jsep = json[\"jsep\"];\n let event = msg[\"videoroom\"];\n let error = msg[\"error\"];\n let substream = msg[\"substream\"];\n let mid = msg[\"mid\"];\n let temporal = msg[\"temporal\"];\n if (substream !== undefined && substream !== null) {\n this._log('Substream: ', sender, mid, substream);\n this._setSelectedSubstream(sender, mid, substream);\n this._resetStats(sender, mid);\n this.requestKeyFrame(sender, mid);\n }\n if (temporal !== undefined && temporal !== null) {\n this._log('Temporal: ', temporal);\n }\n if (type === \"webrtcup\") {\n this.requestKeyFrame(handle.handleId);\n }\n if (event === \"updated\") {\n this._log('Remote has updated tracks', msg);\n if (msg[\"streams\"]) {\n this._updateTransceiverMap(handle.handleId, msg[\"streams\"]);\n }\n }\n if (event === \"attached\") {\n var _decodeJanusDisplay5, _decodeJanusDisplay6, _handle$webrtcStuff, _handle$webrtcStuff2, _handle$webrtcStuff3;\n this._log('Remote have successfully joined Room', msg);\n if (msg[\"streams\"]) {\n this._updateTransceiverMap(handle.handleId, msg[\"streams\"] || []);\n }\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay5 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay5 === void 0 ? void 0 : _decodeJanusDisplay5.userId,\n role: (_decodeJanusDisplay6 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay6 === void 0 ? void 0 : _decodeJanusDisplay6.role,\n stream: null,\n streamMap: structuredClone((_handle$webrtcStuff = handle.webrtcStuff) === null || _handle$webrtcStuff === void 0 ? void 0 : _handle$webrtcStuff.streamMap),\n tracksMap: structuredClone((_handle$webrtcStuff2 = handle.webrtcStuff) === null || _handle$webrtcStuff2 === void 0 ? void 0 : _handle$webrtcStuff2.tracksMap),\n transceiverMap: structuredClone((_handle$webrtcStuff3 = handle.webrtcStuff) === null || _handle$webrtcStuff3 === void 0 ? void 0 : _handle$webrtcStuff3.transceiverMap),\n source: null,\n track: null,\n adding: false,\n removing: false,\n constructId: this.constructId,\n hasAudioTrack: false,\n hasVideoTrack: false\n });\n }\n if (error) {\n this.emit('error', {\n type: 'warning',\n id: 8,\n message: 'remote participant error',\n data: [sender, msg]\n });\n }\n if (jsep) {\n this._publishRemote(handle.handleId, jsep).catch(err => {\n this.emit('error', err);\n });\n }\n }\n }\n _handleDataEvents(handleId, type, data) {\n let handle = this._getHandle(handleId);\n if (type === 'state') {\n this._log(` - Data channel status - `, `UID: ${handleId}`, `STATUS: ${JSON.stringify(data)}`, `ME: ${handleId === this.handleId}`);\n if (handle) {\n let config = handle.webrtcStuff;\n config.dataChannelOpen = this.defaultDataChannelLabel === (data === null || data === void 0 ? void 0 : data.label) && (data === null || data === void 0 ? void 0 : data.state) === 'open';\n }\n if (handleId === this.handleId && this.defaultDataChannelLabel === (data === null || data === void 0 ? void 0 : data.label)) {\n this._isDataChannelOpen = (data === null || data === void 0 ? void 0 : data.state) === 'open';\n this.emit('dataChannel', (data === null || data === void 0 ? void 0 : data.state) === 'open');\n }\n }\n if (type === 'error') {\n this.emit('error', {\n type: 'warning',\n id: 9,\n message: 'data event warning',\n data: [handleId, data]\n });\n if (handle) {\n let config = handle.webrtcStuff;\n if (this.defaultDataChannelLabel === data.label) {\n config.dataChannelOpen = false;\n }\n }\n if (handleId === this.handleId && this.defaultDataChannelLabel === data.label) {\n this._isDataChannelOpen = false;\n this.emit('dataChannel', false);\n }\n }\n if (handleId === this.handleId && type === 'message') {\n let d = null;\n try {\n d = JSON.parse(data);\n } catch (e) {\n this.emit('error', {\n type: 'warning',\n id: 10,\n message: 'data message parse error',\n data: [handleId, e]\n });\n return;\n }\n this.emit('data', d);\n }\n }\n\n //removeHandle === true -> hangup, detach, removeHandle === false -> hangup\n _removeParticipant(handleId, rfid) {\n let removeHandle = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n let handle = this._getHandle(handleId, rfid);\n if (!handle) {\n return Promise.resolve();\n } else {\n handleId = handle.handleId;\n }\n return this._send({\n \"janus\": \"hangup\",\n \"handle_id\": handleId\n }, true).then(() => removeHandle ? this._send({\n \"janus\": \"detach\",\n \"handle_id\": handleId\n }, true) : Promise.resolve()).finally(() => {\n try {\n if (handle.webrtcStuff.stream) {\n if (!this.isRestarting) {\n var _handle$webrtcStuff$s;\n (_handle$webrtcStuff$s = handle.webrtcStuff.stream) === null || _handle$webrtcStuff$s === void 0 ? void 0 : _handle$webrtcStuff$s.getTracks().forEach(track => track.stop());\n } else {\n var _handle$webrtcStuff$s2;\n (_handle$webrtcStuff$s2 = handle.webrtcStuff.stream) === null || _handle$webrtcStuff$s2 === void 0 ? void 0 : _handle$webrtcStuff$s2.getTracks().forEach(track => track.onended = null);\n }\n }\n } catch (e) {\n // Do nothing\n }\n if (handle.webrtcStuff.stream) {\n handle.webrtcStuff.stream.onremovetrack = null;\n handle.webrtcStuff.stream = null;\n }\n if (handle.webrtcStuff.dataChannel) {\n Object.keys(handle.webrtcStuff.dataChannel).forEach(label => {\n handle.webrtcStuff.dataChannel[label].onmessage = null;\n handle.webrtcStuff.dataChannel[label].onopen = null;\n handle.webrtcStuff.dataChannel[label].onclose = null;\n handle.webrtcStuff.dataChannel[label].onerror = null;\n });\n }\n if (handle.webrtcStuff.pc) {\n handle.webrtcStuff.pc.onicecandidate = null;\n handle.webrtcStuff.pc.ontrack = null;\n handle.webrtcStuff.pc.ondatachannel = null;\n handle.webrtcStuff.pc.onconnectionstatechange = null;\n handle.webrtcStuff.pc.oniceconnectionstatechange = null;\n }\n try {\n handle.webrtcStuff.pc.close();\n } catch (e) {}\n handle.webrtcStuff = {\n stream: null,\n streamMap: {},\n tracksMap: [],\n transceiverMap: [],\n subscribeMap: [],\n mySdp: null,\n mediaConstraints: null,\n pc: null,\n dataChannelOpen: false,\n dataChannel: null,\n dtmfSender: null,\n trickle: true,\n iceDone: false,\n isIceRestarting: false,\n stats: {},\n selectedSubstream: {},\n initialSimulcastSubstreamBeenSet: {},\n overriddenSimulcastMode: {}\n };\n if (handleId === this.handleId) {\n var _decodeJanusDisplay7, _decodeJanusDisplay8;\n this._isDataChannelOpen = false;\n this.isPublished = false;\n this.emit('published', {\n status: false,\n hasStream: false\n });\n this.emit('removeLocalParticipant', {\n id: handleId,\n userId: (_decodeJanusDisplay7 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay7 === void 0 ? void 0 : _decodeJanusDisplay7.userId,\n role: (_decodeJanusDisplay8 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay8 === void 0 ? void 0 : _decodeJanusDisplay8.role\n });\n } else {\n var _decodeJanusDisplay9, _decodeJanusDisplay10;\n this.emit(this._getRemoveParticipantEventName(handleId), {\n id: handleId,\n userId: (_decodeJanusDisplay9 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay9 === void 0 ? void 0 : _decodeJanusDisplay9.userId,\n role: (_decodeJanusDisplay10 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay10 === void 0 ? void 0 : _decodeJanusDisplay10.role\n });\n }\n if (removeHandle) {\n let handleIndex = this._participants.findIndex(p => p.handleId === handleId);\n this._participants.splice(handleIndex, 1);\n }\n return true;\n });\n }\n _createParticipant() {\n let userId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let rfid = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n return this._send({\n \"janus\": \"attach\",\n \"plugin\": this.pluginName\n }).then(json => {\n let handleId = json.data[\"id\"];\n let handle = {\n handleId,\n rfid,\n userId,\n webrtcStuff: {\n stream: null,\n streamMap: {},\n tracksMap: [],\n transceiverMap: [],\n subscribeMap: [],\n mySdp: null,\n mediaConstraints: null,\n pc: null,\n dataChannelOpen: false,\n dataChannel: null,\n dtmfSender: null,\n trickle: true,\n iceDone: false,\n isIceRestarting: false,\n stats: {},\n selectedSubstream: {},\n initialSimulcastSubstreamBeenSet: {},\n overriddenSimulcastMode: {}\n }\n };\n this._participants.push(handle);\n return handle;\n });\n }\n _updateSubscribeMap(handleId, subscribe, unsubscribe) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateSubscribeMap']\n });\n return;\n }\n let currentSubscribeMap = handle.webrtcStuff.subscribeMap;\n subscribe.forEach(s => {\n if (!currentSubscribeMap.find(c => c.feed === s.feed && c.mid === s.mid)) {\n currentSubscribeMap.push(s);\n }\n });\n unsubscribe.forEach(s => {\n let index = currentSubscribeMap.findIndex(c => c.feed === s.feed && c.mid === s.mid);\n if (index > -1) {\n currentSubscribeMap.splice(index, 1);\n }\n });\n }\n _isAlreadySubscribed(handleId, feed, mid) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'isAlreadySubscribed']\n });\n return false;\n }\n return handle.webrtcStuff.subscribeMap.findIndex(t => t.mid === mid && t.feed === feed) > -1;\n }\n _updateTransceiverMap(handleId, streams) {\n this._log('Updating current transceiver map', handleId, streams);\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateTransceiverMap']\n });\n return;\n }\n let config = handle.webrtcStuff;\n config.transceiverMap = structuredClone(streams);\n }\n _updateParticipantsTrackData(handleId, streams) {\n this._log('Updating participants track data', handleId, streams);\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateParticipantsTrackData']\n });\n return;\n }\n let config = handle.webrtcStuff;\n config.tracksMap = structuredClone(streams.map(s => {\n let source = null;\n let simulcastBitrates = null;\n try {\n const description = JSON.parse(s.description);\n source = description === null || description === void 0 ? void 0 : description.source;\n simulcastBitrates = description === null || description === void 0 ? void 0 : description.simulcastBitrates;\n } catch (e) {}\n return {\n active: !s.disabled,\n description: s.description,\n source: source,\n simulcastBitrates: simulcastBitrates,\n display: s.display,\n id: s.id,\n mid: s.mid,\n mindex: s.mindex,\n codec: s.codec,\n type: s.type\n };\n }));\n }\n _updateRemoteParticipantStreamMap(handleId) {\n this._log('Updating participants stream map', handleId);\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'updateRemoteParticipantStreamMap']\n });\n return;\n }\n let config = handle.webrtcStuff;\n config.streamMap = {};\n config.transceiverMap.forEach(tItem => {\n var _JSON$parse2, _config$pc$getTransce, _config$pc$getTransce2, _config$pc$getTransce3;\n if (tItem.type === 'data') {\n return;\n }\n if (tItem.active === false) {\n return;\n }\n const source = (_JSON$parse2 = JSON.parse(tItem.feed_description)) === null || _JSON$parse2 === void 0 ? void 0 : _JSON$parse2.source;\n if (!config.streamMap[source]) {\n config.streamMap[source] = [];\n }\n let trackId = (_config$pc$getTransce = config.pc.getTransceivers().find(t => t.mid === tItem.mid)) === null || _config$pc$getTransce === void 0 ? void 0 : (_config$pc$getTransce2 = _config$pc$getTransce.receiver) === null || _config$pc$getTransce2 === void 0 ? void 0 : (_config$pc$getTransce3 = _config$pc$getTransce2.track) === null || _config$pc$getTransce3 === void 0 ? void 0 : _config$pc$getTransce3.id;\n if (trackId) {\n config.streamMap[source].push(trackId);\n }\n });\n }\n _joinRoom(roomId, pin, userId, display) {\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": roomId,\n \"pin\": pin,\n \"ptype\": \"publisher\",\n \"display\": display,\n ...(this.webrtcVersion > 1000 ? {\n id: userId\n } : {})\n }\n }, false, true);\n }\n _watchStream(id) {\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"watch\",\n id: String(id)\n }\n }, false, true);\n }\n _leaveRoom() {\n let dontWait = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n return this.isConnected ? this.sendMessage(this.handleId, {\n body: {\n \"request\": \"leave\"\n }\n }, dontWait).finally(() => {\n this.isConnected = false;\n this.emit('joined', false);\n }) : Promise.resolve();\n }\n\n // internal reconnect\n\n _reconnect() {\n if (this.isReclaiming) {\n return Promise.resolve();\n }\n if (this.ws) {\n this._wipeListeners();\n if (this.ws.readyState === 1) {\n this.ws.close();\n }\n }\n this._stopKeepAlive();\n this.isReclaiming = true;\n this.emit('joining', true);\n return new Promise((resolve, reject) => {\n let abortReconnect = () => {\n this._abortController.signal.removeEventListener('abort', abortReconnect);\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = null;\n this.ws.onerror = null;\n this.isReclaiming = false;\n this.emit('joining', false);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled',\n data: e\n });\n };\n this.ws = new WebSocket(this.server, 'janus-protocol');\n this.__connectionClosedBoundFn = this._connectionClosed.bind(this);\n this.__handleWsEventsBoundFn = this._handleWsEvents.bind(this);\n this.ws.addEventListener('close', this.__connectionClosedBoundFn);\n this.ws.addEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = () => {\n this._abortController.signal.removeEventListener('abort', abortReconnect);\n this._send({\n \"janus\": \"claim\"\n }).then(json => {\n this.sessionId = json[\"session_id\"] ? json[\"session_id\"] : json.data[\"id\"];\n this._startKeepAlive();\n this.isReclaiming = false;\n this.emit('joining', false);\n this._retries = 0;\n resolve(json);\n }).catch(error => {\n this.isReclaiming = false;\n this.emit('joining', false);\n reject({\n type: 'error',\n id: 11,\n message: 'reconnection error',\n data: error\n });\n });\n };\n\n // this is called before 'close' event callback so it doesn't break reconnect loop\n this.ws.onerror = e => {\n this._abortController.signal.removeEventListener('abort', abortReconnect);\n this.isReclaiming = false;\n this.emit('joining', false);\n reject({\n type: 'warning',\n id: 12,\n message: 'ws reconnection error',\n data: e\n });\n };\n this._abortController.signal.addEventListener('abort', abortReconnect);\n });\n }\n connect(roomId, pin, server, iceServers, token, display, userId) {\n let webrtcVersion = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0;\n let initialBitrate = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0;\n let recordingFilename = arguments.length > 9 ? arguments[9] : undefined;\n let simulcast = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : false;\n let simulcastSettings = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : this.defaultSimulcastSettings;\n let enableDtx = arguments.length > 12 && arguments[12] !== undefined ? arguments[12] : false;\n if (this.isConnecting) {\n return Promise.reject({\n type: 'warning',\n id: 16,\n message: 'connection already in progress'\n });\n }\n if (this.ws) {\n this._wipeListeners();\n }\n this._stopKeepAlive();\n this._abortController = new AbortController();\n this.sessionId = null;\n this.server = server;\n this.iceServers = iceServers;\n this.token = token;\n this.roomId = roomId;\n this.pin = pin;\n this.display = display;\n this.userId = userId;\n this.webrtcVersion = webrtcVersion;\n this.initialBitrate = initialBitrate;\n this.recordingFilename = recordingFilename;\n this.isConnecting = true;\n this.enableDtx = enableDtx;\n this.simulcast = simulcast;\n this.simulcastSettings = structuredClone(simulcastSettings);\n\n // sort simulcast bitrates\n if (this.simulcastSettings && typeof this.simulcastSettings === 'object' && Object.keys(this.simulcastSettings).length) {\n Object.keys(this.simulcastSettings).forEach(k => {\n this.simulcastSettings[k].bitrates = this.simulcastSettings[k].bitrates.sort((a, b) => {\n if (a.maxBitrate === b.maxBitrate) {\n return a.maxFramerate - b.maxFramerate;\n }\n return a.maxBitrate - b.maxBitrate;\n });\n });\n }\n this.emit('joining', true);\n return new Promise((resolve, reject) => {\n this.ws = new WebSocket(this.server, 'janus-protocol');\n this.__connectionClosedBoundFn = this._connectionClosed.bind(this);\n this.__handleWsEventsBoundFn = this._handleWsEvents.bind(this);\n let abortConnect = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = null;\n this.ws.onerror = null;\n this.isConnecting = false;\n this.emit('joining', false);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled'\n });\n };\n this.ws.addEventListener('close', this.__connectionClosedBoundFn);\n this.ws.addEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this._retries = 0;\n this._send({\n \"janus\": \"create\"\n }).then(json => {\n this.sessionId = json[\"session_id\"] ? json[\"session_id\"] : json.data[\"id\"];\n this._startKeepAlive();\n return 1;\n }).then(() => this._createParticipant(userId)).then(handle => {\n this.handleId = handle.handleId;\n return 1;\n }).then(() => this._joinRoom(roomId, pin, userId, display)).then(() => {\n this._enableStatsWatch();\n this._enableSubstreamAutoSelect();\n this.isConnecting = false;\n this.emit('joining', false);\n resolve(this);\n }).catch(error => {\n this.isConnecting = false;\n this.emit('joining', false);\n reject({\n type: (error === null || error === void 0 ? void 0 : error.type) === 'warning' ? 'warning' : 'error',\n id: 13,\n message: 'connection error',\n data: error\n });\n });\n };\n this.ws.onerror = e => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.isConnecting = false;\n this.emit('joining', false);\n reject({\n type: 'error',\n id: 14,\n message: 'ws connection error',\n data: e\n });\n };\n this._abortController.signal.addEventListener('abort', abortConnect);\n });\n }\n disconnect() {\n var _this$_abortControlle, _this$_abortControlle2;\n if (this.isDisconnecting) {\n return Promise.resolve();\n }\n (_this$_abortControlle = this._abortController) === null || _this$_abortControlle === void 0 ? void 0 : (_this$_abortControlle2 = _this$_abortControlle.abort) === null || _this$_abortControlle2 === void 0 ? void 0 : _this$_abortControlle2.call(_this$_abortControlle);\n this.isDisconnecting = true;\n this._stopKeepAlive();\n this._disableStatsWatch();\n this._disableSubstreamAutoSelect();\n let isConnected = this.isConnected;\n return Promise.all(this._participants.map(p => this._removeParticipant(p.handleId))).finally(() => {\n this._wipeListeners();\n if (this.ws && this.ws.readyState === 1) {\n this._send({\n \"janus\": \"destroy\"\n }, true);\n this.ws.close();\n }\n this.sessionId = null;\n this.isPublished = false;\n this.isConnected = false;\n this.isDisconnecting = false;\n this.emit('publishing', false);\n this.emit('published', {\n status: false,\n hasStream: false\n });\n this.emit('joining', false);\n this.emit('joined', false);\n this.emit('disconnect', isConnected);\n return Promise.resolve('Disconnected');\n });\n }\n startStream(streamId, server, iceServers, token, userId) {\n if (this.isConnecting) {\n return Promise.reject({\n type: 'warning',\n id: 16,\n message: 'connection error',\n data: 'Connection is in progress'\n });\n }\n if (this.ws) {\n this._wipeListeners();\n }\n this._stopKeepAlive();\n this._abortController = new AbortController();\n this.server = server;\n this.iceServers = iceServers;\n this.token = token;\n this.streamId = streamId;\n this.userId = userId;\n this.sessionId = null;\n this.isConnecting = true;\n this.emit('streamStarting', true);\n return new Promise((resolve, reject) => {\n this.ws = new WebSocket(this.server, 'janus-protocol');\n this.__connectionClosedBoundFn = this._connectionClosed.bind(this);\n this.__handleWsEventsBoundFn = this._handleWsEvents.bind(this);\n let abortConnect = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.ws.removeEventListener('close', this.__connectionClosedBoundFn);\n this.ws.removeEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = null;\n this.ws.onerror = null;\n this.isConnecting = false;\n this.emit('streamStarting', false);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled'\n });\n };\n this.ws.addEventListener('close', this.__connectionClosedBoundFn);\n this.ws.addEventListener('message', this.__handleWsEventsBoundFn);\n this.ws.onopen = () => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this._retries = 0;\n this._send({\n \"janus\": \"create\"\n }).then(json => {\n this.sessionId = json[\"session_id\"] ? json[\"session_id\"] : json.data[\"id\"];\n this._startKeepAlive();\n return 1;\n }).then(() => this._createParticipant(userId)).then(handle => {\n this.handleId = handle.handleId;\n return 1;\n }).then(() => this._watchStream(streamId)).then(() => {\n this.isConnecting = false;\n this.emit('streamStarting', false);\n resolve(this);\n }).catch(error => {\n this.isConnecting = false;\n this.emit('streamStarting', false);\n reject({\n type: 'error',\n id: 13,\n message: 'connection error',\n data: error\n });\n });\n };\n this.ws.onerror = e => {\n this._abortController.signal.removeEventListener('abort', abortConnect);\n this.isConnecting = false;\n this.emit('streamStarting', false);\n reject({\n type: 'error',\n id: 14,\n message: 'ws connection error',\n data: e\n });\n };\n this._abortController.signal.addEventListener('abort', abortConnect);\n });\n }\n stopStream() {\n var _this$_abortControlle3, _this$_abortControlle4;\n if (this.isDisconnecting) {\n return Promise.resolve();\n }\n (_this$_abortControlle3 = this._abortController) === null || _this$_abortControlle3 === void 0 ? void 0 : (_this$_abortControlle4 = _this$_abortControlle3.abort) === null || _this$_abortControlle4 === void 0 ? void 0 : _this$_abortControlle4.call(_this$_abortControlle3);\n this._stopKeepAlive();\n let isStreaming = this.isStreaming;\n this.isDisconnecting = true;\n return this._removeParticipant(this.handleId).finally(() => {\n this.sendMessage(this.handleId, {\n body: {\n \"request\": \"stop\"\n }\n }, true);\n this._wipeListeners();\n this._send({\n \"janus\": \"destroy\"\n }, true);\n if (this.ws && this.ws.readyState === 1) {\n this.ws.close();\n }\n this.sessionId = null;\n this.isDisconnecting = false;\n this.isStreaming = false;\n this.emit('streamStarting', false);\n this.emit('streaming', false);\n this.emit('disconnect', isStreaming);\n return Promise.resolve('Disconnected');\n });\n }\n destroy() {\n if (this.sessiontype === 'reactooroom') {\n return this.disconnect().then(() => {\n this.clear();\n return true;\n });\n } else if (this.sessiontype === 'streaming') {\n return this.stopStream().then(() => {\n this.clear();\n return true;\n });\n }\n }\n _enableDebug() {\n this._log = console.log.bind(console);\n }\n _getHandle(handleId) {\n let rfid = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n let userId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n return this._participants.find(p => {\n var _decodeJanusDisplay11;\n return p.handleId === handleId || rfid && p.rfid === rfid || userId && ((_decodeJanusDisplay11 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(p.userId)) === null || _decodeJanusDisplay11 === void 0 ? void 0 : _decodeJanusDisplay11.userId) === userId;\n });\n }\n _findSimulcastConfig(source, settings) {\n return Object.keys(settings).reduce((acc, key) => {\n var _key$match;\n if (settings[source]) {\n return settings[source];\n } else if (source.indexOf((_key$match = key.match(/\\*(.*?)\\*/)) === null || _key$match === void 0 ? void 0 : _key$match[1]) > -1) {\n return settings[key];\n } else return acc;\n }, settings['default']);\n }\n _disableStatsWatch() {\n if (this._statsTimeoutId) {\n clearInterval(this._statsTimeout);\n this._statsTimeoutStopped = true;\n this._statsTimeoutId = null;\n }\n }\n _enableStatsWatch() {\n if (this._statsTimeoutId) {\n clearTimeout(this._statsTimeoutId);\n this._statsTimeoutId = null;\n }\n this._statsTimeoutStopped = false;\n const loop = () => {\n let startTime = performance.now();\n let endTime = null;\n this._getStats('video').then(participantsStats => {\n endTime = performance.now();\n this._parseVideoStats(participantsStats);\n }).finally(() => {\n if (!this._statsTimeoutStopped) {\n this._statsTimeoutId = setTimeout(loop, this._statsInterval - Math.min(endTime - startTime, this._statsInterval));\n }\n });\n };\n loop();\n }\n\n // This method completely ignores temporal layers\n // We prefer higher fps and lower resolution so if the fps in not in the range of 0.7 of the max fps we go to the next lower resolution\n\n _enableSubstreamAutoSelect() {\n if (!this.simulcast) {\n return;\n }\n if (this._aqTimeoutId) {\n clearTimeout(this._aqTimeoutId);\n this._aqTimeoutId = null;\n this._aqIntervalCounter = 0;\n }\n const checkStats = () => {\n this._participants.forEach(p => {\n if (p.handleId !== this.handleId) {\n var _p$webrtcStuff, _p$webrtcStuff$pc, _transceivers$filter;\n const transceivers = (_p$webrtcStuff = p.webrtcStuff) === null || _p$webrtcStuff === void 0 ? void 0 : (_p$webrtcStuff$pc = _p$webrtcStuff.pc) === null || _p$webrtcStuff$pc === void 0 ? void 0 : _p$webrtcStuff$pc.getTransceivers();\n const mids = (transceivers === null || transceivers === void 0 ? void 0 : (_transceivers$filter = transceivers.filter(t => t.receiver.track.kind === \"video\")) === null || _transceivers$filter === void 0 ? void 0 : _transceivers$filter.map(t => t.mid)) || [];\n mids.forEach(mid => {\n var _p$webrtcStuff2, _p$webrtcStuff2$overr, _p$webrtcStuff3, _p$webrtcStuff3$overr;\n const {\n source,\n simulcastBitrates\n } = p.webrtcStuff.tracksMap.find(t => t.mid === mid) || {};\n\n // track is gone\n if (!simulcastBitrates) {\n return;\n }\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n const initialSubstreamBeenSet = !!p.webrtcStuff.initialSimulcastSubstreamBeenSet[mid];\n const defaultSelectedSubstream = ((_p$webrtcStuff2 = p.webrtcStuff) === null || _p$webrtcStuff2 === void 0 ? void 0 : (_p$webrtcStuff2$overr = _p$webrtcStuff2.overriddenSimulcastMode[mid]) === null || _p$webrtcStuff2$overr === void 0 ? void 0 : _p$webrtcStuff2$overr.defaultSubstream) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.defaultSubstream);\n const simulcastMode = ((_p$webrtcStuff3 = p.webrtcStuff) === null || _p$webrtcStuff3 === void 0 ? void 0 : (_p$webrtcStuff3$overr = _p$webrtcStuff3.overriddenSimulcastMode[mid]) === null || _p$webrtcStuff3$overr === void 0 ? void 0 : _p$webrtcStuff3$overr.mode) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.mode);\n if (simulcastMode === 'browserControlled') {\n // do nothing\n } else if (simulcastMode === 'manual' && this._aqIntervalCounter % this._aqIntervalDivisor === 0 || !initialSubstreamBeenSet) {\n p.webrtcStuff.initialSimulcastSubstreamBeenSet[mid] = true;\n const currentSubstream = p.webrtcStuff.selectedSubstream[mid];\n if (defaultSelectedSubstream !== undefined && defaultSelectedSubstream !== null && defaultSelectedSubstream !== currentSubstream) {\n this._log('Attempting to force substream quality', defaultSelectedSubstream);\n this.selectSubStream(p.handleId, defaultSelectedSubstream, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n } else if (simulcastMode === 'controlled') {\n var _p$webrtcStuff4, _p$webrtcStuff4$stats, _p$webrtcStuff4$stats2, _p$webrtcStuff5, _p$webrtcStuff5$stats, _p$webrtcStuff5$stats2;\n const currentSubstream = p.webrtcStuff.selectedSubstream[mid];\n const settingsForCurrentSubstream = simulcastBitrates === null || simulcastBitrates === void 0 ? void 0 : simulcastBitrates[simulcastBitrates.length - 1 - currentSubstream];\n let directionDecision = 0;\n if (((_p$webrtcStuff4 = p.webrtcStuff) === null || _p$webrtcStuff4 === void 0 ? void 0 : (_p$webrtcStuff4$stats = _p$webrtcStuff4.stats) === null || _p$webrtcStuff4$stats === void 0 ? void 0 : (_p$webrtcStuff4$stats2 = _p$webrtcStuff4$stats[mid]) === null || _p$webrtcStuff4$stats2 === void 0 ? void 0 : _p$webrtcStuff4$stats2.length) > this._upStatsLength) {\n const upMedianStats = this._calculateMedianStats(p.webrtcStuff.stats[mid].slice(this._upStatsLength * -1));\n if ((upMedianStats === null || upMedianStats === void 0 ? void 0 : upMedianStats.framesPerSecond) >= Math.floor(((settingsForCurrentSubstream === null || settingsForCurrentSubstream === void 0 ? void 0 : settingsForCurrentSubstream.maxFramerate) || 30) * 0.7) && (upMedianStats === null || upMedianStats === void 0 ? void 0 : upMedianStats.freezeDurationSinceLast) < this._upStatsLength * this._statsInterval * 0.33 / 1000 /* && upMedianStats?.freezeCountSinceLast < 3 */) {\n directionDecision = 1;\n }\n }\n if (((_p$webrtcStuff5 = p.webrtcStuff) === null || _p$webrtcStuff5 === void 0 ? void 0 : (_p$webrtcStuff5$stats = _p$webrtcStuff5.stats) === null || _p$webrtcStuff5$stats === void 0 ? void 0 : (_p$webrtcStuff5$stats2 = _p$webrtcStuff5$stats[mid]) === null || _p$webrtcStuff5$stats2 === void 0 ? void 0 : _p$webrtcStuff5$stats2.length) > this._downStatsLength) {\n const downMedianStats = this._calculateMedianStats(p.webrtcStuff.stats[mid].slice(this._downStatsLength * -1));\n if ((downMedianStats === null || downMedianStats === void 0 ? void 0 : downMedianStats.framesPerSecond) < Math.floor(((settingsForCurrentSubstream === null || settingsForCurrentSubstream === void 0 ? void 0 : settingsForCurrentSubstream.maxFramerate) || 30) * 0.7) || (downMedianStats === null || downMedianStats === void 0 ? void 0 : downMedianStats.freezeDurationSinceLast) > this._downStatsLength * this._statsInterval * 0.33 / 1000 /* || downMedianStats?.freezeCountSinceLast > 5 || downMedianStats?.jitter > maxJitter(settingsForCurrentSubstream.maxFramerate) */) {\n directionDecision = -1;\n }\n }\n if (directionDecision === -1) {\n if (currentSubstream < simulcastBitrates.length - 1) {\n this._log('Attempting to down the quality for mid: ', mid, ' quality:', currentSubstream + 1);\n this._resetStats(p.handleId, mid);\n this.selectSubStream(p.handleId, currentSubstream + 1, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n } else if (directionDecision === 1) {\n if (currentSubstream > 0) {\n this._log('Attempting to up the quality for mid: ', mid, ' quality:', currentSubstream - 1);\n this._resetStats(p.handleId, mid);\n this.selectSubStream(p.handleId, currentSubstream - 1, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n } else {\n this._log('No quality change for mid: ', mid);\n }\n }\n });\n }\n });\n this._aqIntervalCounter++;\n this._aqTimeoutId = setTimeout(checkStats, this._aqInterval);\n };\n checkStats();\n }\n _disableSubstreamAutoSelect() {\n if (this._aqTimeoutId) {\n clearTimeout(this._aqTimeoutId);\n this._aqTimeoutId = null;\n this._aqIntervalCounter = 0;\n }\n }\n _calculateMedianStats(stats) {\n let medianStats = {\n framesPerSecond: null,\n jitter: null,\n roundTripTime: null,\n freezeDurationSinceLast: null,\n freezeCountSinceLast: null\n };\n let keys = Object.keys(medianStats);\n keys.forEach(key => {\n if (key === 'freezeDurationSinceLast' || key === 'freezeCountSinceLast') {\n medianStats[key] = stats.reduce((acc, cur) => acc + cur[key], 0);\n }\n // median but ignore first value of stats array\n else {\n let values = stats.map(s => s[key]);\n medianStats[key] = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"median\"])(values);\n }\n });\n medianStats.statsLength = stats.length;\n return medianStats;\n }\n _parseVideoStats(participantsStats) {\n participantsStats.forEach(sourceStats => {\n sourceStats.forEach(participantStats => {\n var _participantStats$han;\n if (participantStats !== null && (participantStats === null || participantStats === void 0 ? void 0 : (_participantStats$han = participantStats.handle) === null || _participantStats$han === void 0 ? void 0 : _participantStats$han.handleId) !== this.handleId) {\n let handle = this._getHandle(participantStats.handle.handleId);\n if (handle) {\n var _decodeJanusDisplay12;\n if (!handle.webrtcStuff.stats[participantStats.mid]) {\n handle.webrtcStuff.stats[participantStats.mid] = [];\n }\n const stats = {\n framesPerSecond: null,\n framesDropped: null,\n totalFreezesDuration: null,\n freezeDurationSinceLast: null,\n freezeCount: null,\n jitter: null,\n packetsLost: null,\n nackCount: null,\n roundTripTime: null,\n width: null,\n height: null,\n networkType: null,\n powerEfficientDecoder: null\n };\n participantStats.stats.forEach(report => {\n var _handle$webrtcStuff4, _handle$webrtcStuff4$;\n const simulcastConfigForSource = this._findSimulcastConfig(participantStats.source, this.simulcastSettings);\n const simulcastMode = ((_handle$webrtcStuff4 = handle.webrtcStuff) === null || _handle$webrtcStuff4 === void 0 ? void 0 : (_handle$webrtcStuff4$ = _handle$webrtcStuff4.overriddenSimulcastMode[participantStats.mid]) === null || _handle$webrtcStuff4$ === void 0 ? void 0 : _handle$webrtcStuff4$.mode) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.mode);\n if (report.type === 'inbound-rtp' && report.kind === 'video') {\n var _handle$webrtcStuff$s3, _handle$webrtcStuff$s4, _handle$webrtcStuff$s5, _handle$webrtcStuff$s6, _handle$webrtcStuff$s7, _handle$webrtcStuff$s8, _handle$webrtcStuff$s9, _handle$webrtcStuff$s10, _handle$webrtcStuff$s11, _handle$webrtcStuff$s12;\n stats.framesPerSecond = report.framesPerSecond || 0;\n stats.framesDropped = report.framesDropped || 0;\n stats.totalFreezesDuration = report.totalFreezesDuration || 0;\n stats.freezeDurationSinceLast = (report.totalFreezesDuration || 0) - (((_handle$webrtcStuff$s3 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s3 === void 0 ? void 0 : (_handle$webrtcStuff$s4 = _handle$webrtcStuff$s3[participantStats.mid]) === null || _handle$webrtcStuff$s4 === void 0 ? void 0 : (_handle$webrtcStuff$s5 = _handle$webrtcStuff$s4[((_handle$webrtcStuff$s6 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s6 === void 0 ? void 0 : (_handle$webrtcStuff$s7 = _handle$webrtcStuff$s6[participantStats.mid]) === null || _handle$webrtcStuff$s7 === void 0 ? void 0 : _handle$webrtcStuff$s7.length) - 1]) === null || _handle$webrtcStuff$s5 === void 0 ? void 0 : _handle$webrtcStuff$s5.totalFreezesDuration) || 0);\n stats.freezeCount = report.freezeCount || 0;\n stats.freezeCountSinceLast = (report.freezeCount || 0) - (((_handle$webrtcStuff$s8 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s8 === void 0 ? void 0 : (_handle$webrtcStuff$s9 = _handle$webrtcStuff$s8[participantStats.mid]) === null || _handle$webrtcStuff$s9 === void 0 ? void 0 : (_handle$webrtcStuff$s10 = _handle$webrtcStuff$s9[((_handle$webrtcStuff$s11 = handle.webrtcStuff.stats) === null || _handle$webrtcStuff$s11 === void 0 ? void 0 : (_handle$webrtcStuff$s12 = _handle$webrtcStuff$s11[participantStats.mid]) === null || _handle$webrtcStuff$s12 === void 0 ? void 0 : _handle$webrtcStuff$s12.length) - 1]) === null || _handle$webrtcStuff$s10 === void 0 ? void 0 : _handle$webrtcStuff$s10.freezeCount) || 0);\n stats.jitter = report.jitter;\n stats.packetsLost = report.packetsLost;\n stats.nackCount = report.nackCount;\n stats.width = report.frameWidth;\n stats.height = report.frameHeight;\n stats.powerEfficientDecoder = report.powerEfficientDecoder;\n }\n if (report.type === 'candidate-pair') {\n stats.roundTripTime = report.currentRoundTripTime;\n }\n if (report.type === 'local-candidate') {\n stats.networkType = report.networkType;\n }\n stats.selectedSubstream = handle.webrtcStuff.selectedSubstream[participantStats.mid];\n stats.simulcastMode = simulcastMode;\n });\n\n // pushing stats into handle stats array but keeping only 6 last stats\n handle.webrtcStuff.stats[participantStats.mid].push(stats);\n if (handle.webrtcStuff.stats[participantStats.mid].length > this._statsMaxLength) {\n handle.webrtcStuff.stats[participantStats.mid].shift();\n }\n this.emit('rtcStats', {\n handleId: participantStats.handle.handleId,\n stats,\n userId: (_decodeJanusDisplay12 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(participantStats.handle.userId)) === null || _decodeJanusDisplay12 === void 0 ? void 0 : _decodeJanusDisplay12.userId,\n source: participantStats.source,\n mid: participantStats.mid\n });\n }\n }\n });\n });\n }\n _getStats() {\n let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n return Promise.all(this._participants.map(participant => {\n let mediaTrack = [];\n if (type === 'video') {\n var _participant$webrtcSt, _participant$webrtcSt2;\n mediaTrack = (participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt = participant.webrtcStuff) === null || _participant$webrtcSt === void 0 ? void 0 : (_participant$webrtcSt2 = _participant$webrtcSt.stream) === null || _participant$webrtcSt2 === void 0 ? void 0 : _participant$webrtcSt2.getVideoTracks()) || [];\n } else if (type === 'audio') {\n var _participant$webrtcSt3, _participant$webrtcSt4;\n mediaTrack = (participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt3 = participant.webrtcStuff) === null || _participant$webrtcSt3 === void 0 ? void 0 : (_participant$webrtcSt4 = _participant$webrtcSt3.stream) === null || _participant$webrtcSt4 === void 0 ? void 0 : _participant$webrtcSt4.getAudioTracks()) || [];\n }\n if (type !== null) {\n var _participant$webrtcSt5, _participant$webrtcSt6;\n const transceivers = participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt5 = participant.webrtcStuff) === null || _participant$webrtcSt5 === void 0 ? void 0 : (_participant$webrtcSt6 = _participant$webrtcSt5.pc) === null || _participant$webrtcSt6 === void 0 ? void 0 : _participant$webrtcSt6.getTransceivers();\n return Promise.all(mediaTrack.map(track => {\n var _transceivers$find;\n const source = Object.keys(participant.webrtcStuff.streamMap).find(s => participant.webrtcStuff.streamMap[s].find(t => t === track.id));\n const mid = (_transceivers$find = transceivers.find(t => {\n var _t$receiver, _t$receiver$track, _t$sender, _t$sender$track;\n return ((_t$receiver = t.receiver) === null || _t$receiver === void 0 ? void 0 : (_t$receiver$track = _t$receiver.track) === null || _t$receiver$track === void 0 ? void 0 : _t$receiver$track.id) === track.id || ((_t$sender = t.sender) === null || _t$sender === void 0 ? void 0 : (_t$sender$track = _t$sender.track) === null || _t$sender$track === void 0 ? void 0 : _t$sender$track.id) === track.id;\n })) === null || _transceivers$find === void 0 ? void 0 : _transceivers$find.mid;\n return participant.webrtcStuff.pc.getStats(track).then(r => ({\n stats: r,\n source,\n mid,\n handle: participant\n })).catch(e => Promise.reject({\n stats: null,\n error: e,\n handle: participant,\n source,\n mid\n }));\n }));\n } else {\n var _participant$webrtcSt7, _participant$webrtcSt8;\n return participant === null || participant === void 0 ? void 0 : (_participant$webrtcSt7 = participant.webrtcStuff) === null || _participant$webrtcSt7 === void 0 ? void 0 : (_participant$webrtcSt8 = _participant$webrtcSt7.pc) === null || _participant$webrtcSt8 === void 0 ? void 0 : _participant$webrtcSt8.getStats(null).then(r => ({\n handle: participant,\n stats: r\n })).catch(e => Promise.reject({\n handle: participant,\n error: e\n }));\n }\n }));\n }\n _resetStats(handleId, mid) {\n let handle = this._getHandle(handleId);\n if (handle) {\n let config = handle.webrtcStuff;\n if (!mid) {\n Object.keys(config.stats).forEach(mid => {\n config.stats[mid] = [config.stats[mid][config.stats[mid].length - 1]];\n });\n } else {\n // clearing stats for the new substream\n if (config.stats[mid]) {\n config.stats[mid] = [config.stats[mid][config.stats[mid].length - 1]];\n }\n }\n }\n }\n _sendTrickleCandidate(handleId, candidate) {\n return this._send({\n \"janus\": \"trickle\",\n \"candidate\": candidate,\n \"handle_id\": handleId\n }, false, false, 5);\n }\n _webrtc(handleId) {\n let enableOntrack = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n let handle = this._getHandle(handleId);\n if (!handle) {\n this.emit('error', {\n type: 'error',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'create rtc connection']\n });\n return;\n }\n let config = handle.webrtcStuff;\n if (!config.pc) {\n let pc_config = {\n \"iceServers\": this.iceServers,\n \"iceTransportPolicy\": 'all',\n \"bundlePolicy\": undefined\n };\n pc_config[\"sdpSemantics\"] = \"unified-plan\";\n let pc_constraints = {};\n if (webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser === \"edge\") {\n // This is Edge, enable BUNDLE explicitly\n pc_config.bundlePolicy = \"max-bundle\";\n }\n\n // pc_config.bundlePolicy = 'balanced';\n // pc_config.iceTransportPolicy = 'relay';\n // pc_config.rtcpMuxPolicy = \"negotiate\";\n\n this._log('new RTCPeerConnection', pc_config, pc_constraints);\n config.pc = new RTCPeerConnection(pc_config, pc_constraints);\n config.pc.onnegotiationneeded = () => {\n this._log('onnegotiationneeded');\n };\n config.pc.onconnectionstatechange = () => {\n if (config.pc.connectionState === 'failed') {\n this._log('connectionState failed');\n this._iceRestart(handleId);\n }\n this.emit('connectionState', [handleId, handleId === this.handleId, config.pc.connectionState]);\n if (handleId !== this.handleId && config.pc.connectionState === 'connected') {\n var _decodeJanusDisplay13, _decodeJanusDisplay14;\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay13 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay13 === void 0 ? void 0 : _decodeJanusDisplay13.userId,\n role: (_decodeJanusDisplay14 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay14 === void 0 ? void 0 : _decodeJanusDisplay14.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n track: null,\n source: null,\n constructId: this.constructId,\n adding: false,\n removing: false,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n }\n };\n config.pc.oniceconnectionstatechange = () => {\n if (config.pc.iceConnectionState === 'failed') {\n this._log('iceConnectionState failed');\n this._iceRestart(handleId);\n }\n this.emit('iceState', [handleId, handleId === this.handleId, config.pc.iceConnectionState]);\n if (handleId !== this.handleId && (config.pc.iceConnectionState === 'completed' || config.pc.iceConnectionState === 'connected')) {\n var _decodeJanusDisplay15, _decodeJanusDisplay16;\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay15 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay15 === void 0 ? void 0 : _decodeJanusDisplay15.userId,\n role: (_decodeJanusDisplay16 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay16 === void 0 ? void 0 : _decodeJanusDisplay16.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n track: null,\n source: null,\n constructId: this.constructId,\n adding: false,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n }\n };\n config.pc.onicecandidate = event => {\n if (event.candidate == null || webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser === 'edge' && event.candidate.candidate.indexOf('endOfCandidates') > 0) {\n config.iceDone = true;\n this._sendTrickleCandidate(handleId, {\n \"completed\": true\n }).catch(e => {\n this.emit('error', e);\n });\n } else {\n // JSON.stringify doesn't work on some WebRTC objects anymore\n // See https://code.google.com/p/chromium/issues/detail?id=467366\n var candidate = {\n \"candidate\": event.candidate.candidate,\n \"sdpMid\": event.candidate.sdpMid,\n \"sdpMLineIndex\": event.candidate.sdpMLineIndex\n };\n this._sendTrickleCandidate(handleId, candidate).catch(e => {\n this.emit('error', e);\n });\n }\n };\n if (enableOntrack) {\n config.pc.ontrack = event => {\n var _event$streams, _event$streams$;\n if (!event.streams) return;\n if (!config.stream) {\n config.stream = new MediaStream();\n }\n if (!((_event$streams = event.streams) !== null && _event$streams !== void 0 && (_event$streams$ = _event$streams[0]) !== null && _event$streams$ !== void 0 && _event$streams$.onremovetrack)) {\n event.streams[0].onremovetrack = ev => {\n var _config$stream, _config$pc, _config$pc$getTransce4, _decodeJanusDisplay17, _decodeJanusDisplay18;\n this._log('Remote track removed', ev);\n (_config$stream = config.stream) === null || _config$stream === void 0 ? void 0 : _config$stream.removeTrack(ev.track);\n\n // check if handle still exists\n if (!this._getHandle(handle.handleId)) {\n return;\n }\n this._updateRemoteParticipantStreamMap(handle.handleId);\n let transceiver = (_config$pc = config.pc) === null || _config$pc === void 0 ? void 0 : (_config$pc$getTransce4 = _config$pc.getTransceivers()) === null || _config$pc$getTransce4 === void 0 ? void 0 : _config$pc$getTransce4.find(t => t.receiver.track === ev.track);\n let mid = (transceiver === null || transceiver === void 0 ? void 0 : transceiver.mid) || ev.track.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.track.id));\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay17 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay17 === void 0 ? void 0 : _decodeJanusDisplay17.userId,\n role: (_decodeJanusDisplay18 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay18 === void 0 ? void 0 : _decodeJanusDisplay18.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n source,\n track: ev.track,\n adding: false,\n removing: true,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n };\n }\n if (event.track) {\n var _config$stream2, _decodeJanusDisplay19, _decodeJanusDisplay20;\n (_config$stream2 = config.stream) === null || _config$stream2 === void 0 ? void 0 : _config$stream2.addTrack(event.track);\n this._updateRemoteParticipantStreamMap(handle.handleId);\n let mid = event.transceiver ? event.transceiver.mid : event.track.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(event.track.id));\n if (event.track.kind === 'video') {\n this.requestKeyFrame(handle.handleId, mid);\n }\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n mid,\n id: handle.handleId,\n userId: (_decodeJanusDisplay19 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay19 === void 0 ? void 0 : _decodeJanusDisplay19.userId,\n role: (_decodeJanusDisplay20 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay20 === void 0 ? void 0 : _decodeJanusDisplay20.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n source,\n track: event.track,\n constructId: this.constructId,\n adding: true,\n removing: false,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n if (event.track.onended) return;\n event.track.onended = ev => {\n var _config$stream3, _config$pc2, _config$pc2$getTransc, _decodeJanusDisplay21, _decodeJanusDisplay22;\n this._log('Remote track ended');\n (_config$stream3 = config.stream) === null || _config$stream3 === void 0 ? void 0 : _config$stream3.removeTrack(ev.target);\n // check if handle still exists\n if (!this._getHandle(handle.handleId)) {\n return;\n }\n this._updateRemoteParticipantStreamMap(handle.handleId);\n let transceiver = (_config$pc2 = config.pc) === null || _config$pc2 === void 0 ? void 0 : (_config$pc2$getTransc = _config$pc2.getTransceivers()) === null || _config$pc2$getTransc === void 0 ? void 0 : _config$pc2$getTransc.find(t => t.receiver.track === ev.target);\n let mid = (transceiver === null || transceiver === void 0 ? void 0 : transceiver.mid) || ev.target.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.target.id));\n this.emit(this._getAddParticipantEventName(handle.handleId), {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay21 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay21 === void 0 ? void 0 : _decodeJanusDisplay21.userId,\n role: (_decodeJanusDisplay22 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay22 === void 0 ? void 0 : _decodeJanusDisplay22.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n tracksMap: structuredClone(config.tracksMap),\n transceiverMap: structuredClone(config.transceiverMap),\n source,\n track: ev.target,\n adding: false,\n removing: true,\n hasAudioTrack: !!(config.stream && config.stream.getAudioTracks().length),\n hasVideoTrack: !!(config.stream && config.stream.getVideoTracks().length)\n });\n };\n let mutedTimerId = {};\n let waitPeriod = 300; // ms\n let screenShareWaitPeriod = 5000; // ms\n\n event.track.onmute = ev => {\n var _decodeJanusDisplay23, _decodeJanusDisplay24;\n this._log('Remote track muted');\n let transceiver = config.pc.getTransceivers().find(t => t.receiver.track === ev.target);\n let mid = transceiver.mid || ev.target.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.target.id));\n this.emit('remoteTrackMuted', {\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay23 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay23 === void 0 ? void 0 : _decodeJanusDisplay23.userId,\n role: (_decodeJanusDisplay24 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay24 === void 0 ? void 0 : _decodeJanusDisplay24.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n source,\n kind: ev.target.kind,\n track: ev.target,\n muted: true\n });\n\n // when a track is muted, we try to switch to lower quality substream, but not for screen sharing\n\n if (!this.simulcast) {\n return;\n }\n const wPeriod = source.indexOf('screen') > -1 ? screenShareWaitPeriod : waitPeriod;\n if (!mutedTimerId[mid]) {\n mutedTimerId[mid] = setTimeout(() => {\n var _handle$webrtcStuff5, _handle$webrtcStuff5$;\n mutedTimerId[mid] = null;\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n const simulcastMode = ((_handle$webrtcStuff5 = handle.webrtcStuff) === null || _handle$webrtcStuff5 === void 0 ? void 0 : (_handle$webrtcStuff5$ = _handle$webrtcStuff5.overriddenSimulcastMode[mid]) === null || _handle$webrtcStuff5$ === void 0 ? void 0 : _handle$webrtcStuff5$.mode) || (simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.mode);\n const {\n simulcastBitrates\n } = handle.webrtcStuff.tracksMap.find(t => t.mid === mid) || {};\n\n // track is gone\n if (!simulcastBitrates) {\n return;\n }\n const currentSubstream = handle.webrtcStuff.selectedSubstream[mid];\n if (!(simulcastMode === 'browserControlled') && ev.target.kind === 'video' && currentSubstream < simulcastBitrates.length - 1) {\n this._log('Attempting to down the quality due to track muted');\n this.selectSubStream(handle.handleId, currentSubstream + 1, undefined, mid, false).catch(reason => this._log(`Changing substream for mid: ${mid} failed. Reason: ${reason}`));\n }\n }, wPeriod);\n }\n };\n event.track.onunmute = ev => {\n var _decodeJanusDisplay25, _decodeJanusDisplay26;\n this._log('Remote track unmuted');\n let transceiver = config.pc.getTransceivers().find(t => t.receiver.track === ev.target);\n let mid = transceiver.mid || ev.target.id;\n let source = Object.keys(config.streamMap).find(key => config.streamMap[key].includes(ev.target.id));\n if (mutedTimerId[mid]) {\n clearTimeout(mutedTimerId[mid]);\n mutedTimerId[mid] = null;\n }\n this.emit('remoteTrackMuted', {\n id: handle.handleId,\n mid,\n constructId: this.constructId,\n userId: (_decodeJanusDisplay25 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay25 === void 0 ? void 0 : _decodeJanusDisplay25.userId,\n role: (_decodeJanusDisplay26 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay26 === void 0 ? void 0 : _decodeJanusDisplay26.role,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n source,\n kind: ev.target.kind,\n track: ev.target,\n muted: false\n });\n };\n }\n };\n }\n }\n if (!config.dataChannel || !config.dataChannelOpen) {\n config.dataChannel = {};\n var onDataChannelMessage = event => {\n this._handleDataEvents(handleId, 'message', event.data);\n };\n var onDataChannelStateChange = event => {\n let label = event.target.label;\n let protocol = event.target.protocol;\n let state = config.dataChannel[label] ? config.dataChannel[label].readyState : \"null\";\n this._handleDataEvents(handleId, 'state', {\n state,\n label\n });\n };\n var onDataChannelError = error => {\n var _error$channel;\n this._handleDataEvents(handleId, 'error', {\n label: error === null || error === void 0 ? void 0 : (_error$channel = error.channel) === null || _error$channel === void 0 ? void 0 : _error$channel.label,\n error\n });\n };\n const createDataChannel = (label, protocol, incoming) => {\n let options = {\n ordered: true\n };\n if (!incoming) {\n if (protocol) {\n options = {\n ...options,\n protocol\n };\n }\n config.dataChannel[label] = config.pc.createDataChannel(label, options);\n } else {\n config.dataChannel[label] = incoming;\n }\n config.dataChannel[label].onmessage = onDataChannelMessage;\n config.dataChannel[label].onopen = onDataChannelStateChange;\n config.dataChannel[label].onclose = onDataChannelStateChange;\n config.dataChannel[label].onerror = onDataChannelError;\n };\n createDataChannel(this.defaultDataChannelLabel, null, null);\n config.pc.ondatachannel = function (event) {\n createDataChannel(event.channel.label, event.channel.protocol, event.channel);\n };\n }\n }\n _webrtcPeer(handleId, jsep) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.reject({\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'rtc peer']\n });\n }\n var config = handle.webrtcStuff;\n if (jsep !== undefined && jsep !== null) {\n if (config.pc === null) {\n this._log(\"No PeerConnection: if this is an answer, use createAnswer and not _webrtcPeer\");\n return Promise.resolve(null);\n }\n return config.pc.setRemoteDescription(jsep).then(() => {\n config.remoteSdp = jsep.sdp;\n // Any trickle candidate we cached?\n if (config.candidates && config.candidates.length > 0) {\n for (var i = 0; i < config.candidates.length; i++) {\n var candidate = config.candidates[i];\n if (!candidate || candidate.completed === true) {\n config.pc.addIceCandidate(null);\n } else {\n config.pc.addIceCandidate(candidate);\n }\n }\n config.candidates = [];\n }\n // Done\n return true;\n }).catch(e => {\n return Promise.reject({\n type: 'warning',\n id: 32,\n message: 'rtc peer',\n data: [handleId, e]\n });\n });\n } else {\n return Promise.reject({\n type: 'warning',\n id: 22,\n message: 'rtc peer',\n data: [handleId, 'invalid jsep']\n });\n }\n }\n _iceRestart(handleId) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n return;\n }\n var config = handle.webrtcStuff;\n\n // Already restarting;\n if (config.isIceRestarting) {\n return;\n }\n config.isIceRestarting = true;\n if (this.handleId === handleId) {\n this._log('Performing local ICE restart');\n let hasAudio = !!(config.stream && config.stream.getAudioTracks().length > 0);\n let hasVideo = !!(config.stream && config.stream.getVideoTracks().length > 0);\n this._createAO('offer', handleId, true).then(jsep => {\n if (!jsep) {\n return null;\n }\n return this.sendMessage(handleId, {\n body: {\n \"request\": \"configure\",\n \"keyframe\": true,\n \"audio\": hasAudio,\n \"video\": hasVideo,\n \"data\": true,\n ...(this.recordingFilename ? {\n filename: this.recordingFilename\n } : {})\n },\n jsep\n }, false, false, 5);\n }).then(r => {\n config.isIceRestarting = false;\n this._log('ICE restart success');\n }).catch(e => {\n config.isIceRestarting = false;\n this.emit('error', {\n type: 'warning',\n id: 28,\n message: 'iceRestart failed',\n data: e\n });\n });\n } else {\n this._log('Performing remote ICE restart', handleId);\n return this.sendMessage(handleId, {\n body: {\n \"request\": \"configure\",\n \"restart\": true\n }\n }, false, false, 5).then(() => {}).then(() => {\n config.isIceRestarting = false;\n this._log('ICE restart success');\n }).catch(() => {\n config.isIceRestarting = false;\n });\n }\n }\n _setupTransceivers(handleId, _ref) {\n let [audioSend, audioRecv, videoSend, videoRecv, audioTransceiver = null, videoTransceiver = null] = _ref;\n //TODO: this should be refactored to use handle's trackMap so we dont have to pass any parameters\n\n let handle = this._getHandle(handleId);\n if (!handle) {\n return null;\n }\n let config = handle.webrtcStuff;\n const setTransceiver = function (transceiver, send, recv) {\n let kind = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'audio';\n if (!send && !recv) {\n // disabled: have we removed it?\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"inactive\");\n } else {\n transceiver.direction = \"inactive\";\n }\n }\n } else {\n if (send && recv) {\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"sendrecv\");\n } else {\n transceiver.direction = \"sendrecv\";\n }\n }\n } else if (send && !recv) {\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"sendonly\");\n } else {\n transceiver.direction = \"sendonly\";\n }\n }\n } else if (!send && recv) {\n if (transceiver) {\n if (transceiver.setDirection) {\n transceiver.setDirection(\"recvonly\");\n } else {\n transceiver.direction = \"recvonly\";\n }\n } else {\n // In theory, this is the only case where we might not have a transceiver yet\n config.pc.addTransceiver(kind, {\n direction: \"recvonly\"\n });\n }\n }\n }\n };\n\n // if we're passing any transceivers, we work only on them, doesn't matter if one of them is null\n if (audioTransceiver || videoTransceiver) {\n if (audioTransceiver) {\n setTransceiver(audioTransceiver, audioSend, audioRecv, 'audio');\n }\n if (videoTransceiver) {\n setTransceiver(videoTransceiver, videoSend, videoRecv, 'video');\n }\n }\n // else we work on all transceivers\n else {\n let transceivers = config.pc.getTransceivers();\n if (transceivers && transceivers.length > 0) {\n for (let i in transceivers) {\n let t = transceivers[i];\n if (t.sender && t.sender.track && t.sender.track.kind === \"audio\" || t.receiver && t.receiver.track && t.receiver.track.kind === \"audio\") {\n setTransceiver(t, audioSend, audioRecv, 'audio');\n }\n if (t.sender && t.sender.track && t.sender.track.kind === \"video\" || t.receiver && t.receiver.track && t.receiver.track.kind === \"video\") {\n setTransceiver(t, videoSend, videoRecv, 'video');\n }\n }\n }\n }\n }\n _createAO() {\n let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'offer';\n let handleId = arguments.length > 1 ? arguments[1] : undefined;\n let iceRestart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.reject({\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'createAO', type]\n });\n }\n let methodName = null;\n if (type === 'offer') {\n methodName = 'createOffer';\n } else {\n methodName = 'createAnswer';\n }\n let config = handle.webrtcStuff;\n let mediaConstraints = {};\n if (iceRestart) {\n mediaConstraints[\"iceRestart\"] = true;\n }\n return config.pc[methodName](mediaConstraints).then(response => {\n // if type offer and its me and we want dtx we mungle the sdp\n if (handleId === this.handleId && type === 'offer' && this.enableDtx) {\n // enable DTX\n response.sdp = response.sdp.replace(\"useinbandfec=1\", \"useinbandfec=1;usedtx=1\");\n }\n config.mySdp = response.sdp;\n let _p = config.pc.setLocalDescription(response).catch(e => {\n return Promise.reject({\n type: 'warning',\n id: 24,\n message: 'setLocalDescription',\n data: [handleId, e]\n });\n });\n config.mediaConstraints = mediaConstraints;\n if (!config.iceDone && !config.trickle) {\n // Don't do anything until we have all candidates\n return Promise.resolve(null);\n }\n\n // JSON.stringify doesn't work on some WebRTC objects anymore\n // See https://code.google.com/p/chromium/issues/detail?id=467366\n var jsep = {\n \"type\": response.type,\n \"sdp\": response.sdp\n };\n if (response.e2ee) jsep.e2ee = true;\n if (response.rid_order === \"hml\" || response.rid_order === \"lmh\") jsep.rid_order = response.rid_order;\n if (response.force_relay) jsep.force_relay = true;\n return _p.then(() => jsep);\n }, e => {\n return Promise.reject({\n type: 'warning',\n id: 25,\n message: methodName,\n data: [handleId, e]\n });\n });\n }\n _publishRemote(handleId, jsep) {\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.reject({\n type: 'warning',\n id: 15,\n message: 'id non-existent',\n data: [handleId, 'publish remote participant']\n });\n }\n this._webrtc(handleId, true);\n let config = handle.webrtcStuff;\n if (jsep) {\n return config.pc.setRemoteDescription(jsep).then(() => {\n config.remoteSdp = jsep.sdp;\n // Any trickle candidate we cached?\n if (config.candidates && config.candidates.length > 0) {\n for (var i = 0; i < config.candidates.length; i++) {\n var candidate = config.candidates[i];\n if (!candidate || candidate.completed === true) {\n // end-of-candidates\n config.pc.addIceCandidate(null);\n } else {\n // New candidate\n config.pc.addIceCandidate(candidate);\n }\n }\n config.candidates = [];\n }\n this._setupTransceivers(handleId, [false, true, false, true]);\n\n // Create the answer now\n return this._createAO('answer', handleId, false).then(_jsep => {\n if (!_jsep) {\n this.emit('error', {\n type: 'warning',\n id: 19,\n message: 'publish remote participant',\n data: [handleId, 'no jsep']\n });\n return Promise.resolve();\n }\n return this.sendMessage(handleId, {\n \"body\": {\n \"request\": \"start\",\n ...(this.roomId && {\n \"room\": this.roomId\n }),\n ...(this.pin && {\n pin: this.pin\n })\n },\n \"jsep\": _jsep\n });\n });\n }, e => Promise.reject({\n type: 'warning',\n id: 23,\n message: 'setRemoteDescription',\n data: [handleId, e]\n }));\n } else {\n return Promise.resolve();\n }\n }\n\n //Public methods\n _republishOnTrackEnded(source) {\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return;\n }\n let config = handle.webrtcStuff;\n if (!config.stream) {\n return;\n }\n let sourceTrackIds = config.streamMap[source] || [];\n let remainingTracks = [];\n for (let i = 0; i < sourceTrackIds.length; i++) {\n let foundTrack = config.stream.getTracks().find(t => t.id === sourceTrackIds[i]);\n if (foundTrack) {\n remainingTracks.push(foundTrack);\n }\n }\n if (remainingTracks.length) {\n let stream = new MediaStream();\n remainingTracks.forEach(track => stream.addTrack(track));\n return this.publishLocal(stream, source);\n } else {\n return this.publishLocal(null, source);\n }\n }\n publishLocal() {\n var _stream$getVideoTrack, _stream$getAudioTrack, _config$stream4, _config$stream4$getAu, _config$stream5, _config$stream5$getVi, _stream$getAudioTrack2, _stream$getVideoTrack2;\n let stream = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'camera0';\n if (this.isDisconnecting || !this.isConnected) {\n return Promise.reject({\n type: 'warning',\n id: 18,\n message: 'Either not connected or disconnecting'\n });\n }\n if ((stream === null || stream === void 0 ? void 0 : (_stream$getVideoTrack = stream.getVideoTracks()) === null || _stream$getVideoTrack === void 0 ? void 0 : _stream$getVideoTrack.length) > 1) {\n return Promise.reject({\n type: 'warning',\n id: 30,\n message: 'multiple video tracks not supported',\n data: null\n });\n }\n if ((stream === null || stream === void 0 ? void 0 : (_stream$getAudioTrack = stream.getAudioTracks()) === null || _stream$getAudioTrack === void 0 ? void 0 : _stream$getAudioTrack.length) > 1) {\n return Promise.reject({\n type: 'warning',\n id: 30,\n message: 'multiple audio tracks not supported',\n data: null\n });\n }\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return Promise.reject({\n type: 'error',\n id: 31,\n message: 'no local id, connect before publishing',\n data: null\n });\n }\n this.emit('publishing', true);\n this._webrtc(this.handleId);\n let config = handle.webrtcStuff;\n if (!config.stream) {\n config.stream = new MediaStream();\n }\n let needsNegotiation = !this.isPublished;\n let transceivers = config.pc.getTransceivers();\n let existingTracks = [...(config.streamMap[source] || [])];\n if (stream !== null && stream !== void 0 && stream.getTracks().length) {\n var _stream$getTracks;\n config.streamMap[source] = (stream === null || stream === void 0 ? void 0 : (_stream$getTracks = stream.getTracks()) === null || _stream$getTracks === void 0 ? void 0 : _stream$getTracks.map(track => track.id)) || [];\n } else {\n delete config.streamMap[source];\n }\n\n // remove old audio track related to this source\n let oldAudioStream = config === null || config === void 0 ? void 0 : (_config$stream4 = config.stream) === null || _config$stream4 === void 0 ? void 0 : (_config$stream4$getAu = _config$stream4.getAudioTracks()) === null || _config$stream4$getAu === void 0 ? void 0 : _config$stream4$getAu.find(track => existingTracks.includes(track.id));\n if (oldAudioStream) {\n try {\n oldAudioStream.stop();\n } catch (e) {\n this._log(e);\n }\n config.stream.removeTrack(oldAudioStream);\n }\n\n // remove old video track related to this source\n let oldVideoStream = config === null || config === void 0 ? void 0 : (_config$stream5 = config.stream) === null || _config$stream5 === void 0 ? void 0 : (_config$stream5$getVi = _config$stream5.getVideoTracks()) === null || _config$stream5$getVi === void 0 ? void 0 : _config$stream5$getVi.find(track => existingTracks.includes(track.id));\n if (oldVideoStream) {\n try {\n oldVideoStream.stop();\n } catch (e) {\n this._log(e);\n }\n config.stream.removeTrack(oldVideoStream);\n }\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n let audioTrackReplacePromise = Promise.resolve();\n let videoTrackReplacePromise = Promise.resolve();\n let audioTransceiver = null;\n let videoTransceiver = null;\n let replaceAudio = stream === null || stream === void 0 ? void 0 : (_stream$getAudioTrack2 = stream.getAudioTracks()) === null || _stream$getAudioTrack2 === void 0 ? void 0 : _stream$getAudioTrack2.length;\n let replaceVideo = stream === null || stream === void 0 ? void 0 : (_stream$getVideoTrack2 = stream.getVideoTracks()) === null || _stream$getVideoTrack2 === void 0 ? void 0 : _stream$getVideoTrack2.length;\n for (const transceiver of transceivers) {\n var _transceiver$sender, _transceiver$sender$t, _transceiver$sender2, _transceiver$sender2$, _transceiver$sender3, _transceiver$sender3$, _transceiver$sender4, _transceiver$sender4$, _transceiver$sender5, _transceiver$sender5$, _transceiver$sender5$2, _transceiver$sender6, _transceiver$sender6$, _transceiver$sender6$2;\n if (['sendonly', 'sendrecv'].includes(transceiver.currentDirection) && ((_transceiver$sender = transceiver.sender) === null || _transceiver$sender === void 0 ? void 0 : (_transceiver$sender$t = _transceiver$sender.track) === null || _transceiver$sender$t === void 0 ? void 0 : _transceiver$sender$t.kind) === 'audio' && existingTracks.includes((_transceiver$sender2 = transceiver.sender) === null || _transceiver$sender2 === void 0 ? void 0 : (_transceiver$sender2$ = _transceiver$sender2.track) === null || _transceiver$sender2$ === void 0 ? void 0 : _transceiver$sender2$.id)) {\n audioTransceiver = transceiver;\n } else if (['sendonly', 'sendrecv'].includes(transceiver.currentDirection) && ((_transceiver$sender3 = transceiver.sender) === null || _transceiver$sender3 === void 0 ? void 0 : (_transceiver$sender3$ = _transceiver$sender3.track) === null || _transceiver$sender3$ === void 0 ? void 0 : _transceiver$sender3$.kind) === 'video' && existingTracks.includes((_transceiver$sender4 = transceiver.sender) === null || _transceiver$sender4 === void 0 ? void 0 : (_transceiver$sender4$ = _transceiver$sender4.track) === null || _transceiver$sender4$ === void 0 ? void 0 : _transceiver$sender4$.id)) {\n videoTransceiver = transceiver;\n }\n\n // Reusing existing transceivers\n // TODO: if we start using different codecs for different sources, we need to check for that here\n else if (transceiver.currentDirection === 'inactive' && (_transceiver$sender5 = transceiver.sender) !== null && _transceiver$sender5 !== void 0 && (_transceiver$sender5$ = _transceiver$sender5.getParameters()) !== null && _transceiver$sender5$ !== void 0 && (_transceiver$sender5$2 = _transceiver$sender5$.codecs) !== null && _transceiver$sender5$2 !== void 0 && _transceiver$sender5$2.find(c => c.mimeType.indexOf('audio') > -1) && replaceAudio && !audioTransceiver) {\n audioTransceiver = transceiver;\n needsNegotiation = true;\n } else if (transceiver.currentDirection === 'inactive' && (_transceiver$sender6 = transceiver.sender) !== null && _transceiver$sender6 !== void 0 && (_transceiver$sender6$ = _transceiver$sender6.getParameters()) !== null && _transceiver$sender6$ !== void 0 && (_transceiver$sender6$2 = _transceiver$sender6$.codecs) !== null && _transceiver$sender6$2 !== void 0 && _transceiver$sender6$2.find(c => c.mimeType.indexOf('video') > -1) && replaceVideo && !videoTransceiver) {\n videoTransceiver = transceiver;\n needsNegotiation = true;\n }\n }\n if (replaceAudio) {\n config.stream.addTrack(stream.getAudioTracks()[0]);\n if (audioTransceiver && audioTransceiver.sender) {\n audioTrackReplacePromise = audioTransceiver.sender.replaceTrack(stream.getAudioTracks()[0]);\n } else {\n config.pc.addTrack(stream.getAudioTracks()[0], config.stream);\n needsNegotiation = true;\n }\n } else {\n if (audioTransceiver && audioTransceiver.sender) {\n audioTrackReplacePromise = audioTransceiver.sender.replaceTrack(null);\n needsNegotiation = true;\n }\n }\n if (replaceVideo) {\n config.stream.addTrack(stream.getVideoTracks()[0]);\n if (videoTransceiver && videoTransceiver.sender) {\n videoTrackReplacePromise = videoTransceiver.sender.replaceTrack(stream.getVideoTracks()[0]);\n } else {\n if (!this.simulcast) {\n config.pc.addTrack(stream.getVideoTracks()[0], config.stream);\n } else {\n if (webrtc_adapter__WEBPACK_IMPORTED_MODULE_0__[\"default\"].browserDetails.browser !== 'firefox') {\n // standard\n config.pc.addTransceiver(stream.getVideoTracks()[0], {\n direction: 'sendonly',\n streams: [config.stream],\n sendEncodings: structuredClone(simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates)\n });\n } else {\n // firefox\n let transceiver = config.pc.addTransceiver(stream.getVideoTracks()[0], {\n direction: 'sendonly',\n streams: [config.stream]\n });\n let sender = transceiver ? transceiver.sender : null;\n if (sender) {\n let parameters = sender.getParameters() || {};\n parameters.encodings = stream.getVideoTracks()[0].sendEncodings || structuredClone(simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates);\n sender.setParameters(parameters);\n }\n }\n }\n needsNegotiation = true;\n }\n } else {\n if (videoTransceiver && videoTransceiver.sender) {\n videoTrackReplacePromise = videoTransceiver.sender.replaceTrack(null);\n needsNegotiation = true;\n }\n }\n this.isAudioEnabed = !!(config.stream && config.stream.getAudioTracks().length > 0);\n this.isVideoEnabled = !!(config.stream && config.stream.getVideoTracks().length > 0);\n\n // we possibly created new transceivers, so we need to get them again\n transceivers = config.pc.getTransceivers();\n existingTracks = [...(config.streamMap[source] || [])];\n if (!audioTransceiver) {\n audioTransceiver = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'audio' && existingTracks.includes(transceiver.sender.track.id));\n }\n if (!videoTransceiver) {\n videoTransceiver = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'video' && existingTracks.includes(transceiver.sender.track.id));\n }\n let hasAudio = !!(stream && stream.getAudioTracks().length > 0);\n let hasVideo = !!(stream && stream.getVideoTracks().length > 0);\n this._setupTransceivers(this.handleId, [hasAudio, false, hasVideo, false, audioTransceiver, videoTransceiver]);\n const emitEvents = () => {\n var _decodeJanusDisplay27, _decodeJanusDisplay28;\n this.isPublished = true;\n if (!config.stream.onremovetrack) {\n config.stream.onremovetrack = ev => {};\n }\n let republishTimeoutId = null;\n let tracks = config.stream.getTracks();\n this.emit('addLocalParticipant', {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay27 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay27 === void 0 ? void 0 : _decodeJanusDisplay27.userId,\n role: (_decodeJanusDisplay28 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display)) === null || _decodeJanusDisplay28 === void 0 ? void 0 : _decodeJanusDisplay28.role,\n stream: tracks.length ? config.stream : null,\n // that null is there due to backward compatibility\n track: null,\n streamMap: structuredClone(config.streamMap),\n source,\n adding: false,\n removing: false,\n constructId: this.constructId,\n hasAudioTrack: hasAudio,\n hasVideoTrack: hasVideo\n });\n if (tracks.length) {\n tracks.forEach(track => {\n // used as a flag to not emit tracks that been already emitted\n if (!track.onended) {\n var _decodeJanusDisplay29, _decodeJanusDisplay30;\n this.emit('addLocalParticipant', {\n tid: Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"generateUUID\"])(),\n id: handle.handleId,\n userId: (_decodeJanusDisplay29 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay29 === void 0 ? void 0 : _decodeJanusDisplay29.userId,\n role: (_decodeJanusDisplay30 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(this.display)) === null || _decodeJanusDisplay30 === void 0 ? void 0 : _decodeJanusDisplay30.role,\n track,\n stream: config.stream,\n streamMap: structuredClone(config.streamMap),\n source,\n adding: true,\n removing: false,\n constructId: this.constructId,\n hasAudioTrack: hasAudio,\n hasVideoTrack: hasVideo\n });\n track.onended = ev => {\n config.stream.removeTrack(track);\n clearTimeout(republishTimeoutId);\n republishTimeoutId = setTimeout(() => {\n this._republishOnTrackEnded(source);\n }, 100);\n };\n }\n });\n }\n this.isMuted = [];\n for (const source of Object.keys(config.streamMap)) {\n var _config$stream6, _config$stream6$getAu, _config$stream7, _config$stream7$getVi, _transceivers$find2, _transceivers$find3;\n const audioTrack = (_config$stream6 = config.stream) === null || _config$stream6 === void 0 ? void 0 : (_config$stream6$getAu = _config$stream6.getAudioTracks()) === null || _config$stream6$getAu === void 0 ? void 0 : _config$stream6$getAu.find(track => config.streamMap[source].includes(track.id));\n const videoTrack = (_config$stream7 = config.stream) === null || _config$stream7 === void 0 ? void 0 : (_config$stream7$getVi = _config$stream7.getVideoTracks()) === null || _config$stream7$getVi === void 0 ? void 0 : _config$stream7$getVi.find(track => config.streamMap[source].includes(track.id));\n this.isMuted.push({\n type: 'audio',\n value: !audioTrack || !audioTrack.enabled,\n source,\n mid: (_transceivers$find2 = transceivers.find(transceiver => {\n var _transceiver$sender7, _transceiver$sender7$, _transceiver$sender8, _transceiver$sender8$;\n return ((_transceiver$sender7 = transceiver.sender) === null || _transceiver$sender7 === void 0 ? void 0 : (_transceiver$sender7$ = _transceiver$sender7.track) === null || _transceiver$sender7$ === void 0 ? void 0 : _transceiver$sender7$.kind) === 'audio' && ((_transceiver$sender8 = transceiver.sender) === null || _transceiver$sender8 === void 0 ? void 0 : (_transceiver$sender8$ = _transceiver$sender8.track) === null || _transceiver$sender8$ === void 0 ? void 0 : _transceiver$sender8$.id) === (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.id);\n })) === null || _transceivers$find2 === void 0 ? void 0 : _transceivers$find2.mid\n });\n this.isMuted.push({\n type: 'video',\n value: !videoTrack || !videoTrack.enabled,\n source,\n mid: (_transceivers$find3 = transceivers.find(transceiver => {\n var _transceiver$sender9, _transceiver$sender9$, _transceiver$sender10, _transceiver$sender11;\n return ((_transceiver$sender9 = transceiver.sender) === null || _transceiver$sender9 === void 0 ? void 0 : (_transceiver$sender9$ = _transceiver$sender9.track) === null || _transceiver$sender9$ === void 0 ? void 0 : _transceiver$sender9$.kind) === 'video' && ((_transceiver$sender10 = transceiver.sender) === null || _transceiver$sender10 === void 0 ? void 0 : (_transceiver$sender11 = _transceiver$sender10.track) === null || _transceiver$sender11 === void 0 ? void 0 : _transceiver$sender11.id) === (videoTrack === null || videoTrack === void 0 ? void 0 : videoTrack.id);\n })) === null || _transceivers$find3 === void 0 ? void 0 : _transceivers$find3.mid\n });\n this.emit('localHasVideo', !!videoTrack, source);\n this.emit('localHasAudio', !!audioTrack, source);\n }\n for (const val of this.isMuted) {\n this.emit('localMuted', {\n ...val\n });\n }\n this.emit('published', {\n status: true,\n hasStream: tracks.length > 0\n });\n this.emit('publishing', false);\n return this;\n };\n\n // this should be enough\n if (!needsNegotiation) {\n return Promise.all([audioTrackReplacePromise, videoTrackReplacePromise]).then(() => emitEvents());\n }\n this._log('Starting negotiation');\n return Promise.all([audioTrackReplacePromise, videoTrackReplacePromise]).then(() => this._createAO('offer', this.handleId, false)).then(jsep => {\n if (!jsep) {\n return null;\n }\n //HOTFIX: Temporary fix for Safari 13\n if (jsep.sdp && jsep.sdp.indexOf(\"\\r\\na=ice-ufrag\") === -1) {\n jsep.sdp = jsep.sdp.replace(\"\\na=ice-ufrag\", \"\\r\\na=ice-ufrag\");\n }\n let descriptions = [];\n Object.keys(config.streamMap).forEach(source => {\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n config.streamMap[source].forEach(trackId => {\n let t = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.id === trackId);\n if (t) {\n descriptions.push({\n mid: t.mid,\n description: JSON.stringify({\n source,\n simulcastBitrates: simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates,\n intercomGroups: this._talkIntercomChannels\n })\n });\n }\n });\n });\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"configure\",\n \"audio\": this.isAudioEnabed,\n \"video\": this.isVideoEnabled,\n \"data\": true,\n ...(this.recordingFilename ? {\n filename: this.recordingFilename\n } : {}),\n descriptions: descriptions\n },\n jsep\n });\n }).then(r => {\n if (this._isDataChannelOpen === true) {\n return Promise.resolve(r);\n } else {\n return new Promise((resolve, reject) => {\n let dataChannelTimeoutId = null;\n let _resolve = val => {\n if (val) {\n clearTimeout(dataChannelTimeoutId);\n this._abortController.signal.removeEventListener('abort', _rejectAbort);\n this.off('dataChannel', _resolve, this);\n resolve(this);\n }\n };\n let _rejectTimeout = () => {\n this.off('dataChannel', _resolve, this);\n this._abortController.signal.removeEventListener('abort', _rejectAbort);\n reject({\n type: 'error',\n id: 27,\n message: 'Data channel did not open',\n data: null\n });\n };\n let _rejectAbort = () => {\n this._abortController.signal.removeEventListener('abort', _rejectAbort);\n clearTimeout(dataChannelTimeoutId);\n this.off('dataChannel', _resolve, this);\n reject({\n type: 'warning',\n id: 17,\n message: 'Connection cancelled'\n });\n };\n dataChannelTimeoutId = setTimeout(_rejectTimeout, 10000);\n this._abortController.signal.addEventListener('abort', _rejectAbort);\n this.on('dataChannel', _resolve, this);\n });\n }\n }).then(() => emitEvents()).catch(e => {\n this.emit('publishing', false);\n return Promise.reject(e);\n });\n }\n unpublishLocal() {\n let dontWait = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n return this.isPublished ? this.sendMessage(this.handleId, {\n body: {\n \"request\": \"unpublish\"\n }\n }, dontWait).finally(r => {\n this.isPublished = false;\n this.emit('published', {\n status: false,\n hasStream: false\n });\n return r;\n }) : Promise.resolve();\n }\n getUserTalkIntercomChannels(userId) {\n let talkIntercomChannels = [];\n let handle = this._getHandle(null, null, userId);\n if (handle) {\n let config = handle.webrtcStuff;\n talkIntercomChannels = config.tracksMap.reduce((acc, val) => {\n if (val.description) {\n try {\n let description = JSON.parse(val.description);\n if (description.intercomGroups) {\n description.intercomGroups.forEach(group => {\n if (!acc.includes(group)) {\n acc.push(group);\n }\n });\n }\n } catch (e) {}\n }\n return acc;\n }, []);\n }\n return talkIntercomChannels;\n }\n toggleAudio() {\n var _config$pc3;\n let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'camera0';\n let mid = arguments.length > 2 ? arguments[2] : undefined;\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 21,\n message: 'no local id, connect first',\n data: null\n });\n return;\n }\n let config = handle.webrtcStuff;\n let transceivers = (_config$pc3 = config.pc) === null || _config$pc3 === void 0 ? void 0 : _config$pc3.getTransceivers();\n let transceiver = null;\n if (source) {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"audio\" && (config.streamMap[source] || []).includes(t.sender.track.id));\n } else {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"audio\" && (mid ? t.mid === mid : true));\n }\n if (transceiver) {\n transceiver.sender.track.enabled = value !== null ? !!value : !transceiver.sender.track.enabled;\n }\n this.isMuted = [];\n for (const source of Object.keys(config.streamMap)) {\n var _config$stream8, _config$stream8$getAu, _config$stream9, _config$stream9$getVi, _audioTransceiver$sen, _audioTransceiver$sen2, _videoTransceiver$sen, _videoTransceiver$sen2;\n const audioTrack = (_config$stream8 = config.stream) === null || _config$stream8 === void 0 ? void 0 : (_config$stream8$getAu = _config$stream8.getAudioTracks()) === null || _config$stream8$getAu === void 0 ? void 0 : _config$stream8$getAu.find(track => config.streamMap[source].includes(track.id));\n const audioTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'audio' && transceiver.sender.track.id === (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.id));\n const videoTrack = (_config$stream9 = config.stream) === null || _config$stream9 === void 0 ? void 0 : (_config$stream9$getVi = _config$stream9.getVideoTracks()) === null || _config$stream9$getVi === void 0 ? void 0 : _config$stream9$getVi.find(track => config.streamMap[source].includes(track.id));\n const videoTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'video' && transceiver.sender.track.id === (videoTrack === null || videoTrack === void 0 ? void 0 : videoTrack.id));\n this.isMuted.push({\n type: 'audio',\n value: !audioTrack || !audioTransceiver || !(audioTransceiver !== null && audioTransceiver !== void 0 && (_audioTransceiver$sen = audioTransceiver.sender) !== null && _audioTransceiver$sen !== void 0 && (_audioTransceiver$sen2 = _audioTransceiver$sen.track) !== null && _audioTransceiver$sen2 !== void 0 && _audioTransceiver$sen2.enabled),\n source,\n mid: audioTransceiver === null || audioTransceiver === void 0 ? void 0 : audioTransceiver.mid\n });\n this.isMuted.push({\n type: 'video',\n value: !videoTrack || !videoTransceiver || !(videoTransceiver !== null && videoTransceiver !== void 0 && (_videoTransceiver$sen = videoTransceiver.sender) !== null && _videoTransceiver$sen !== void 0 && (_videoTransceiver$sen2 = _videoTransceiver$sen.track) !== null && _videoTransceiver$sen2 !== void 0 && _videoTransceiver$sen2.enabled),\n source,\n mid: videoTransceiver === null || videoTransceiver === void 0 ? void 0 : videoTransceiver.mid\n });\n }\n for (let val of this.isMuted) {\n this.emit('localMuted', {\n ...val\n });\n }\n }\n toggleVideo() {\n var _config$pc4;\n let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'camera0';\n let mid = arguments.length > 2 ? arguments[2] : undefined;\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n this.emit('error', {\n type: 'warning',\n id: 21,\n message: 'no local id, connect first',\n data: null\n });\n return;\n }\n let config = handle.webrtcStuff;\n let transceivers = (_config$pc4 = config.pc) === null || _config$pc4 === void 0 ? void 0 : _config$pc4.getTransceivers();\n let transceiver = null;\n if (source) {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"video\" && (config.streamMap[source] || []).includes(t.sender.track.id));\n } else {\n transceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(t => t.sender && t.sender.track && t.receiver.track.kind === \"video\" && (mid ? t.mid === mid : true));\n }\n if (transceiver) {\n transceiver.sender.track.enabled = value !== null ? !!value : !transceiver.sender.track.enabled;\n }\n this.isMuted = [];\n for (const source of Object.keys(config.streamMap)) {\n var _config$stream10, _config$stream10$getA, _config$stream11, _config$stream11$getV, _audioTransceiver$sen3, _audioTransceiver$sen4, _videoTransceiver$sen3, _videoTransceiver$sen4;\n const audioTrack = (_config$stream10 = config.stream) === null || _config$stream10 === void 0 ? void 0 : (_config$stream10$getA = _config$stream10.getAudioTracks()) === null || _config$stream10$getA === void 0 ? void 0 : _config$stream10$getA.find(track => config.streamMap[source].includes(track.id));\n const audioTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'audio' && transceiver.sender.track.id === (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.id));\n const videoTrack = (_config$stream11 = config.stream) === null || _config$stream11 === void 0 ? void 0 : (_config$stream11$getV = _config$stream11.getVideoTracks()) === null || _config$stream11$getV === void 0 ? void 0 : _config$stream11$getV.find(track => config.streamMap[source].includes(track.id));\n const videoTransceiver = transceivers === null || transceivers === void 0 ? void 0 : transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.kind === 'video' && transceiver.sender.track.id === (videoTrack === null || videoTrack === void 0 ? void 0 : videoTrack.id));\n this.isMuted.push({\n type: 'audio',\n value: !audioTrack || !audioTransceiver || !(audioTransceiver !== null && audioTransceiver !== void 0 && (_audioTransceiver$sen3 = audioTransceiver.sender) !== null && _audioTransceiver$sen3 !== void 0 && (_audioTransceiver$sen4 = _audioTransceiver$sen3.track) !== null && _audioTransceiver$sen4 !== void 0 && _audioTransceiver$sen4.enabled),\n source,\n mid: audioTransceiver === null || audioTransceiver === void 0 ? void 0 : audioTransceiver.mid\n });\n this.isMuted.push({\n type: 'video',\n value: !videoTrack || !videoTransceiver || !(videoTransceiver !== null && videoTransceiver !== void 0 && (_videoTransceiver$sen3 = videoTransceiver.sender) !== null && _videoTransceiver$sen3 !== void 0 && (_videoTransceiver$sen4 = _videoTransceiver$sen3.track) !== null && _videoTransceiver$sen4 !== void 0 && _videoTransceiver$sen4.enabled),\n source,\n mid: videoTransceiver === null || videoTransceiver === void 0 ? void 0 : videoTransceiver.mid\n });\n }\n for (let val of this.isMuted) {\n this.emit('localMuted', {\n ...val\n });\n }\n }\n requestKeyFrame(handleId, mid) {\n this.sendMessage(handleId, {\n \"body\": {\n \"request\": \"configure\",\n \"keyframe\": true,\n ...(mid !== undefined ? {\n streams: [{\n mid,\n keyframe: true\n }]\n } : {})\n }\n }).catch(() => null);\n }\n _setSelectedSubstream(handleId, mid, substream) {\n let handle = this._getHandle(handleId);\n if (handle) {\n let config = handle.webrtcStuff;\n if (!mid) {\n Object.keys(config.selectedSubstream).forEach(mid => {\n config.selectedSubstream[mid] = substream;\n });\n } else {\n config.selectedSubstream[mid] = substream;\n }\n }\n }\n overrideSimulcastSettings(handleId, mid, source) {\n let settings = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n const {\n mode,\n defaultSubstream\n } = settings;\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let config = handle.webrtcStuff;\n if (source !== undefined || mid !== undefined) {\n if (mid === undefined) {\n let transceivers = config.pc.getTransceivers();\n for (let trackId of config.streamMap[source]) {\n let transceiver = transceivers.find(transceiver => transceiver.receiver.track && transceiver.receiver.track.kind === 'video' && transceiver.receiver.track.id === trackId);\n if (transceiver) {\n mid = transceiver.mid;\n break;\n }\n }\n }\n if (mid !== undefined) {\n if (!config.overriddenSimulcastMode[mid]) {\n config.overriddenSimulcastMode[mid] = {};\n }\n config.overriddenSimulcastMode[mid]['defaultSubstream'] = defaultSubstream;\n config.overriddenSimulcastMode[mid]['mode'] = mode;\n return true;\n } else {\n return false;\n }\n }\n }\n selectSubStream(handleId) {\n let substream = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;\n let source = arguments.length > 2 ? arguments[2] : undefined;\n let mid = arguments.length > 3 ? arguments[3] : undefined;\n let manual = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;\n this._log('Select substream called for handle:', handleId, 'Source or mid:', source ? source : mid, 'Substream:', substream);\n let handle = this._getHandle(handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let config = handle.webrtcStuff;\n return new Promise((resolve, reject) => {\n let messageTimeoutId;\n let abortResponse = () => {\n clearTimeout(messageTimeoutId);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n reject('aborted');\n };\n let parseResponse = event => {\n let json = JSON.parse(event.data);\n var sender = json[\"sender\"];\n if (sender === handleId) {\n let plugindata = json[\"plugindata\"] || {};\n let msg = plugindata[\"data\"] || {};\n let substream = msg[\"substream\"];\n if (substream !== undefined && substream !== null && (mid !== undefined ? msg[\"mid\"] === mid : true)) {\n clearTimeout(messageTimeoutId);\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n resolve({\n substream,\n sender\n });\n }\n }\n };\n if (source !== undefined || mid !== undefined) {\n if (mid === undefined) {\n let transceivers = config.pc.getTransceivers();\n for (let trackId of config.streamMap[source]) {\n let transceiver = transceivers.find(transceiver => transceiver.receiver.track && transceiver.receiver.track.kind === 'video' && transceiver.receiver.track.id === trackId);\n if (transceiver) {\n mid = transceiver.mid;\n break;\n }\n }\n }\n if (mid !== undefined) {\n if (!config.overriddenSimulcastMode[mid]) {\n config.overriddenSimulcastMode[mid] = {};\n }\n if (substream === null) {\n if (manual) {\n // reset to previous state\n config.overriddenSimulcastMode[mid]['defaultSubstream'] = null;\n config.overriddenSimulcastMode[mid]['mode'] = null;\n }\n resolve({\n substream,\n sender: handleId\n });\n return;\n }\n if (manual) {\n config.overriddenSimulcastMode[mid]['defaultSubstream'] = substream;\n config.overriddenSimulcastMode[mid]['mode'] = \"manual\";\n }\n this.ws.addEventListener('message', parseResponse);\n this._abortController.signal.addEventListener('abort', abortResponse);\n messageTimeoutId = setTimeout(() => {\n this._abortController.signal.removeEventListener('abort', abortResponse);\n this.ws.removeEventListener('message', parseResponse);\n reject('timeout');\n }, 10000);\n this.sendMessage(handleId, {\n \"body\": {\n \"request\": \"configure\",\n \"streams\": [{\n mid,\n substream: parseInt(substream)\n }]\n }\n });\n } else {\n reject('no mid found');\n }\n } else {\n reject('no source or mid');\n }\n });\n }\n setTalkIntercomChannels() {\n let groups = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['participants'];\n if (typeof groups !== 'object' || !(\"length\" in groups)) {\n this._log('setTalkIntercomChannels: groups must be an array');\n groups = [groups];\n }\n this._talkIntercomChannels = structuredClone(groups);\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let config = handle.webrtcStuff;\n let transceivers = config.pc.getTransceivers();\n let descriptions = [];\n Object.keys(config.streamMap).forEach(source => {\n const simulcastConfigForSource = this._findSimulcastConfig(source, this.simulcastSettings);\n config.streamMap[source].forEach(trackId => {\n let t = transceivers.find(transceiver => transceiver.sender.track && transceiver.sender.track.id === trackId);\n if (t) {\n descriptions.push({\n mid: t.mid,\n description: JSON.stringify({\n simulcastBitrates: simulcastConfigForSource === null || simulcastConfigForSource === void 0 ? void 0 : simulcastConfigForSource.bitrates,\n intercomGroups: groups,\n source: source\n })\n });\n }\n });\n });\n return this.sendMessage(this.handleId, {\n body: {\n \"request\": \"configure\",\n descriptions: descriptions\n }\n });\n }\n setListenIntercomChannels() {\n let groups = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['participants'];\n if (typeof groups !== 'object' || !(\"length\" in groups)) {\n this._log('setListenIntercomChannels: groups must be an array');\n groups = [groups];\n }\n this._listenIntercomChannels = structuredClone(groups);\n let handle = this._getHandle(this.handleId);\n if (!handle) {\n return Promise.resolve();\n }\n let promises = [];\n this._participants.forEach(participant => {\n if (participant.handleId === this.handleId) {\n return;\n }\n let handle = this._getHandle(participant.handleId);\n if (handle) {\n const tracksMap = handle.webrtcStuff.tracksMap.filter(t => t.active);\n const subscribe = [];\n const unsubscribe = [];\n tracksMap.forEach(track => {\n if (track.type === 'data') {\n return;\n }\n const description = JSON.parse(track.description);\n const intercomGroups = (description === null || description === void 0 ? void 0 : description.intercomGroups) || [];\n if (this._listenIntercomChannels.some(g => intercomGroups.includes(g))) {\n if (!this._isAlreadySubscribed(participant.handleId, track.id, track.mid)) {\n subscribe.push({\n feed: track.id,\n mid: track.mid\n });\n }\n } else {\n unsubscribe.push({\n feed: track.id,\n mid: track.mid\n });\n }\n });\n this._updateSubscribeMap(participant.handleId, subscribe, unsubscribe);\n if (subscribe.length || unsubscribe.length) {\n promises.push(this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"update\",\n ...(subscribe.length ? {\n subscribe\n } : {}),\n ...(unsubscribe.length ? {\n unsubscribe\n } : {})\n }\n }));\n }\n }\n });\n return Promise.all(promises);\n }\n setRoomType() {\n let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'watchparty';\n this._roomType = type;\n return this._roomType;\n }\n setRestrictSubscribeToUserIds() {\n let userIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n this._restrictSubscribeToUserIds = structuredClone(userIds);\n if (!this.isConnected) {\n return Promise.resolve(this._restrictSubscribeToUserIds);\n }\n // sanity check by getting listparticipants and comparing it to _remoteUsersCache\n this.sendMessage(this.handleId, {\n body: {\n request: 'listparticipants',\n room: this.roomId\n }\n }).then(r => {\n let participants = r.participants;\n let remoteUsersCache = this._remoteUsersCache;\n let handle = this._getHandle(this.handleId);\n // filter out my user id from response and compare it to remoteUsersCache\n participants = participants.filter(p => {\n var _decodeJanusDisplay31, _decodeJanusDisplay32;\n return ((_decodeJanusDisplay31 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(p.id)) === null || _decodeJanusDisplay31 === void 0 ? void 0 : _decodeJanusDisplay31.userId) !== ((_decodeJanusDisplay32 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(handle.userId)) === null || _decodeJanusDisplay32 === void 0 ? void 0 : _decodeJanusDisplay32.userId);\n });\n\n // get rid of participants that are in participants but not in remoteUsersCache\n remoteUsersCache = remoteUsersCache.filter(r => participants.find(p => p.id === r.id));\n remoteUsersCache.forEach(r => {\n var _decodeJanusDisplay33;\n const handle = this._getHandle(null, null, (_decodeJanusDisplay33 = Object(_wt_utils__WEBPACK_IMPORTED_MODULE_2__[\"decodeJanusDisplay\"])(r.userId)) === null || _decodeJanusDisplay33 === void 0 ? void 0 : _decodeJanusDisplay33.userId);\n if (this._participantShouldSubscribe(r.userId)) {\n var _handle$webrtcStuff6;\n // todo: do a nicer flag to indicate inactive handle than just checking for pc\n if (!handle || !((_handle$webrtcStuff6 = handle.webrtcStuff) !== null && _handle$webrtcStuff6 !== void 0 && _handle$webrtcStuff6.pc)) {\n this._log('Subscribing to ', r.userId);\n this._createParticipant(r.userId, r.id).then(handle => {\n this._updateParticipantsTrackData(handle.handleId, r.streams);\n const subscribe = r.streams.filter(s => !s.disabled && this._intercomSubscribe(s)).map(stream => ({\n feed: stream.id,\n mid: stream.mid\n }));\n handle.webrtcStuff.subscribeMap = structuredClone(subscribe);\n return this.sendMessage(handle.handleId, {\n body: {\n \"request\": \"join\",\n \"room\": this.roomId,\n \"ptype\": \"subscriber\",\n \"private_id\": this.privateId,\n streams: subscribe,\n //\"feed\": id,\n ...(this.webrtcVersion > 1000 ? {\n id: this.userId\n } : {}),\n pin: this.pin\n }\n });\n }).catch(err => {\n this.emit('error', err);\n });\n } else {\n this._log('Already subscribed to ', r.userId);\n }\n } else if (handle) {\n this._log('Unsubscribing from ', r.userId);\n this._removeParticipant(handle.handleId);\n }\n });\n });\n }\n}\n_defineProperty(RoomSession, \"sessionTypes\", {\n 'reactooroom': 'janus.plugin.reactooroom',\n 'streaming': 'janus.plugin.streaming'\n});\n_defineProperty(RoomSession, \"userRoleSubscriptionRules\", {\n participant: {\n \"watchparty\": ['participant', 'talkback'],\n \"studio\": ['participant', 'talkback', 'host', 'observer'],\n \"commentary\": ['participant', 'talkback', 'host'],\n \"intercom\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3'],\n \"videowall\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3'],\n \"videowall-queue\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3'],\n \"videowall-queue-video\": ['host', 'talkback', 'observer', 'observerSolo1', 'observerSolo2', 'observerSolo3']\n },\n monitor: {\n \"watchparty\": ['participant', 'host'],\n \"studio\": ['participant', 'host', 'observer'],\n \"commentary\": ['participant', 'host'],\n \"intercom\": ['host', 'participant'],\n \"videowall\": ['host', 'participant'],\n \"videowall-queue\": ['host', 'participant'],\n \"videowall-queue-video\": ['host', 'participant']\n },\n talkback: {\n \"watchparty\": ['participant', 'host', 'talkback'],\n \"studio\": ['participant', 'host', 'observer', 'talkback'],\n \"commentary\": ['host', 'participant', 'talkback'],\n \"intercom\": ['host', 'participant', 'talkback'],\n \"videowall\": ['host', 'participant', 'talkback'],\n \"videowall-queue\": ['host', 'participant', 'talkback'],\n \"videowall-queue-video\": ['host', 'participant', 'talkback']\n },\n observer: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n observerSolo1: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n observerSolo2: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n observerSolo3: {\n \"watchparty\": ['participant'],\n \"studio\": ['participant'],\n \"commentary\": ['participant'],\n \"intercom\": ['participant'],\n \"videowall\": ['participant'],\n \"videowall-queue\": ['participant'],\n \"videowall-queue-video\": ['participant']\n },\n host: {\n \"watchparty\": [],\n \"studio\": [],\n \"commentary\": [],\n \"intercom\": [],\n \"videowall\": [],\n \"videowall-queue\": [],\n \"videowall-queue-video\": []\n },\n companionTV: {},\n companionPhone: {}\n});\n/* harmony default export */ __webpack_exports__[\"default\"] = (Room);\n\n//# sourceURL=webpack://WatchTogetherSDK/./src/modules/wt-room.js?");
|
|
10514
10514
|
|
|
10515
10515
|
/***/ }),
|
|
10516
10516
|
|