@signalwire/js 3.29.1 → 3.29.2

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.
Files changed (34) hide show
  1. package/dist/core/src/BaseSession.d.ts.map +1 -1
  2. package/dist/core/src/types/fabricRoomSession.d.ts +22 -1
  3. package/dist/core/src/types/fabricRoomSession.d.ts.map +1 -1
  4. package/dist/core/src/utils/interfaces.d.ts +1 -1
  5. package/dist/core/src/utils/interfaces.d.ts.map +1 -1
  6. package/dist/index.esm.js +26 -6
  7. package/dist/index.esm.js.map +2 -2
  8. package/dist/index.js +28 -6
  9. package/dist/index.js.map +2 -2
  10. package/dist/index.umd.js +4 -4
  11. package/dist/index.umd.js.map +1 -1
  12. package/dist/js/src/buildVideoElement.d.ts.map +1 -1
  13. package/dist/js/src/fabric/FabricRoomSession.d.ts +1 -0
  14. package/dist/js/src/fabric/FabricRoomSession.d.ts.map +1 -1
  15. package/dist/js/src/fabric/utils/eventMappers.d.ts +4 -4
  16. package/dist/js/src/fabric/utils/validationProxy.d.ts.map +1 -1
  17. package/dist/js/src/fabric/utils/validators.d.ts +1 -0
  18. package/dist/js/src/fabric/utils/validators.d.ts.map +1 -1
  19. package/dist/js/tsconfig.build.tsbuildinfo +1 -1
  20. package/dist/webrtc/src/BaseConnection.d.ts.map +1 -1
  21. package/dist/webrtc/src/RTCPeer.d.ts +10 -0
  22. package/dist/webrtc/src/RTCPeer.d.ts.map +1 -1
  23. package/dist/webrtc/src/RTCPeerConnectionManager.d.ts.map +1 -1
  24. package/dist/webrtc/src/connectionPoolManager.d.ts.map +1 -1
  25. package/dist/webrtc/src/utils/index.d.ts +1 -0
  26. package/dist/webrtc/src/utils/index.d.ts.map +1 -1
  27. package/dist/webrtc/src/utils/sdpHelpers.d.ts.map +1 -1
  28. package/dist/webrtc/src/workers/roomSubscribedWorker.d.ts.map +1 -1
  29. package/package.json +3 -3
  30. package/src/buildVideoElement.ts +7 -1
  31. package/src/fabric/FabricRoomSession.ts +7 -0
  32. package/src/fabric/utils/validationProxy.ts +2 -0
  33. package/src/fabric/utils/validators.ts +7 -0
  34. package/src/utils/videoElement.ts +3 -3
package/dist/index.umd.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /*!
2
- * SignalWire JS SDK v3.29.1 (https://signalwire.com)
3
- * Copyright 2018-2025 SignalWire
2
+ * SignalWire JS SDK v3.29.2 (https://signalwire.com)
3
+ * Copyright 2018-2026 SignalWire
4
4
  * Licensed under MIT(https://github.com/signalwire/signalwire-js/blob/main/LICENSE)
5
5
  */
6
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SignalWire={})}(this,(function(e){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r={exports:{}};!function(e){var r,i;r=t,i=function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],o={},n=null;function s(e,t){var r=e[t];if("function"==typeof r.bind)return r.bind(e);try{return Function.prototype.bind.call(r,e)}catch(t){return function(){return Function.prototype.apply.apply(r,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var r=this.getLevel(),o=0;o<i.length;o++){var n=i[o];this[n]=o<r?e:this.methodFactory(n,r,this.name)}if(this.log=this.debug,typeof console===t&&r<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(i,o,n){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&r?a:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,r){var s,a,d,u=this,h="loglevel";function m(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var r=window.document.cookie,i=encodeURIComponent(h),o=r.indexOf(i+"=");-1!==o&&(e=/^([^;]+)/.exec(r.slice(o+i.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function p(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=r||l,u.getLevel=function(){return null!=d?d:null!=a?a:s},u.setLevel=function(e,r){return d=p(e),!1!==r&&function(e){var r=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=r)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+r+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=p(e),m()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(n!==u&&(s=p(n.getLevel())),c.call(u),n===u)for(var e in o)o[e].rebuild()},s=p(n?n.getLevel():"WARN");var g=m();null!=g&&(d=p(g)),c.call(u)}(n=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=o[e];return t||(t=o[e]=new u(e,n.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return n.noConflict=function(){return typeof window!==t&&window.log===n&&(window.log=h),n},n.getLoggers=function(){return o},n.default=n,n},e.exports?e.exports=i():r.log=i()}(r);var i=r.exports;let o;const n=new Uint8Array(16);function s(){if(!o&&(o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(n)}var a=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const c=[];for(let e=0;e<256;++e)c.push((e+256).toString(16).slice(1));function d(e,t=0){return c[e[t+0]]+c[e[t+1]]+c[e[t+2]]+c[e[t+3]]+"-"+c[e[t+4]]+c[e[t+5]]+"-"+c[e[t+6]]+c[e[t+7]]+"-"+c[e[t+8]]+c[e[t+9]]+"-"+c[e[t+10]]+c[e[t+11]]+c[e[t+12]]+c[e[t+13]]+c[e[t+14]]+c[e[t+15]]}function l(e,t,r){function i(e,i,o,n){var s;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}(e)),"string"==typeof i&&(i=function(e){if(!function(e){return"string"==typeof e&&a.test(e)}(e))throw TypeError("Invalid UUID");let t;const r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(i)),16!==(null===(s=i)||void 0===s?void 0:s.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+e.length);if(c.set(i),c.set(e,i.length),c=r(c),c[6]=15&c[6]|t,c[8]=63&c[8]|128,o){n=n||0;for(let e=0;e<16;++e)o[n+e]=c[e];return o}return d(c)}try{i.name=e}catch(e){}return i.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",i.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",i}function u(e){return 14+(e+64>>>9<<4)+1}function h(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function m(e,t,r,i,o,n){return h((s=h(h(t,e),h(i,n)))<<(a=o)|s>>>32-a,r);var s,a}function p(e,t,r,i,o,n,s){return m(t&r|~t&i,e,t,o,n,s)}function g(e,t,r,i,o,n,s){return m(t&i|r&~i,e,t,o,n,s)}function f(e,t,r,i,o,n,s){return m(t^r^i,e,t,o,n,s)}function v(e,t,r,i,o,n,s){return m(r^(t|~i),e,t,o,n,s)}l("v3",48,(function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r)}return function(e){const t=[],r=32*e.length,i="0123456789abcdef";for(let o=0;o<r;o+=8){const r=e[o>>5]>>>o%32&255,n=parseInt(i.charAt(r>>>4&15)+i.charAt(15&r),16);t.push(n)}return t}(function(e,t){e[t>>5]|=128<<t%32,e[u(t)-1]=t;let r=1732584193,i=-271733879,o=-1732584194,n=271733878;for(let t=0;t<e.length;t+=16){const s=r,a=i,c=o,d=n;r=p(r,i,o,n,e[t],7,-680876936),n=p(n,r,i,o,e[t+1],12,-389564586),o=p(o,n,r,i,e[t+2],17,606105819),i=p(i,o,n,r,e[t+3],22,-1044525330),r=p(r,i,o,n,e[t+4],7,-176418897),n=p(n,r,i,o,e[t+5],12,1200080426),o=p(o,n,r,i,e[t+6],17,-1473231341),i=p(i,o,n,r,e[t+7],22,-45705983),r=p(r,i,o,n,e[t+8],7,1770035416),n=p(n,r,i,o,e[t+9],12,-1958414417),o=p(o,n,r,i,e[t+10],17,-42063),i=p(i,o,n,r,e[t+11],22,-1990404162),r=p(r,i,o,n,e[t+12],7,1804603682),n=p(n,r,i,o,e[t+13],12,-40341101),o=p(o,n,r,i,e[t+14],17,-1502002290),i=p(i,o,n,r,e[t+15],22,1236535329),r=g(r,i,o,n,e[t+1],5,-165796510),n=g(n,r,i,o,e[t+6],9,-1069501632),o=g(o,n,r,i,e[t+11],14,643717713),i=g(i,o,n,r,e[t],20,-373897302),r=g(r,i,o,n,e[t+5],5,-701558691),n=g(n,r,i,o,e[t+10],9,38016083),o=g(o,n,r,i,e[t+15],14,-660478335),i=g(i,o,n,r,e[t+4],20,-405537848),r=g(r,i,o,n,e[t+9],5,568446438),n=g(n,r,i,o,e[t+14],9,-1019803690),o=g(o,n,r,i,e[t+3],14,-187363961),i=g(i,o,n,r,e[t+8],20,1163531501),r=g(r,i,o,n,e[t+13],5,-1444681467),n=g(n,r,i,o,e[t+2],9,-51403784),o=g(o,n,r,i,e[t+7],14,1735328473),i=g(i,o,n,r,e[t+12],20,-1926607734),r=f(r,i,o,n,e[t+5],4,-378558),n=f(n,r,i,o,e[t+8],11,-2022574463),o=f(o,n,r,i,e[t+11],16,1839030562),i=f(i,o,n,r,e[t+14],23,-35309556),r=f(r,i,o,n,e[t+1],4,-1530992060),n=f(n,r,i,o,e[t+4],11,1272893353),o=f(o,n,r,i,e[t+7],16,-155497632),i=f(i,o,n,r,e[t+10],23,-1094730640),r=f(r,i,o,n,e[t+13],4,681279174),n=f(n,r,i,o,e[t],11,-358537222),o=f(o,n,r,i,e[t+3],16,-722521979),i=f(i,o,n,r,e[t+6],23,76029189),r=f(r,i,o,n,e[t+9],4,-640364487),n=f(n,r,i,o,e[t+12],11,-421815835),o=f(o,n,r,i,e[t+15],16,530742520),i=f(i,o,n,r,e[t+2],23,-995338651),r=v(r,i,o,n,e[t],6,-198630844),n=v(n,r,i,o,e[t+7],10,1126891415),o=v(o,n,r,i,e[t+14],15,-1416354905),i=v(i,o,n,r,e[t+5],21,-57434055),r=v(r,i,o,n,e[t+12],6,1700485571),n=v(n,r,i,o,e[t+3],10,-1894986606),o=v(o,n,r,i,e[t+10],15,-1051523),i=v(i,o,n,r,e[t+1],21,-2054922799),r=v(r,i,o,n,e[t+8],6,1873313359),n=v(n,r,i,o,e[t+15],10,-30611744),o=v(o,n,r,i,e[t+6],15,-1560198380),i=v(i,o,n,r,e[t+13],21,1309151649),r=v(r,i,o,n,e[t+4],6,-145523070),n=v(n,r,i,o,e[t+11],10,-1120210379),o=v(o,n,r,i,e[t+2],15,718787259),i=v(i,o,n,r,e[t+9],21,-343485551),r=h(r,s),i=h(i,a),o=h(o,c),n=h(n,d)}return[r,i,o,n]}(function(e){if(0===e.length)return[];const t=8*e.length,r=new Uint32Array(u(t));for(let i=0;i<t;i+=8)r[i>>5]|=(255&e[i/8])<<i%32;return r}(e),8*e.length))}));var y={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function b(e,t,r){if(y.randomUUID&&!t&&!e)return y.randomUUID();const i=(e=e||{}).random||(e.rng||s)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return d(i)}function _(e,t,r,i){switch(e){case 0:return t&r^~t&i;case 1:case 3:return t^r^i;case 2:return t&r^t&i^r&i}}function w(e,t){return e<<t|e>>>32-t}function k(e){return k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(e)}function S(e,t,r){return(t=function(e){var t=function(e){if("object"!=k(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=k(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==k(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function C(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function I(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?C(Object(r),!0).forEach((function(t){S(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):C(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function T(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}l("v5",80,(function(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);const i=Math.ceil((e.length/4+2)/16),o=new Array(i);for(let t=0;t<i;++t){const r=new Uint32Array(16);for(let i=0;i<16;++i)r[i]=e[64*t+4*i]<<24|e[64*t+4*i+1]<<16|e[64*t+4*i+2]<<8|e[64*t+4*i+3];o[t]=r}o[i-1][14]=8*(e.length-1)/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<i;++e){const i=new Uint32Array(80);for(let t=0;t<16;++t)i[t]=o[e][t];for(let e=16;e<80;++e)i[e]=w(i[e-3]^i[e-8]^i[e-14]^i[e-16],1);let n=r[0],s=r[1],a=r[2],c=r[3],d=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),o=w(n,5)+_(r,s,a,c)+d+t[r]+i[e]>>>0;d=c,c=a,a=w(s,30)>>>0,s=n,n=o}r[0]=r[0]+n>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+a>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+d>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]}));var E="function"==typeof Symbol&&Symbol.observable||"@@observable",P=function(){return Math.random().toString(36).substring(7).split("").join(".")},M={INIT:"@@redux/INIT"+P(),REPLACE:"@@redux/REPLACE"+P(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+P()}};function R(e,t,r){var i;if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error(T(0));if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(T(1));return r(R)(e,t)}if("function"!=typeof e)throw new Error(T(2));var o=e,n=t,s=[],a=s,c=!1;function d(){a===s&&(a=s.slice())}function l(){if(c)throw new Error(T(3));return n}function u(e){if("function"!=typeof e)throw new Error(T(4));if(c)throw new Error(T(5));var t=!0;return d(),a.push(e),function(){if(t){if(c)throw new Error(T(6));t=!1,d();var r=a.indexOf(e);a.splice(r,1),s=null}}}function h(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(T(7));if(void 0===e.type)throw new Error(T(8));if(c)throw new Error(T(9));try{c=!0,n=o(n,e)}finally{c=!1}for(var t=s=a,r=0;r<t.length;r++)(0,t[r])();return e}return h({type:M.INIT}),(i={dispatch:h,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(T(10));o=e,h({type:M.REPLACE})}})[E]=function(){var e,t=u;return(e={subscribe:function(e){if("object"!=typeof e||null===e)throw new Error(T(11));function r(){e.next&&e.next(l())}return r(),{unsubscribe:t(r)}}})[E]=function(){return this},e},i}function A(e){for(var t=Object.keys(e),r={},i=0;i<t.length;i++){var o=t[i];"function"==typeof e[o]&&(r[o]=e[o])}var n,s=Object.keys(r);try{!function(e){Object.keys(e).forEach((function(t){var r=e[t];if(void 0===r(void 0,{type:M.INIT}))throw new Error(T(12));if(void 0===r(void 0,{type:M.PROBE_UNKNOWN_ACTION()}))throw new Error(T(13))}))}(r)}catch(e){n=e}return function(e,t){if(void 0===e&&(e={}),n)throw n;for(var i=!1,o={},a=0;a<s.length;a++){var c=s[a],d=e[c],l=(0,r[c])(d,t);if(void 0===l)throw new Error(T(14));o[c]=l,i=i||l!==d}return(i=i||s.length!==Object.keys(e).length)?o:e}}function x(e,t){return function(){return t(e.apply(this,arguments))}}function O(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return 0===t.length?function(e){return e}:1===t.length?t[0]:t.reduce((function(e,t){return function(){return e(t.apply(void 0,arguments))}}))}function j(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e){return function(){var r=e.apply(void 0,arguments),i=function(){throw new Error(T(15))},o={getState:r.getState,dispatch:function(){return i.apply(void 0,arguments)}},n=t.map((function(e){return e(o)}));return i=O.apply(void 0,n)(r.dispatch),I(I({},r),{},{dispatch:i})}}}var L=/*#__PURE__*/Object.freeze({__proto__:null,__DO_NOT_USE__ActionTypes:M,applyMiddleware:j,bindActionCreators:function(e,t){if("function"==typeof e)return x(e,t);if("object"!=typeof e||null===e)throw new Error(T(16));var r={};for(var i in e){var o=e[i];"function"==typeof o&&(r[i]=x(o,t))}return r},combineReducers:A,compose:O,createStore:R,legacy_createStore:R}),D=function(e){return"@@redux-saga/"+e},W=
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SignalWire={})}(this,(function(e){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r={exports:{}};!function(e){var r,i;r=t,i=function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],o={},n=null;function s(e,t){var r=e[t];if("function"==typeof r.bind)return r.bind(e);try{return Function.prototype.bind.call(r,e)}catch(t){return function(){return Function.prototype.apply.apply(r,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var r=this.getLevel(),o=0;o<i.length;o++){var n=i[o];this[n]=o<r?e:this.methodFactory(n,r,this.name)}if(this.log=this.debug,typeof console===t&&r<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(i,o,n){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&r?a:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,r){var s,a,d,u=this,h="loglevel";function m(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var r=window.document.cookie,i=encodeURIComponent(h),o=r.indexOf(i+"=");-1!==o&&(e=/^([^;]+)/.exec(r.slice(o+i.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function p(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=r||l,u.getLevel=function(){return null!=d?d:null!=a?a:s},u.setLevel=function(e,r){return d=p(e),!1!==r&&function(e){var r=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=r)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+r+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=p(e),m()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(n!==u&&(s=p(n.getLevel())),c.call(u),n===u)for(var e in o)o[e].rebuild()},s=p(n?n.getLevel():"WARN");var g=m();null!=g&&(d=p(g)),c.call(u)}(n=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=o[e];return t||(t=o[e]=new u(e,n.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return n.noConflict=function(){return typeof window!==t&&window.log===n&&(window.log=h),n},n.getLoggers=function(){return o},n.default=n,n},e.exports?e.exports=i():r.log=i()}(r);var i=r.exports;let o;const n=new Uint8Array(16);function s(){if(!o&&(o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(n)}var a=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const c=[];for(let e=0;e<256;++e)c.push((e+256).toString(16).slice(1));function d(e,t=0){return c[e[t+0]]+c[e[t+1]]+c[e[t+2]]+c[e[t+3]]+"-"+c[e[t+4]]+c[e[t+5]]+"-"+c[e[t+6]]+c[e[t+7]]+"-"+c[e[t+8]]+c[e[t+9]]+"-"+c[e[t+10]]+c[e[t+11]]+c[e[t+12]]+c[e[t+13]]+c[e[t+14]]+c[e[t+15]]}function l(e,t,r){function i(e,i,o,n){var s;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}(e)),"string"==typeof i&&(i=function(e){if(!function(e){return"string"==typeof e&&a.test(e)}(e))throw TypeError("Invalid UUID");let t;const r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(i)),16!==(null===(s=i)||void 0===s?void 0:s.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+e.length);if(c.set(i),c.set(e,i.length),c=r(c),c[6]=15&c[6]|t,c[8]=63&c[8]|128,o){n=n||0;for(let e=0;e<16;++e)o[n+e]=c[e];return o}return d(c)}try{i.name=e}catch(e){}return i.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",i.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",i}function u(e){return 14+(e+64>>>9<<4)+1}function h(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function m(e,t,r,i,o,n){return h((s=h(h(t,e),h(i,n)))<<(a=o)|s>>>32-a,r);var s,a}function p(e,t,r,i,o,n,s){return m(t&r|~t&i,e,t,o,n,s)}function g(e,t,r,i,o,n,s){return m(t&i|r&~i,e,t,o,n,s)}function f(e,t,r,i,o,n,s){return m(t^r^i,e,t,o,n,s)}function v(e,t,r,i,o,n,s){return m(r^(t|~i),e,t,o,n,s)}l("v3",48,(function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r)}return function(e){const t=[],r=32*e.length,i="0123456789abcdef";for(let o=0;o<r;o+=8){const r=e[o>>5]>>>o%32&255,n=parseInt(i.charAt(r>>>4&15)+i.charAt(15&r),16);t.push(n)}return t}(function(e,t){e[t>>5]|=128<<t%32,e[u(t)-1]=t;let r=1732584193,i=-271733879,o=-1732584194,n=271733878;for(let t=0;t<e.length;t+=16){const s=r,a=i,c=o,d=n;r=p(r,i,o,n,e[t],7,-680876936),n=p(n,r,i,o,e[t+1],12,-389564586),o=p(o,n,r,i,e[t+2],17,606105819),i=p(i,o,n,r,e[t+3],22,-1044525330),r=p(r,i,o,n,e[t+4],7,-176418897),n=p(n,r,i,o,e[t+5],12,1200080426),o=p(o,n,r,i,e[t+6],17,-1473231341),i=p(i,o,n,r,e[t+7],22,-45705983),r=p(r,i,o,n,e[t+8],7,1770035416),n=p(n,r,i,o,e[t+9],12,-1958414417),o=p(o,n,r,i,e[t+10],17,-42063),i=p(i,o,n,r,e[t+11],22,-1990404162),r=p(r,i,o,n,e[t+12],7,1804603682),n=p(n,r,i,o,e[t+13],12,-40341101),o=p(o,n,r,i,e[t+14],17,-1502002290),i=p(i,o,n,r,e[t+15],22,1236535329),r=g(r,i,o,n,e[t+1],5,-165796510),n=g(n,r,i,o,e[t+6],9,-1069501632),o=g(o,n,r,i,e[t+11],14,643717713),i=g(i,o,n,r,e[t],20,-373897302),r=g(r,i,o,n,e[t+5],5,-701558691),n=g(n,r,i,o,e[t+10],9,38016083),o=g(o,n,r,i,e[t+15],14,-660478335),i=g(i,o,n,r,e[t+4],20,-405537848),r=g(r,i,o,n,e[t+9],5,568446438),n=g(n,r,i,o,e[t+14],9,-1019803690),o=g(o,n,r,i,e[t+3],14,-187363961),i=g(i,o,n,r,e[t+8],20,1163531501),r=g(r,i,o,n,e[t+13],5,-1444681467),n=g(n,r,i,o,e[t+2],9,-51403784),o=g(o,n,r,i,e[t+7],14,1735328473),i=g(i,o,n,r,e[t+12],20,-1926607734),r=f(r,i,o,n,e[t+5],4,-378558),n=f(n,r,i,o,e[t+8],11,-2022574463),o=f(o,n,r,i,e[t+11],16,1839030562),i=f(i,o,n,r,e[t+14],23,-35309556),r=f(r,i,o,n,e[t+1],4,-1530992060),n=f(n,r,i,o,e[t+4],11,1272893353),o=f(o,n,r,i,e[t+7],16,-155497632),i=f(i,o,n,r,e[t+10],23,-1094730640),r=f(r,i,o,n,e[t+13],4,681279174),n=f(n,r,i,o,e[t],11,-358537222),o=f(o,n,r,i,e[t+3],16,-722521979),i=f(i,o,n,r,e[t+6],23,76029189),r=f(r,i,o,n,e[t+9],4,-640364487),n=f(n,r,i,o,e[t+12],11,-421815835),o=f(o,n,r,i,e[t+15],16,530742520),i=f(i,o,n,r,e[t+2],23,-995338651),r=v(r,i,o,n,e[t],6,-198630844),n=v(n,r,i,o,e[t+7],10,1126891415),o=v(o,n,r,i,e[t+14],15,-1416354905),i=v(i,o,n,r,e[t+5],21,-57434055),r=v(r,i,o,n,e[t+12],6,1700485571),n=v(n,r,i,o,e[t+3],10,-1894986606),o=v(o,n,r,i,e[t+10],15,-1051523),i=v(i,o,n,r,e[t+1],21,-2054922799),r=v(r,i,o,n,e[t+8],6,1873313359),n=v(n,r,i,o,e[t+15],10,-30611744),o=v(o,n,r,i,e[t+6],15,-1560198380),i=v(i,o,n,r,e[t+13],21,1309151649),r=v(r,i,o,n,e[t+4],6,-145523070),n=v(n,r,i,o,e[t+11],10,-1120210379),o=v(o,n,r,i,e[t+2],15,718787259),i=v(i,o,n,r,e[t+9],21,-343485551),r=h(r,s),i=h(i,a),o=h(o,c),n=h(n,d)}return[r,i,o,n]}(function(e){if(0===e.length)return[];const t=8*e.length,r=new Uint32Array(u(t));for(let i=0;i<t;i+=8)r[i>>5]|=(255&e[i/8])<<i%32;return r}(e),8*e.length))}));var y={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function b(e,t,r){if(y.randomUUID&&!t&&!e)return y.randomUUID();const i=(e=e||{}).random||(e.rng||s)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return d(i)}function _(e,t,r,i){switch(e){case 0:return t&r^~t&i;case 1:case 3:return t^r^i;case 2:return t&r^t&i^r&i}}function w(e,t){return e<<t|e>>>32-t}function k(e){return k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(e)}function S(e,t,r){return(t=function(e){var t=function(e){if("object"!=k(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=k(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==k(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function C(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function I(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?C(Object(r),!0).forEach((function(t){S(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):C(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function T(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}l("v5",80,(function(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);const i=Math.ceil((e.length/4+2)/16),o=new Array(i);for(let t=0;t<i;++t){const r=new Uint32Array(16);for(let i=0;i<16;++i)r[i]=e[64*t+4*i]<<24|e[64*t+4*i+1]<<16|e[64*t+4*i+2]<<8|e[64*t+4*i+3];o[t]=r}o[i-1][14]=8*(e.length-1)/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<i;++e){const i=new Uint32Array(80);for(let t=0;t<16;++t)i[t]=o[e][t];for(let e=16;e<80;++e)i[e]=w(i[e-3]^i[e-8]^i[e-14]^i[e-16],1);let n=r[0],s=r[1],a=r[2],c=r[3],d=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),o=w(n,5)+_(r,s,a,c)+d+t[r]+i[e]>>>0;d=c,c=a,a=w(s,30)>>>0,s=n,n=o}r[0]=r[0]+n>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+a>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+d>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]}));var E="function"==typeof Symbol&&Symbol.observable||"@@observable",P=function(){return Math.random().toString(36).substring(7).split("").join(".")},M={INIT:"@@redux/INIT"+P(),REPLACE:"@@redux/REPLACE"+P(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+P()}};function R(e,t,r){var i;if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error(T(0));if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(T(1));return r(R)(e,t)}if("function"!=typeof e)throw new Error(T(2));var o=e,n=t,s=[],a=s,c=!1;function d(){a===s&&(a=s.slice())}function l(){if(c)throw new Error(T(3));return n}function u(e){if("function"!=typeof e)throw new Error(T(4));if(c)throw new Error(T(5));var t=!0;return d(),a.push(e),function(){if(t){if(c)throw new Error(T(6));t=!1,d();var r=a.indexOf(e);a.splice(r,1),s=null}}}function h(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(T(7));if(void 0===e.type)throw new Error(T(8));if(c)throw new Error(T(9));try{c=!0,n=o(n,e)}finally{c=!1}for(var t=s=a,r=0;r<t.length;r++)(0,t[r])();return e}return h({type:M.INIT}),(i={dispatch:h,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(T(10));o=e,h({type:M.REPLACE})}})[E]=function(){var e,t=u;return(e={subscribe:function(e){if("object"!=typeof e||null===e)throw new Error(T(11));function r(){e.next&&e.next(l())}return r(),{unsubscribe:t(r)}}})[E]=function(){return this},e},i}function A(e){for(var t=Object.keys(e),r={},i=0;i<t.length;i++){var o=t[i];"function"==typeof e[o]&&(r[o]=e[o])}var n,s=Object.keys(r);try{!function(e){Object.keys(e).forEach((function(t){var r=e[t];if(void 0===r(void 0,{type:M.INIT}))throw new Error(T(12));if(void 0===r(void 0,{type:M.PROBE_UNKNOWN_ACTION()}))throw new Error(T(13))}))}(r)}catch(e){n=e}return function(e,t){if(void 0===e&&(e={}),n)throw n;for(var i=!1,o={},a=0;a<s.length;a++){var c=s[a],d=e[c],l=(0,r[c])(d,t);if(void 0===l)throw new Error(T(14));o[c]=l,i=i||l!==d}return(i=i||s.length!==Object.keys(e).length)?o:e}}function x(e,t){return function(){return t(e.apply(this,arguments))}}function O(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return 0===t.length?function(e){return e}:1===t.length?t[0]:t.reduce((function(e,t){return function(){return e(t.apply(void 0,arguments))}}))}function L(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e){return function(){var r=e.apply(void 0,arguments),i=function(){throw new Error(T(15))},o={getState:r.getState,dispatch:function(){return i.apply(void 0,arguments)}},n=t.map((function(e){return e(o)}));return i=O.apply(void 0,n)(r.dispatch),I(I({},r),{},{dispatch:i})}}}var j=/*#__PURE__*/Object.freeze({__proto__:null,__DO_NOT_USE__ActionTypes:M,applyMiddleware:L,bindActionCreators:function(e,t){if("function"==typeof e)return x(e,t);if("object"!=typeof e||null===e)throw new Error(T(16));var r={};for(var i in e){var o=e[i];"function"==typeof o&&(r[i]=x(o,t))}return r},combineReducers:A,compose:O,createStore:R,legacy_createStore:R}),D=function(e){return"@@redux-saga/"+e},W=
7
7
  /*#__PURE__*/
8
8
  D("CANCEL_PROMISE"),V=
9
9
  /*#__PURE__*/
@@ -27,5 +27,5 @@ D("TERMINATE"),K=
27
27
  /*#__PURE__*/
28
28
  D("LOCATION");function G(){return G=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},G.apply(null,arguments)}var J=function(e){return null==e},Q=function(e){return null!=e},X=function(e){return"function"==typeof e},Y=function(e){return"string"==typeof e},Z=Array.isArray,ee=function(e){return e&&X(e.then)},te=function(e){return e&&X(e.next)&&X(e.throw)},re=function e(t){return t&&(Y(t)||oe(t)||X(t)||Z(t)&&t.every(e))},ie=function(e){return e&&X(e.take)&&X(e.close)},oe=function(e){return Boolean(e)&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype},ne=
29
29
  /*#__PURE__*/
30
- function(){return function(){return!0}}(),se=function(){},ae=function(e){return e},ce=function(e,t){G(e,t),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(t).forEach((function(r){e[r]=t[r]}))};function de(e,t){var r=e.indexOf(t);r>=0&&e.splice(r,1)}function le(e){var t=!1;return function(){t||(t=!0,e())}}var ue=function(e){throw e},he=function(e){return{value:e,done:!0}};function me(e,t,r){void 0===t&&(t=ue),void 0===r&&(r="iterator");var i={meta:{name:r},next:e,throw:t,return:he,isSagaIterator:!0};return"undefined"!=typeof Symbol&&(i[Symbol.iterator]=function(){return i}),i}function pe(e,t){var r=t.sagaStack;console.error(e),console.error(r)}var ge=function(e){return Array.apply(null,new Array(e))},fe=function(e){return function(t){return e(Object.defineProperty(t,z,{value:!0}))}},ve=function(e){return e===q},ye=function(e){return e===H},be=function(e){return ve(e)||ye(e)};function _e(e,t){var r,i=Object.keys(e),o=i.length,n=0,s=Z(e)?ge(o):{},a={};return i.forEach((function(e){var i=function(i,a){r||(a||be(i)?(t.cancel(),t(i,a)):(s[e]=i,++n===o&&(r=!0,t(s))))};i.cancel=se,a[e]=i})),t.cancel=function(){r||(r=!0,i.forEach((function(e){return a[e].cancel()})))},a}function we(e){return{name:e.name||"anonymous",location:ke(e)}}function ke(e){return e[K]}function Se(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return 0===t.length?function(e){return e}:1===t.length?t[0]:t.reduce((function(e,t){return function(){return e(t.apply(void 0,arguments))}}))}var Ce={isEmpty:ne,put:se,take:se},Ie="TAKE",Te="CALL",Ee="FORK",Pe="JOIN",Me="SELECT",Re="CANCELLED",Ae=function(e,t){var r;return(r={})[N]=!0,r.combinator=!1,r.type=e,r.payload=t,r};function xe(e,t){return void 0===e&&(e="*"),re(e)?(Q(t)&&console.warn("take(pattern) takes one argument but two were provided. Consider passing an array for listening to several action types"),Ae(Ie,{pattern:e})):ie(r=e)&&r[U]&&Q(t)&&re(t)?Ae(Ie,{channel:e,pattern:t}):ie(e)?(Q(t)&&console.warn("take(channel) takes one argument but two were provided. Second argument is ignored."),Ae(Ie,{channel:e})):void 0;var r}function Oe(e,t){return J(t)&&(t=e,e=void 0),Ae("PUT",{channel:e,action:t})}function je(e,t){var r,i=null;return X(e)?r=e:(Z(e)?(i=e[0],r=e[1]):(i=e.context,r=e.fn),i&&Y(r)&&X(i[r])&&(r=i[r])),{context:i,fn:r,args:t}}function Le(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return Ae(Te,je(e,r))}function De(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return Ae(Ee,je(e,r))}function We(e){void 0===e&&(e=ae);for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return Ae(Me,{selector:e,args:r})}function Ve(){return Ae(Re,{})}var Ne=[],$e=0;function Ue(e){try{Fe(),e()}finally{He()}}function ze(e){Ne.push(e),$e||(Fe(),qe())}function Be(e){try{return Fe(),e()}finally{qe()}}function Fe(){$e++}function He(){$e--}function qe(){var e;for(He();!$e&&void 0!==(e=Ne.shift());)Ue(e)}var Ke=function(e){return function(t){return e.some((function(e){return Ye(e)(t)}))}},Ge=function(e){return function(t){return e(t)}},Je=function(e){return function(t){return t.type===String(e)}},Qe=function(e){return function(t){return t.type===e}},Xe=function(){return ne};function Ye(e){var t="*"===e?Xe:Y(e)?Je:Z(e)?Ke:function(e){return X(e)&&e.hasOwnProperty("toString")}(e)?Je:X(e)?Ge:oe(e)?Qe:null;if(null===t)throw new Error("invalid pattern: "+e);return t(e)}var Ze={type:V},et=function(e){return e&&e.type===V};function tt(e){void 0===e&&(e=function(e){void 0===e&&(e=10);var t=new Array(e),r=0,i=0,o=0,n=function(){if(0!=r){var i=t[o];return t[o]=null,r--,o=(o+1)%e,i}},s=function(){for(var e=[];r;)e.push(n());return e};return{isEmpty:function(){return 0==r},put:function(n){var a;r<e||(a=2*e,t=s(),r=t.length,i=t.length,o=0,t.length=a,e=a),function(o){t[i]=o,i=(i+1)%e,r++}(n)},take:n,flush:s}}(void 0));var t=!1,r=[];return{take:function(i){t&&e.isEmpty()?i(Ze):e.isEmpty()?(r.push(i),i.cancel=function(){de(r,i)}):i(e.take())},put:function(i){if(!t){if(0===r.length)return e.put(i);r.shift()(i)}},flush:function(r){t&&e.isEmpty()?r(Ze):r(e.flush())},close:function(){if(!t){t=!0;var e=r;r=[];for(var i=0,o=e.length;i<o;i++)(0,e[i])(Ze)}}}}function rt(e,t){void 0===t&&(t=Ce);var r,i=!1,o=tt(t),n=function(){i||(i=!0,X(r)&&r(),o.close())};return r=le(r=e((function(e){et(e)?n():o.put(e)}))),i&&r(),{take:o.take,flush:o.flush,close:n}}function it(){var e,t=!1,r=[],i=r,o=function(){i===r&&(i=r.slice())},n=function(){t=!0;var e=r=i;i=[],e.forEach((function(e){e(Ze)}))};return(e={})[U]=!0,e.put=function(e){if(!t)if(et(e))n();else for(var o=r=i,s=0,a=o.length;s<a;s++){var c=o[s];c[$](e)&&(c.cancel(),c(e))}},e.take=function(e,r){void 0===r&&(r=Xe),t?e(Ze):(e[$]=r,o(),i.push(e),e.cancel=le((function(){o(),de(i,e)})))},e.close=n,e}function ot(){var e=it(),t=e.put;return e.put=function(e){e[z]?t(e):ze((function(){t(e)}))},e}function nt(e,t){var r=e[W];X(r)&&(t.cancel=r),e.then(t,(function(e){t(e,!0)}))}var st,at=0,ct=function(){return++at};function dt(e){e.isRunning()&&e.cancel()}var lt=((st={})[Ie]=function(e,t,r){var i=t.channel,o=void 0===i?e.channel:i,n=t.pattern,s=t.maybe,a=function(e){e instanceof Error?r(e,!0):!et(e)||s?r(e):r(q)};try{o.take(a,Q(n)?Ye(n):null)}catch(e){return void r(e,!0)}r.cancel=a.cancel},st.PUT=function(e,t,r){var i=t.channel,o=t.action,n=t.resolve;ze((function(){var t;try{t=(i?i.put:e.dispatch)(o)}catch(e){return void r(e,!0)}n&&ee(t)?nt(t,r):r(t)}))},st.ALL=function(e,t,r,i){var o=i.digestEffect,n=at,s=Object.keys(t);if(0!==s.length){var a=_e(t,r);s.forEach((function(e){o(t[e],n,a[e],e)}))}else r(Z(t)?[]:{})},st.RACE=function(e,t,r,i){var o=i.digestEffect,n=at,s=Object.keys(t),a=Z(t)?ge(s.length):{},c={},d=!1;s.forEach((function(e){var t=function(t,i){d||(i||be(t)?(r.cancel(),r(t,i)):(r.cancel(),d=!0,a[e]=t,r(a)))};t.cancel=se,c[e]=t})),r.cancel=function(){d||(d=!0,s.forEach((function(e){return c[e].cancel()})))},s.forEach((function(e){d||o(t[e],n,c[e],e)}))},st[Te]=function(e,t,r,i){var o=t.context,n=t.fn,s=t.args,a=i.task;try{var c=n.apply(o,s);if(ee(c))return void nt(c,r);if(te(c))return void _t(e,c,a.context,at,we(n),!1,r);r(c)}catch(e){r(e,!0)}},st.CPS=function(e,t,r){var i=t.context,o=t.fn,n=t.args;try{var s=function(e,t){J(e)?r(t):r(e,!0)};o.apply(i,n.concat(s)),s.cancel&&(r.cancel=s.cancel)}catch(e){r(e,!0)}},st[Ee]=function(e,t,r,i){var o=t.fn,n=t.detached,s=i.task,a=function(e){var t=e.context,r=e.fn,i=e.args;try{var o=r.apply(t,i);if(te(o))return o;var n=!1;return me((function(e){return n?{value:e,done:!0}:(n=!0,{value:o,done:!ee(o)})}))}catch(e){return me((function(){throw e}))}}({context:t.context,fn:o,args:t.args}),c=function(e,t){return e.isSagaIterator?{name:e.meta.name}:we(t)}(a,o);Be((function(){var t=_t(e,a,s.context,at,c,n,void 0);n?r(t):t.isRunning()?(s.queue.addTask(t),r(t)):t.isAborted()?s.queue.abort(t.error()):r(t)}))},st[Pe]=function(e,t,r,i){var o=i.task,n=function(e,t){if(e.isRunning()){var r={task:o,cb:t};t.cancel=function(){e.isRunning()&&de(e.joiners,r)},e.joiners.push(r)}else e.isAborted()?t(e.error(),!0):t(e.result())};if(Z(t)){if(0===t.length)return void r([]);var s=_e(t,r);t.forEach((function(e,t){n(e,s[t])}))}else n(t,r)},st.CANCEL=function(e,t,r,i){t===B?dt(i.task):Z(t)?t.forEach(dt):dt(t),r()},st[Me]=function(e,t,r){var i=t.selector,o=t.args;try{r(i.apply(void 0,[e.getState()].concat(o)))}catch(e){r(e,!0)}},st.ACTION_CHANNEL=function(e,t,r){var i=t.pattern,o=tt(t.buffer),n=Ye(i),s=function t(r){et(r)||e.channel.take(t,n),o.put(r)},a=o.close;o.close=function(){s.cancel(),a()},e.channel.take(s,n),r(o)},st[Re]=function(e,t,r,i){r(i.task.isCancelled())},st.FLUSH=function(e,t,r){t.flush(r)},st.GET_CONTEXT=function(e,t,r,i){r(i.task.context[t])},st.SET_CONTEXT=function(e,t,r,i){ce(i.task.context,t),r()},st);function ut(e,t){return e+"?"+t}function ht(e){var t=e.name,r=e.location;return r?t+" "+ut(r.fileName,r.lineNumber):t}function mt(e){var t,r=(t=[]).concat.apply(t,e.map((function(e){return e.cancelledTasks})));return r.length?["Tasks cancelled due to error:"].concat(r).join("\n"):""}var pt=null,gt=[],ft=function(e){e.crashedEffect=pt,gt.push(e)},vt=function(){pt=null,gt.length=0},yt=function(e){pt=e},bt=function(){var e,t=gt[0],r=gt.slice(1),i=t.crashedEffect?(e=ke(t.crashedEffect))?e.code+" "+ut(e.fileName,e.lineNumber):"":null;return["The above error occurred in task "+ht(t.meta)+(i?" \n when executing effect "+i:"")].concat(r.map((function(e){return" created by "+ht(e.meta)})),[mt(gt)]).join("\n")};function _t(e,t,r,i,o,n,s){var a=e.finalizeRunEffect((function(t,r,i){ee(t)?nt(t,i):te(t)?_t(e,t,d.context,r,o,!1,i):t&&t[N]?(0,lt[t.type])(e,t.payload,i,l):i(t)}));u.cancel=se;var c={meta:o,cancel:function(){0===c.status&&(c.status=1,u(H))},status:0},d=function(e,t,r,i,o,n,s){var a;void 0===s&&(s=se);var c,d,l=0,u=null,h=[],m=Object.create(r),p=function(e,t,r){var i,o=[],n=!1;function s(e){h.push.apply(h,p.getTasks().map((function(e){return e.meta.name}))),c(),r(e,!0)}function a(t){o.push(t),t.cont=function(a,c){n||(de(o,t),t.cont=se,c?s(a):(t===e&&(i=a),o.length||(n=!0,r(i))))}}function c(){n||(n=!0,o.forEach((function(e){e.cont=se,e.cancel()})),o=[])}return a(e),{addTask:a,cancelAll:c,abort:s,getTasks:function(){return o}}}(t,0,g);function g(t,r){if(r){if(l=2,ft({meta:o,cancelledTasks:h}),f.isRoot){var i=bt();vt(),e.onError(t,{sagaStack:i})}d=t,u&&u.reject(t)}else t===H?l=1:1!==l&&(l=3),c=t,u&&u.resolve(t);f.cont(t,r),f.joiners.forEach((function(e){e.cb(t,r)})),f.joiners=null}var f=((a={})[F]=!0,a.id=i,a.meta=o,a.isRoot=n,a.context=m,a.joiners=[],a.queue=p,a.cancel=function(){0===l&&(l=1,p.cancelAll(),g(H,!1))},a.cont=s,a.end=g,a.setContext=function(e){ce(m,e)},a.toPromise=function(){return u||((e={}).promise=new Promise((function(t,r){e.resolve=t,e.reject=r})),u=e,2===l?u.reject(d):0!==l&&u.resolve(c)),u.promise;var e},a.isRunning=function(){return 0===l},a.isCancelled=function(){return 1===l||0===l&&1===t.status},a.isAborted=function(){return 2===l},a.result=function(){return c},a.error=function(){return d},a);return f}(e,c,r,i,o,n,s),l={task:d,digestEffect:h};return s&&(s.cancel=d.cancel),u(),d;function u(e,r){try{var o;r?(o=t.throw(e),vt()):ye(e)?(c.status=1,u.cancel(),o=X(t.return)?t.return(H):{done:!0,value:H}):o=ve(e)?X(t.return)?t.return():{done:!0}:t.next(e),o.done?(1!==c.status&&(c.status=3),c.cont(o.value)):h(o.value,i,u)}catch(e){if(1===c.status)throw e;c.status=2,c.cont(e,!0)}}function h(t,r,i,o){void 0===o&&(o="");var n,s=ct();function c(r,o){n||(n=!0,i.cancel=se,e.sagaMonitor&&(o?e.sagaMonitor.effectRejected(s,r):e.sagaMonitor.effectResolved(s,r)),o&&yt(t),i(r,o))}e.sagaMonitor&&e.sagaMonitor.effectTriggered({effectId:s,parentEffectId:r,label:o,effect:t}),c.cancel=se,i.cancel=function(){n||(n=!0,c.cancel(),c.cancel=se,e.sagaMonitor&&e.sagaMonitor.effectCancelled(s))},a(t,s,c)}}function wt(e,t){for(var r=e.channel,i=void 0===r?ot():r,o=e.dispatch,n=e.getState,s=e.context,a=void 0===s?{}:s,c=e.sagaMonitor,d=e.effectMiddlewares,l=e.onError,u=void 0===l?pe:l,h=arguments.length,m=new Array(h>2?h-2:0),p=2;p<h;p++)m[p-2]=arguments[p];var g,f=t.apply(void 0,m),v=ct();if(c&&(c.rootSagaStarted=c.rootSagaStarted||se,c.effectTriggered=c.effectTriggered||se,c.effectResolved=c.effectResolved||se,c.effectRejected=c.effectRejected||se,c.effectCancelled=c.effectCancelled||se,c.actionDispatched=c.actionDispatched||se,c.rootSagaStarted({effectId:v,saga:t,args:m})),d){var y=Se.apply(void 0,d);g=function(e){return function(t,r,i){return y((function(t){return e(t,r,i)}))(t)}}}else g=ae;var b={channel:i,dispatch:fe(o),getState:n,sagaMonitor:c,onError:u,finalizeRunEffect:g};return Be((function(){var e=_t(b,f,a,v,we(t),!0,void 0);return c&&c.effectResolved(v,e),e}))}var kt={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function o(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,i,o=[];if(0===this._eventsCount)return o;for(i in e=this._events)t.call(e,i)&&o.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[r?r+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var i=0,o=t.length,n=new Array(o);i<o;i++)n[i]=t[i].fn;return n},a.prototype.listenerCount=function(e){var t=this._events[r?r+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,i,o,n,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,d,l=this._events[a],u=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,i),!0;case 4:return l.fn.call(l.context,t,i,o),!0;case 5:return l.fn.call(l.context,t,i,o,n),!0;case 6:return l.fn.call(l.context,t,i,o,n,s),!0}for(d=1,c=new Array(u-1);d<u;d++)c[d-1]=arguments[d];l.fn.apply(l.context,c)}else{var h,m=l.length;for(d=0;d<m;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),u){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,t);break;case 3:l[d].fn.call(l[d].context,t,i);break;case 4:l[d].fn.call(l[d].context,t,i,o);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];l[d].fn.apply(l[d].context,c)}}return!0},a.prototype.on=function(e,t,r){return n(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,i,o){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return s(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||o&&!a.once||i&&a.context!==i||s(this,n);else{for(var c=0,d=[],l=a.length;c<l;c++)(a[c].fn!==t||o&&!a[c].once||i&&a[c].context!==i)&&d.push(a[c]);d.length?this._events[n]=1===d.length?d[0]:d:s(this,n)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=r?r+e:e]&&s(this,t):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(kt);var St=kt.exports,Ct=Object.defineProperty,It=Object.defineProperties,Tt=Object.getOwnPropertyDescriptor,Et=Object.getOwnPropertyDescriptors,Pt=Object.getOwnPropertyNames,Mt=Object.getOwnPropertySymbols,Rt=Object.prototype.hasOwnProperty,At=Object.prototype.propertyIsEnumerable,xt=(e,t,r)=>t in e?Ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Ot=(e,t)=>{for(var r in t||(t={}))Rt.call(t,r)&&xt(e,r,t[r]);if(Mt)for(var r of Mt(t))At.call(t,r)&&xt(e,r,t[r]);return e},jt=(e,t)=>It(e,Et(t)),Lt=(e,t)=>{var r={};for(var i in e)Rt.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&Mt)for(var i of Mt(e))t.indexOf(i)<0&&At.call(e,i)&&(r[i]=e[i]);return r},Dt=(e,t)=>{for(var r in t)Ct(e,r,{get:t[r],enumerable:!0})},Wt=(e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of Pt(t))Rt.call(e,o)||o===r||Ct(e,o,{get:()=>t[o],enumerable:!(i=Tt(t,o))||i.enumerable});return e},Vt=(e,t,r)=>(Wt(e,t,"default"),r&&Wt(r,t,"default")),Nt=(e,t,r)=>xt(e,"symbol"!=typeof t?t+"":t,r),$t="__local__",Ut="__synthetic__",zt="chat",Bt=Symbol.for("sw-execute-connection-closed"),Ft=Symbol.for("sw-execute-timeout"),Ht=Symbol.for("sw-connect-error"),qt=i.getLogger("signalwire"),Kt=qt.methodFactory;qt.methodFactory=(e,t,r)=>{const i=Kt(e,t,r);return function(...e){e.unshift(/* @__PURE__ */(new Date).toISOString(),"-"),i.apply(void 0,e)}};var Gt,Jt=qt.getLevel();qt.setLevel(Jt);var Qt={},Xt=()=>null!=Gt?Gt:qt,Yt=({type:e,payload:t})=>{const r=Xt(),{logWsTraffic:i}=Qt||{};if(!i)return;const o=(e=>!("method"in e)||"signalwire.ping"!==e.method)(t)?JSON.stringify(t,null,2):t;return r.info(`${e.toUpperCase()}: \n`,o,"\n")},Zt=()=>{const e=Xt();return new Proxy(e,{get:(e,t,r)=>"wsTraffic"===t?Yt:Reflect.get(e,t,r)})},er=/[A-Z]/g,tr=e=>e.replace(er,(e=>`_${e.toLowerCase()}`)),rr=["webrtc.message"],ir=e=>rr.includes(e),or=/^2[0-9][0-9]$/,nr=(e,t)=>{const{result:r={},error:i}=e;if(i)return{error:i};const{code:o,node_id:n,result:s=null}=r;return o&&!or.test(o)?{error:r}:null===s?(t&&(r.node_id=t),{result:r}):s?s.jsonrpc?nr(s,n):{result:s}:{result:r}},sr={propsToUpdateValue:["updated","layers","members","recordings","playbacks"]},ar=(e,t=sr)=>(null==e?void 0:e.__sw_symbol)||(null==e?void 0:e.__sw_proxy)?e:Object.entries(e).reduce(((e,[r,i])=>{const o=cr(r);return e[o]="object"==typeof i&&i?Array.isArray(i)?t.propsToUpdateValue.includes(r)?i.map((e=>"string"==typeof e?cr(e):ar(e))):i:ar(i):(e=>e.endsWith("At"))(o)?(e=>{if(void 0===e)return e;const t=new Date(1e3*e);return isNaN(t.getTime())?e:t})(i):i,e}),{}),cr=e=>e.includes("_")?e.split("_").reduce(((e,t,r)=>{const i=t.trim().charAt(0),o=t.substr(1).toLowerCase();return`${e}${0===r?i.toLowerCase():i.toUpperCase()}${o}`}),""):e,dr=(e,t=e=>e,r={})=>(Array.isArray(e)?r=e.map(((e,i)=>"object"==typeof e?dr(e,t,r[i]):e)):Object.keys(e).forEach((i=>{const o=tr(i);r[o]=e[i]&&"object"==typeof e[i]?dr(e[i],t,r[o]):t(e[i])})),r),lr=(e,t)=>(Object.keys(t).forEach((t=>{if(e.prototype.hasOwnProperty(t))throw new Error(`[extendComponent] Duplicated method name: ${t}`)})),Object.defineProperties(e.prototype,t),e),ur=(e,t)=>{if(t&&"string"==typeof t){const r=new RegExp(`^${t}.`);return e.replace(r,"")}const r=e.split(".");return r.length>1?(r.shift(),r.join(".")):e},hr=({delayLimit:e=Number.MAX_SAFE_INTEGER,initialDelay:t=100,variation:r=1})=>{if(t<0||e<0||r<0)throw new Error("No Negative Numbers");if(t>e)throw new Error("initialDelay must be lte delayLimit");let i=Math.min(t,e);return()=>{if(i===e)return e;const t=i;return i=Math.min(i+r,e),t}},mr=({initialDelay:e=100})=>{if(e<0)throw new Error("No Negative Numbers");return()=>e},pr=async({asyncCallable:e,maxRetries:t=10,delayFn:r,validator:i,expectedErrorHandler:o})=>{let n=t-1,s=0;const a=async()=>{var c;try{let t;return t=s<=0?await e():await new Promise(((t,r)=>setTimeout((()=>{e().then(t).catch(r)}),s))),n&&(null==i||i(t)),t}catch(e){if(n-- >0&&!(null==o?void 0:o(e)))return s=null!=(c=null==r?void 0:r())?c:0,Zt().debug(`Retrying request: ${t-n} of ${t}`),a();throw e}};return a()},gr=/^(ws|wss):\/\//,fr=(e,t,r)=>{let i=null;return Promise.race([e,new Promise(((e,o)=>i=setTimeout(o,t,r)))]).finally((()=>clearTimeout(i)))},vr=["video.member.updated","video.member.talking"],yr=["video.room.joined","video.track","video.active","video.answering","video.destroy","video.early","video.hangup","video.held","video.new","video.purge","video.recovering","video.requesting","video.ringing","video.trying","video.media.connected","video.media.reconnecting","video.media.disconnected","video.microphone.updated","video.camera.updated","video.speaker.updated","video.microphone.disconnected","video.camera.disconnected","video.speaker.disconnected"],br=e=>{const t=e.map((e=>{if("string"==typeof e){const t=(e=>{const t=e.split(":");return t[t.length-1]})(e);return yr.includes(t)||(e=>e.includes(Ut))(t)||_r(t)||(e=>e.includes("session."))(t)?null:vr.find((e=>t.startsWith(e)))||t}return e}));return Array.from(new Set(t)).filter(Boolean)},_r=e=>e.includes($t),wr=e=>Boolean(e.method),kr=e=>void 0!==e&&"jti"in e,Sr=e=>wr(e)&&"signalwire.connect"==e.method,Cr=e=>{var t;return Ot({jsonrpc:"2.0",id:null!=(t=e.id)?t:b()},e)},Ir=e=>Ot({jsonrpc:"2.0"},e),Tr={major:3,minor:0,revision:0},Er={major:4,minor:0,revision:0},Pr=e=>Cr({method:"signalwire.connect",params:Ot({version:Tr,event_acks:!0},e)}),Mr=e=>Cr({method:"signalwire.reauthenticate",params:{authentication:e}}),Rr={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",fromFabricAddressId:"from_fabric_address_id"},Ar=e=>{if(e.hasOwnProperty("dialogParams")){const t=Lt(e.dialogParams,["remoteSdp","localStream","remoteStream"]);for(const e in Rr)e&&t.hasOwnProperty(e)&&(t[Rr[e]]=t[e],delete t[e]);e.dialogParams=t}return e},xr=e=>(t={})=>Cr({method:e,params:Ar(t)}),Or=xr("verto.invite"),jr=xr("verto.bye"),Lr=xr("verto.modify"),Dr=xr("verto.info"),Wr=xr("verto.answer"),Vr=xr("verto.subscribe"),Nr=xr("verto.pong"),$r=(e,t)=>Ir({id:e,result:{method:t}}),Ur={};Dt(Ur,{authErrorAction:()=>Qr,authExpiringAction:()=>Yr,authSuccessAction:()=>Xr,createAction:()=>Br,destroyAction:()=>Gr,getCustomSagaActionType:()=>ni,initAction:()=>Kr,makeCustomSagaAction:()=>oi,reauthAction:()=>Jr,sessionDisconnectedAction:()=>ei,sessionForceCloseAction:()=>ri,sessionReconnectingAction:()=>ti,socketMessageAction:()=>Zr});var zr={};function Br(e,t){function r(...r){if(t){let i=t(...r);if(!i)throw new Error("prepareAction did not return an object");return Ot(Ot({type:e,payload:i.payload},"meta"in i&&{meta:i.meta}),"error"in i&&{error:i.error})}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>t.type===e,r}Dt(zr,{configureStore:()=>qr,createAction:()=>Br}),Vt(zr,L);var Fr="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?O:O.apply(null,arguments)},Hr=!0;function qr(e){const t=function(){return[]},{reducer:r,middleware:i=t(),devTools:o=!0,preloadedState:n,enhancers:s}=e||{};let a;if("function"==typeof r)a=r;else{if(!function(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let r=t;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return t===r}(r))throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');a=A(r)}let c=i;"function"==typeof c&&(c=c(t));const d=j(...c);let l=O;o&&(l=Fr(Ot({trace:!Hr},"object"==typeof o&&o)));let u=[d];return Array.isArray(s)?u=[d,...s]:"function"==typeof s&&(u=s(u)),R(a,n,l(...u))}var Kr=Br("swSdk/init"),Gr=Br("swSdk/destroy"),Jr=Br("swSdk/reauth"),Qr=Br("auth/error"),Xr=Br("auth/success"),Yr=Br("auth/expiring"),Zr=Br("socket/message"),ei=Br("session.disconnected"),ti=Br("session.reconnecting"),ri=Br("session.forceClose"),ii=(e,t)=>`${t.type}/${e}`,oi=(e,t)=>jt(Ot({},t),{type:ii(e,t)}),ni=(e,t)=>ii(e,t);function si(e){const t={},r=[];let i;const o={addCase(e,r){const i="string"==typeof e?e:e.type;if(i in t)throw new Error("addCase cannot be called with two reducers for the same action type");return t[i]=r,o},addMatcher:(e,t)=>(r.push({matcher:e,reducer:t}),o),addDefaultCase:e=>(i=e,o)};return e(o),[t,r,i]}var ai=({name:e="",initialState:t,reducers:r,extraReducers:i})=>function(e){const{name:t}=e;if(!t)throw new Error("`name` is a required option for createSlice");const r=e.initialState,i=e.reducers||{},o=Object.keys(i),n={},s={},a={};function c(){const[t={},i=[],o]="function"==typeof e.extraReducers?si(e.extraReducers):[e.extraReducers],n=Ot(Ot({},t),s);return function(e,t,r=[],i){let o,[n,s,a]="function"==typeof t?si(t):[t,r,i];function c(e=o(),t){let r=[n[t.type],...s.filter((({matcher:e})=>e(t))).map((({reducer:e})=>e))];return 0===r.filter((e=>!!e)).length&&(r=[a]),r.reduce(((e,r)=>r?r(e,t):e),e)}return o="function"==typeof e?()=>e():()=>e,c.getInitialState=o,c}(r,n,i,o)}let d;return o.forEach((e=>{const r=i[e],o=`${t}/${e}`;let c,d;"reducer"in r?(c=r.reducer,d=r.prepare):c=r,n[e]=c,s[o]=c,a[e]=d?Br(o,d):Br(o)})),{name:t,reducer:(e,t)=>(d||(d=c()),d(e,t)),actions:a,caseReducers:n,getInitialState:()=>(d||(d=c()),d.getInitialState())}}({name:e,initialState:t,reducers:r,extraReducers:e=>{e.addCase(Gr.type,(()=>t)),"function"==typeof i&&i(e)}});function ci(e){return[Kr.type,Jr.type].includes(e.type)}var di=ai({name:"session",initialState:{protocol:"",iceServers:[],authStatus:"unknown",authorization:void 0,authorizationState:void 0,authError:void 0,authCount:0},reducers:{connected:(e,{payload:t})=>{var r,i;return jt(Ot({},e),{authStatus:"authorized",authorization:null==t?void 0:t.authorization,authCount:e.authCount+1,protocol:null!=(r=null==t?void 0:t.protocol)?r:"",iceServers:null!=(i=null==t?void 0:t.ice_servers)?i:[]})},authStatus:(e,{payload:t})=>jt(Ot({},e),{authStatus:t}),updateAuthorization:(e,{payload:t})=>jt(Ot({},e),{authorization:t}),updateAuthorizationState:(e,{payload:t})=>jt(Ot({},e),{authorizationState:t})},extraReducers:e=>{e.addCase(Qr.type,((e,{payload:t})=>jt(Ot({},e),{authStatus:"unauthorized",authError:t.error}))),e.addMatcher(ci,(e=>jt(Ot({},e),{authStatus:"authorizing"})))}}),{actions:li,reducer:ui}=di,hi=Symbol("BaseSession"),mi=class{constructor(e){var t,r;this.options=e,Nt(this,"__sw_symbol",hi),Nt(this,"uuid",b()),Nt(this,"WebSocketConstructor"),Nt(this,"CloseEventConstructor"),Nt(this,"agent"),Nt(this,"connectVersion",Tr),Nt(this,"_rpcConnectResult"),Nt(this,"_requests",/* @__PURE__ */new Map),Nt(this,"_socket",null),Nt(this,"_host","wss://relay.signalwire.com"),Nt(this,"_executeTimeoutMs",1e4),Nt(this,"_executeTimeoutError",Ft),Nt(this,"_executeQueue",/* @__PURE__ */new Set),Nt(this,"_swConnectError",Ht),Nt(this,"_executeConnectionClosed",Bt),Nt(this,"_checkPingDelay",15e3),Nt(this,"_checkPingTimer",null),Nt(this,"_reconnectTimer"),Nt(this,"_status","unknown"),Nt(this,"_resolveWaitConnected",null),Nt(this,"_sessionChannel"),Nt(this,"wsOpenHandler"),Nt(this,"wsCloseHandler"),Nt(this,"wsErrorHandler");const{host:i,logLevel:o="info",sessionChannel:n}=e;i&&(this._host=(e=>`${gr.test(e)?"":"wss://"}${e}`)(i)),n&&(this._sessionChannel=n),o&&(null==(r=(t=this.logger).setLevel)||r.call(t,o)),this._onSocketOpen=this._onSocketOpen.bind(this),this._onSocketError=this._onSocketError.bind(this),this._onSocketClose=this._onSocketClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this.execute=this.execute.bind(this),this.connect=this.connect.bind(this),this.wsOpenHandler=e=>{var t;null==(t=this._socket)||t.removeEventListener("open",this.wsOpenHandler),this._onSocketOpen(e)},this.wsCloseHandler=e=>{var t;null==(t=this._socket)||t.removeEventListener("close",this.wsCloseHandler),this._onSocketClose(e)},this.wsErrorHandler=e=>{var t;null==(t=this._socket)||t.removeEventListener("error",this.wsErrorHandler),this._onSocketError(e)}}get host(){return this._host}get rpcConnectResult(){return this._rpcConnectResult}get relayProtocol(){var e,t;return null!=(t=null==(e=this._rpcConnectResult)?void 0:e.protocol)?t:""}get signature(){if(this._rpcConnectResult){const{authorization:e}=this._rpcConnectResult;return e.signature}}get logger(){return Zt()}get connecting(){var e;return 0===(null==(e=this._socket)?void 0:e.readyState)}get connected(){var e;return 1===(null==(e=this._socket)?void 0:e.readyState)}get closing(){var e;return 2===(null==(e=this._socket)?void 0:e.readyState)}get closed(){return!this._socket||3===this._socket.readyState}get status(){return this._status}get idle(){return"idle"===this._status}get ready(){return!Boolean(this.idle||!this.connected)}async _waitConnected(){return new Promise((e=>{this.connected?e():this._resolveWaitConnected=e}))}set token(e){this.options.token=e}connect(){if(!(null==this?void 0:this.WebSocketConstructor))throw new Error("Missing WebSocketConstructor");if(!(null==this?void 0:this.CloseEventConstructor))throw new Error("Missing CloseEventConstructor");this._clearTimers(),this.connecting||this.connected?this.logger.warn("Session already connected."):(this._removeSocketListeners(),this.destroySocket(),this._clearCheckPingTimer(),this._socket=this._createSocket(),this._addSocketListeners())}_createSocket(){return new this.WebSocketConstructor(this._host)}destroySocket(){this._socket&&(this._socket.close(),this.wsCloseHandler(new this.CloseEventConstructor("close",{reason:"Client-side closed"})),this._socket=null)}_addSocketListeners(){if(!this._socket)return this.logger.debug("Invalid socket instance to add listeners");this._removeSocketListeners(),this._socket.addEventListener("open",this.wsOpenHandler),this._socket.addEventListener("close",this.wsCloseHandler),this._socket.addEventListener("error",this.wsErrorHandler),this._socket.addEventListener("message",this._onSocketMessage)}_removeSocketListeners(){if(!this._socket)return this.logger.debug("Invalid socket instance to remove listeners");this._socket.removeEventListener("open",this.wsOpenHandler),this._socket.removeEventListener("close",this.wsCloseHandler),this._socket.removeEventListener("error",this.wsErrorHandler),this._socket.removeEventListener("message",this._onSocketMessage)}disconnect(){this._socket&&!this.closing?(this._status="disconnecting",this._checkCurrentStatus()):this.logger.debug("Session not connected or already in closing state.")}execute(e){if("disconnecting"===this._status)return this.logger.warn("Reject request because the session is disconnecting",e),Promise.reject({code:"400",message:"The SDK session is disconnecting"});if("disconnected"===this._status)return Promise.reject({code:"400",message:"The SDK is disconnected"});let t=Promise.resolve();return"params"in e&&(t=new Promise(((t,r)=>{this._requests.set(e.id,{rpcRequest:e,resolve:t,reject:r})}))),this.ready?(this._send(e),fr(t,this._executeTimeoutMs,this._executeTimeoutError).catch((t=>{if(t===this._executeConnectionClosed)throw this._executeConnectionClosed;if(t!==this._executeTimeoutError)throw t;if(Sr(e))throw this._swConnectError;if(this._checkCurrentStatus(),this.logger.error("Request Timeout",e),"disconnected"===this.status)return this.logger.debug("Request failed because the session is disconnected",this.status,this._socket);this._closeConnection("reconnecting")}))):(this._addToExecuteQueue(e),this.connect(),t)}get _connectParams(){return{agent:this.agent,version:this.connectVersion,authentication:{project:this.options.project,token:this.options.token}}}async authenticate(){var e,t;const r=this._connectParams;this._relayProtocolIsValid()&&(r.protocol=this.relayProtocol),(null==(e=this.options.topics)?void 0:e.length)?r.contexts=this.options.topics:(null==(t=this.options.contexts)?void 0:t.length)&&(r.contexts=this.options.contexts),this._rpcConnectResult=await this.execute(Pr(r))}authError(e){this._removeSocketListeners(),this.dispatch(Qr({error:e}))}forceClose(){return this._removeSocketListeners(),this._closeConnection("reconnecting")}async _onSocketOpen(e){var t;this.logger.debug("_onSocketOpen",e.type);try{this._status="unknown",this._clearTimers(),await this.authenticate(),this._status="connected",null==(t=this._resolveWaitConnected)||t.call(this),this._flushExecuteQueue(),this.dispatch(Xr())}catch(e){if(e===this._swConnectError||e===this._executeConnectionClosed)return void this.logger.debug("Invalid connect or connection closed. Waiting for retry.");this.logger.error("Auth Error",e),this.authError(e)}}_onSocketError(e){this.logger.debug("_onSocketError",e)}_onSocketClose(e){this.logger.debug("_onSocketClose",e.type,e.code,e.reason),"disconnected"!==this._status&&(this._status="reconnecting",this.dispatch(ti()),this._clearTimers(),this._clearPendingRequests(),this._reconnectTimer=setTimeout((()=>{this.connect()}),1e3*Math.floor(4*Math.random()+1))),this._socket=null}_clearTimers(){clearTimeout(this._reconnectTimer)}_clearPendingRequests(){this.logger.debug("_clearPendingRequests",this._requests.size),this._requests.forEach((({reject:e})=>{e(this._executeConnectionClosed)})),this._requests.clear()}_onSocketMessage(e){const t=this.decode(e.data);if(this.logger.wsTraffic({type:"recv",payload:t}),(e=>!wr(e))(t)){const e=this._requests.get(t.id);if(e){const{rpcRequest:r,resolve:i,reject:o}=e;this._requests.delete(t.id);const{result:n,error:s}=(({response:e,request:t})=>{const{result:r={},error:i}=e;return i?{error:i}:"signalwire.connect"===t.method?{result:r}:nr(e)})({response:t,request:r});return this._checkCurrentStatus(),s?o(s):i(n)}return this.logger.warn("Unknown request for",t)}switch(t.method){case"signalwire.ping":return this._pingHandler(t);case"signalwire.disconnect":this.execute((r=t.id,Ir({id:r,result:{}}))).catch((e=>{this.logger.error("SwDisconnect Error",e)})).finally((()=>{this._status="idle"}));break;default:this._eventAcknowledgingHandler(t).catch((e=>this.logger.error("Event Acknowledging Error",e))),this.dispatch(Zr(t))}var r}dispatch(e){if(!this._sessionChannel)throw new Error("Session channel does not exist");this._sessionChannel.put(e)}_relayProtocolIsValid(){var e;return this.signature&&(null==(e=null==this?void 0:this.relayProtocol)?void 0:e.split("_")[1])===this.signature}encode(e){return JSON.stringify(e)}decode(e){return(e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}})(e)}async onSwAuthorizationState(e){this.persistSwAuthorizationState(e)}async retrieveSwAuthorizationState(){return""}async persistSwAuthorizationState(e){}_send(e){this.logger.wsTraffic({type:"send",payload:e}),this._socket.send(this.encode(e))}_addToExecuteQueue(e){this.logger.warn("Request queued waiting for session to reconnect",e),this._executeQueue.add(e)}_flushExecuteQueue(){if(this._executeQueue.size){if(!this.ready)return this.logger.warn("Session not ready to flush the queue."),void this._closeConnection("reconnecting");this.logger.debug(`${this._executeQueue.size} messages to flush`),this._executeQueue.forEach((e=>{this._send(e),this._executeQueue.delete(e)})),this._executeQueue.clear()}}_clearCheckPingTimer(){clearTimeout(this._checkPingTimer)}async _pingHandler(e){var t,r,i;this._clearCheckPingTimer(),this._checkPingTimer=setTimeout((()=>{this.logger.debug("Timeout waiting for ping"),this._closeConnection("reconnecting")}),this._checkPingDelay),await this.execute((r=e.id,i=null==(t=null==e?void 0:e.params)?void 0:t.timestamp,Ir({id:r,result:{timestamp:i||Date.now()/1e3}})))}async _eventAcknowledgingHandler(e){const{method:t,id:r}=e;return"signalwire.event"===t?this.execute((e=>Ir({id:e,result:{}}))(r)):Promise.resolve()}_checkCurrentStatus(){switch(this._status){case"disconnecting":if(this._requests.size>0)return;this._requests.clear(),this._closeConnection("disconnected");break;case"disconnected":this.dispatch(ei());break;case"reconnecting":this.wsCloseHandler(new this.CloseEventConstructor("close",{reason:"Client-side closed"}))}}_closeConnection(e){this._clearCheckPingTimer(),this.logger.debug("Close Connection:",e),this._status=e,this.dispatch(li.authStatus("disconnected"===e?"unauthorized":"unknown")),this._removeSocketListeners(),this.destroySocket(),this._checkCurrentStatus()}},pi=class extends mi{constructor(e){super(e),this.options=e,Nt(this,"_expiredDiffSeconds",0),Nt(this,"_refreshTokenNotificationDiff",120),Nt(this,"_checkTokenExpirationDelay",2e4),Nt(this,"_checkTokenExpirationTimer",null),this._checkTokenExpiration=this._checkTokenExpiration.bind(this),this.reauthenticate=this.reauthenticate.bind(this)}get expiresAt(){var e;if(!(null==this?void 0:this._rpcConnectResult))return 0;const{authorization:t}=this._rpcConnectResult,r=null!=(e=kr(t)?t.fabric_subscriber.expires_at:null==t?void 0:t.expires_at)?e:0;if("string"==typeof r){const e=Date.parse(r);if(!isNaN(e))return Math.floor(e/1e3)}return r}get expiresIn(){const e=Math.floor(Date.now()/1e3);return this.expiresAt-e}get expired(){return this.expiresAt>0&&this.expiresIn<=this._expiredDiffSeconds}async authenticate(){const e=jt(Ot({},this._connectParams),{authentication:{jwt_token:this.options.token}});if(this._relayProtocolIsValid())e.protocol=this.relayProtocol;else{const t=await this.retrieveRelayProtocol();t&&(e.protocol=t)}if(e.protocol){const t=await this.retrieveSwAuthorizationState();t&&(e.authorization_state=t)}try{this._rpcConnectResult=await this.execute(Pr(e)),await this.persistRelayProtocol(),await this._checkTokenExpiration()}catch(e){if(this.logger.debug("BaseJWTSession authenticate error",e),"Requester validation failed"===e.message)return this.removeRelayProtocol(),this.removeSwAuthorizationState(),this.removePrevCallId(),void await this.authenticate();throw e}}async retrieveRelayProtocol(){return""}async persistRelayProtocol(){}removeRelayProtocol(){}removeSwAuthorizationState(){}removePrevCallId(){}async reauthenticate(){if(this.logger.debug("Session Reauthenticate",{ready:this.ready,expired:this.expired}),!this.ready||this.expired)return this.connect();const e={project:this._rpcConnectResult.authorization.project_id,jwt_token:this.options.token};try{this._rpcConnectResult=await this.execute(Mr(e))}catch(e){throw clearTimeout(this._checkTokenExpirationTimer),e}}_onSocketClose(e){clearTimeout(this._checkTokenExpirationTimer),super._onSocketClose(e)}async _checkTokenExpiration(){if(!this.expiresAt)return;const e=this.options.onRefreshToken;if(this.expiresIn<=this._refreshTokenNotificationDiff)if(this.dispatch(Yr()),"function"==typeof e)try{const t=await e();this.dispatch(Jr({token:t}))}catch(e){this.logger.error(e)}else this.logger.warn("The token is going to expire!");clearTimeout(this._checkTokenExpirationTimer),this.expired||(this._checkTokenExpirationTimer=setTimeout(this._checkTokenExpiration,this._checkTokenExpirationDelay))}},gi={};Dt(gi,{authErrorAction:()=>Qr,authExpiringAction:()=>Yr,authSuccessAction:()=>Xr,configureStore:()=>zi,connect:()=>$i,createAction:()=>Br,createCatchableSaga:()=>Si,createRestartableSaga:()=>wi,destroyAction:()=>Gr,eventChannel:()=>rt,getCustomSagaActionType:()=>ni,initAction:()=>Kr,makeCustomSagaAction:()=>oi,reauthAction:()=>Jr,sessionDisconnectedAction:()=>ei,sessionForceCloseAction:()=>ri,sessionReconnectingAction:()=>ti,socketMessageAction:()=>Zr});var fi=ai({name:"components",initialState:{byId:{}},reducers:{upsert:(e,{payload:t})=>jt(Ot({},e),t.id in e.byId?{byId:jt(Ot({},e.byId),{[t.id]:Ot(Ot({},e.byId[t.id]),t)})}:{byId:jt(Ot({},e.byId),{[t.id]:t})}),cleanup:(e,{payload:t})=>jt(Ot({},e),{byId:Object.entries(e.byId).reduce(((e,[r,i])=>(t.ids.includes(r)||(e[r]=i),e)),{})})}}),{actions:vi,reducer:yi}=fi,bi=(0,zr.combineReducers)({components:yi,session:ui}),_i={};Dt(_i,{createCatchableSaga:()=>Si,createRestartableSaga:()=>wi,eventChannel:()=>rt});var wi=e=>function*(){!function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return o=De.apply(void 0,[e].concat(r)),Ae(Ee,G({},o.payload,{detached:!0}));var o}((function*(){for(;;)try{Zt().debug("Run a restartable saga"),yield Le(e),Zt().debug("One of the restartable saga has ended. Restarting..")}catch(e){Zt().error("Restartable Saga Error",e)}}))},ki=e=>Zt().error("Catchable Saga Error",e),Si=(e,t=ki)=>function*(...r){try{yield Le(e,...r)}catch(e){t(e)}};function*Ci({sessionChannel:e,swEventChannel:t,session:r}){function*i(e){if(yield Oe(t,(e=>{const{event_type:t,params:r,node_id:i}=e;if("queuing.relay.tasks"===t)return{type:t,payload:e};if(ir(t)&&(null==r?void 0:r.jsonrpc)){const e=r;return e.params&&(e.params.nodeId=i),{type:t,payload:e}}return{type:t,payload:r}})(e)),!(e=>ir(null==e?void 0:e.event_type))(e)&&!(e=>{var t;return!!(null==(t=null==e?void 0:e.event_type)?void 0:t.startsWith("video."))})(e))return(e=>"signalwire.authorization.state"===(null==e?void 0:e.event_type))(e)?(r.onSwAuthorizationState(e.params.authorization_state),void(yield Oe(li.updateAuthorizationState(e.params.authorization_state)))):void(yield Oe({type:e.event_type,payload:e}))}Zt().debug("sessionChannelWatcher [started]");const o=Si((function*(e){if(e.type!==Zr.type)return void(yield Oe(e));const{method:t,params:r}=e.payload;if("signalwire.event"!==t)return Zt().debug(`Unknown message: ${t}`,e);yield De(i,r)}),(e=>{Zt().error("Channel Error",e)}));for(;;)try{for(;;){const t=yield xe(e);yield De(o,t)}}catch(e){Zt().error("sessionChannelWorker error:",e)}finally{Zt().debug("sessionChannelWorker [finally]")}}var Ii=class e extends Error{constructor(t,r){super(r),this.code=t,this.message=r,Nt(this,"name","AuthError"),Object.setPrototypeOf(this,e.prototype)}},Ti=class e extends Error{constructor(t,r,i){super(r),this.code=t,this.message=r,this.response=i,Nt(this,"name","HttpError"),Object.setPrototypeOf(this,e.prototype)}},Ei=class extends Error{constructor(e){super(e),this.name="CapabilityError"}};function*Pi({initSession:e,sessionEmitter:t,userOptions:r,channels:i}){var o;Zt().debug("sessionSaga [started]");const n=e(),s=i.swEventChannel,a=i.sessionChannel;let c=[];if(null==(o=r.workers)?void 0:o.length)try{const e=r.workers.map((e=>Le(wi(e))));c=yield function(e){var t=Ae("ALL",e);return t.combinator=!0,t}(e)}catch(e){Zt().error("Error running custom workers",e)}const d=yield De(Ci,{session:n,sessionChannel:a,swEventChannel:s}),l=yield De(Ri,{session:n,sessionEmitter:t,sessionChannel:a,userOptions:r});n.connect(),yield xe(Gr.type),n.disconnect(),yield xe(ei.type),t.emit("session.disconnected"),l.cancel(),d.cancel(),c.forEach((e=>e.cancel())),s.close(),a.close(),Zt().debug("sessionSaga [ended]")}function*Mi({session:e,token:t,sessionEmitter:r}){try{e.reauthenticate&&(e.token=t,yield Le(e.reauthenticate),yield Oe(li.connected(e.rpcConnectResult)),r.emit("session.connected"))}catch(t){Zt().error("Reauthenticate Error",t),e.authError(t)}}function*Ri(e){Zt().debug("sessionStatusWatcher [started]");const{session:t,sessionEmitter:r}=e;try{for(;;){const i=yield xe([Xr.type,Qr.type,Yr.type,Jr.type,ti.type,ri.type]);switch(Zt().debug("sessionStatusWatcher",i.type,i.payload),i.type){case Xr.type:yield Oe(li.connected(t.rpcConnectResult)),r.emit("session.connected");break;case Qr.type:yield De(Ai,jt(Ot({},e),{action:i}));break;case Yr.type:r.emit("session.expiring");break;case Jr.type:yield De(Mi,{session:t,token:i.payload.token,sessionEmitter:r});break;case ti.type:r.emit("session.reconnecting");break;case ri.type:t.forceClose()}}}finally{(yield Ve())&&Zt().debug("sessionStatusWatcher [cancelled]")}}function*Ai(e){Zt().debug("sessionAuthErrorSaga [started]");try{const{action:t,sessionEmitter:r}=e,{error:i}=t.payload,o=i?new Ii(i.code,i.message):new Error("Unauthorized");r.emit("session.auth_error",o)}finally{(yield Ve())&&Zt().debug("sessionAuthErrorSaga [cancelled]")}}var xi={};Dt(xi,{getAuthError:()=>Di,getAuthStatus:()=>Li,getAuthorization:()=>Wi,getAuthorizationState:()=>Vi,getIceServers:()=>Oi,getProtocol:()=>Ni,getSession:()=>ji});var Oi=({session:e})=>{var t;return null!=(t=null==e?void 0:e.iceServers)?t:[]},ji=e=>e.session,Li=({session:e})=>e.authStatus,Di=({session:e})=>e.authError,Wi=({session:e})=>e.authorization,Vi=({session:e})=>e.authorizationState,Ni=({session:e})=>e.protocol,$i=e=>{const{sessionListeners:t={},store:r,Component:i,customSagas:o=[]}=e,n=Object.keys(t);return e=>{const s=new i(jt(Ot({},e),{store:r})),a=/* @__PURE__ */new Map;let c=!0;const d=r.subscribe((()=>{const e=r.getState(),i=ji(e);for(const e of n){if(!1===c)return;const r=`session.${e}`,o=a.get(r),n=i[e];if(void 0!==n&&o!==n){a.set(r,n);const o=t[e];"string"==typeof o?s[o](i):"function"==typeof o&&o(i)}}})),l=null==o?void 0:o.map((e=>r.runSaga(e,{instance:s,runSaga:r.runSaga})));return s.destroyer=()=>{c=!1,d(),a.clear(),(null==l?void 0:l.length)&&l.forEach((e=>e.cancel()))},s}},Ui=()=>new St;Vt(gi,zr);var zi=e=>{var t;const{userOptions:r,SessionConstructor:i,preloadedState:o={},runRootSaga:n=!0}=e,s=function(e){var t,r=void 0===e?{}:e,i=r.context,o=void 0===i?{}:i,n=r.channel,s=void 0===n?ot():n,a=r.sagaMonitor,c=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(r,["context","channel","sagaMonitor"]);function d(e){return t=wt.bind(null,G({},c,{context:o,channel:s,dispatch:e.dispatch,getState:e.getState,sagaMonitor:a})),function(e){return function(t){a&&a.actionDispatched&&a.actionDispatched(t);var r=e(t);return s.put(t),r}}}return d.run=function(){return t.apply(void 0,arguments)},d.setContext=function(e){ce(o,e)},d}({sagaMonitor:r.sagaMonitor}),a=it(),c=tt(),d={swEventChannel:a,sessionChannel:c},l=qr({devTools:null==(t=null==r?void 0:r.devTools)||t,reducer:bi,preloadedState:o,middleware:e=>e().concat(s)}),u=(()=>{const e=/* @__PURE__ */new Map;return{get:t=>e.get(t),set:(t,r)=>(e.set(t,r),e),remove:t=>(e.delete(t),e),getAll:()=>Array.from(e.entries()),deleteAll:()=>(e.clear(),e)}})(),{initSession:h,getSession:m,sessionEmitter:p}=(e=>{const{SessionConstructor:t,userOptions:r,sessionChannel:i}=e,o=Ui();let n=null;return{session:n,initSession:()=>(n=new t(jt(Ot({},r),{sessionChannel:i})),n),getSession:()=>(n||Zt().warn("Session does not exist!"),n),sessionEmitter:o}})({userOptions:r,sessionChannel:c,SessionConstructor:i});if(n){const e=(e=>function*({userOptions:t,channels:r}){for(Zt().debug("rootSaga [started]"),t.logger&&(Gt=t.logger),t.debug&&(e=>{null!=e?Object.assign(Qt,e):Qt={}})(t.debug);;){yield xe(Kr.type);try{yield Le(Pi,jt(Ot({},e),{userOptions:t,channels:r}));break}catch(e){Zt().error("RootSaga Error:",e)}finally{(yield Ve())&&Zt().debug("rootSaga [cancelled]"),Zt().debug("Reboot rootSaga")}}Zt().debug("rootSaga [finished]")})({initSession:h,sessionEmitter:p});s.run(e,{userOptions:r,channels:d})}return jt(Ot({},l),{runSaga:(e,t)=>s.run(e,jt(Ot({},t),{channels:d,getSession:m,instanceMap:u})),channels:d,instanceMap:u,sessionEmitter:p})},Bi=function*(e){const{initialState:t,onDone:r,onFail:i,getSession:o}=e,{requestId:n,method:s,params:a}=t,c=o();if(!c){const e=new Error("Session does not exist!");return Zt().error(e),void(null==i||i(e))}try{let e=(({method:e,params:t})=>Cr({method:e,params:t}))({id:n,method:s,params:a});const t=yield Le(c.execute,e);null==r||r(t)}catch(e){Zt().warn("Execute error: ",e),null==i||i(e)}},Fi=e=>e,Hi=Symbol("BaseComponent"),qi=class{constructor(e){this.options=e,Nt(this,"__sw_symbol",Hi),Nt(this,"uuid",b()),Nt(this,"_customSagaTriggers",/* @__PURE__ */new Map),Nt(this,"_destroyer"),Nt(this,"eventEmitter"),Nt(this,"_runningWorkers",[]),Nt(this,"_workers",/* @__PURE__ */new Map),this.eventEmitter=new St}get __uuid(){return this.uuid}get logger(){return Zt()}set destroyer(e){this._destroyer=e}get store(){return this.options.store}get instanceMap(){return this.store.instanceMap}get emitter(){return this.eventEmitter}get sessionEmitter(){return this.store.sessionEmitter}get session(){return this.sessionEmitter}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){return this.emitter.off(e,t)}removeAllListeners(e){return e?this.off(e):(this.eventNames().forEach((e=>{this.off(e)})),this.emitter)}eventNames(){return this.emitter.eventNames()}sessionEventNames(){return this.sessionEmitter.eventNames()}getSubscriptions(){return br(this.eventNames())}emit(e,...t){return this.emitter.emit(e,...t)}listenerCount(e){return this.emitter.listenerCount(e)}destroy(){var e;null==(e=this._destroyer)||e.call(this),this.removeAllListeners(),this.detachWorkers()}execute({method:e,params:t},{transformParams:r=Fi,transformResolve:i=Fi,transformReject:o=Fi}={transformParams:Fi,transformResolve:Fi,transformReject:Fi}){return new Promise(((n,s)=>{const a=b();this.runWorker("executeActionWorker",{worker:Bi,onDone:e=>n(i(e)),onFail:e=>s(o(e)),initialState:{requestId:a,componentId:this.__uuid,method:e,params:r(t)}})}))}triggerCustomSaga(e){return new Promise(((t,r)=>{const i=b();this._customSagaTriggers.set(i,{resolve:t,reject:r}),this.store.dispatch(Ot({dispatchId:i},oi(this.__uuid,e)))}))}settleCustomSagaTrigger({dispatchId:e,payload:t,kind:r}){const i=this._customSagaTriggers.get(e);i&&(i[r](t),this._customSagaTriggers.delete(e))}select(e){return e(this.store.getState())}getStateProperty(e){return this[e]}get _sessionAuthStatus(){return this.select(Li)}get _sessionAuthorization(){return this.select(Wi)}_waitUntilSessionAuthorized(){switch(this._sessionAuthStatus){case"authorized":return Promise.resolve(this);case"unknown":case"authorizing":return new Promise(((e,t)=>{const r=this.store.subscribe((()=>{const i=this.select(Li),o=this.select(Di);if("authorized"===i)e(this),r();else if("unauthorized"===i){const e=o?new Ii(o.code,o.message):new Error("Unauthorized");t(e),r()}}))}));case"unauthorized":return Promise.reject(new Error("Unauthorized"))}}runWorker(e,t){return this._workers.has(e)?Zt().warn(`[runWorker] Worker with name ${e} has already been registerd.`):this._setWorker(e,t),this._attachWorker(e,t)}cancelWorker(e){const t=this._runningWorkers.findIndex((t=>t===e));t>-1&&(this._runningWorkers.splice(t,1),e.cancel())}_setWorker(e,t){this._workers.set(e,t)}_attachWorker(e,t){var r=t,{worker:i}=r,o=Lt(r,["worker"]);const n=this.store.runSaga(i,Ot({instance:this,runSaga:this.store.runSaga},o));return this._runningWorkers.push(n),this._workers.delete(e),n}detachWorkers(){this._runningWorkers.forEach((e=>{e.cancel()})),this._runningWorkers=[]}},Ki=class extends qi{constructor(e){super(e),this.options=e}connect(){const e=Li(this.store.getState());return"unknown"!==e&&"unauthorized"!==e||this.store.dispatch(Kr()),this._waitUntilSessionAuthorized()}disconnect(){this.store.dispatch(Gr())}removeAllListeners(e){return this.sessionEventNames().forEach((e=>{this.sessionEmitter.off(e)})),super.removeAllListeners(e)}},Gi=class extends qi{constructor(e){super(e),this.options=e,Nt(this,"subscribeMethod","signalwire.subscribe"),Nt(this,"subscribeParams",{}),Nt(this,"_latestExecuteParams");const t=()=>{this._latestExecuteParams=void 0};super.session.on("session.connected",t),super.session.on("session.disconnected",t),super.session.on("session.reconnecting",t)}shouldExecuteSubscribe(e){return!this._latestExecuteParams||JSON.stringify(e)!==JSON.stringify(this._latestExecuteParams)}async subscribe(){await this._waitUntilSessionAuthorized();const e=this.getSubscriptions();if(0===e.length)return void this.logger.debug("`subscribe()` was called without any listeners attached.");const t={method:this.subscribeMethod,params:jt(Ot({},this.subscribeParams),{event_channel:this.getStateProperty("eventChannel"),events:e})};if(this.shouldExecuteSubscribe(t))return this._latestExecuteParams=t,new Promise((async(e,r)=>{try{return await this.execute(t),e(void 0)}catch(e){return r(e)}}));this.logger.debug("BaseConsumer.subscribe() - Skipped .execute() since the execParams are exactly the same as last time")}},Ji={audio_muted:!0,video_muted:!0,deaf:!0,visible:!0,input_volume:1,output_volume:1,input_sensitivity:1};Object.keys(Ji).map((e=>`video.member.updated.${e}`));var Qi=ar(Ji);Object.keys(Qi).map((e=>`member.updated.${e}`));var Xi={};Dt(Xi,{getComponent:()=>Yi,getComponentsById:()=>Zi,getComponentsToCleanup:()=>eo});var Yi=({components:e},t)=>{var r;return null==(r=e.byId)?void 0:r[t]},Zi=({components:e})=>e.byId,eo=e=>{const t=Zi(e);let r=[];return Object.keys(t).forEach((e=>{(t[e].responses||t[e].errors)&&r.push(e)})),r},to={audio_muted:!0,video_muted:!0,deaf:!0,visible:!0,input_volume:1,output_volume:1,input_sensitivity:1,handraised:!0,echo_cancellation:!0,auto_gain:!0,noise_suppression:!0};Object.keys(to).map((e=>`member.updated.${e}`));var ro=ar(to);Object.keys(ro).map((e=>`member.updated.${e}`));var io={};Dt(io,{RoomSessionPlaybackAPI:()=>Xo,RoomSessionRecordingAPI:()=>Jo,RoomSessionStreamAPI:()=>Zo,audioMuteMember:()=>Mo,audioUnmuteMember:()=>Ro,createRoomSessionPlaybackObject:()=>Yo,createRoomSessionRecordingObject:()=>Qo,createRoomSessionStreamObject:()=>en,deafMember:()=>Oo,deleteMemberMeta:()=>Ko,deleteMeta:()=>Io,demote:()=>$o,getLayouts:()=>ao,getMemberMeta:()=>Fo,getMembers:()=>co,getMeta:()=>ko,getPlaybacks:()=>bo,getRecordings:()=>vo,getStreams:()=>To,hideVideoMuted:()=>ho,lock:()=>po,play:()=>_o,promote:()=>No,removeAllMembers:()=>Bo,removeMember:()=>zo,setDeaf:()=>Lo,setHideVideoMuted:()=>fo,setInputSensitivityMember:()=>Vo,setInputVolumeMember:()=>Do,setLayout:()=>lo,setMemberMeta:()=>Ho,setMemberPosition:()=>Uo,setMeta:()=>So,setOutputVolumeMember:()=>Wo,setPositions:()=>uo,setPrioritizeHandraise:()=>Po,setRaisedHand:()=>Go,showVideoMuted:()=>mo,startRecording:()=>yo,startStream:()=>Eo,undeafMember:()=>jo,unlock:()=>go,updateMemberMeta:()=>qo,updateMeta:()=>Co,videoMuteMember:()=>Ao,videoUnmuteMember:()=>xo});var oo=()=>{},no=(e,t={})=>({value:function(r={}){return this.execute({method:e,params:Ot({room_session_id:this.roomSessionId},r)},t)}}),so=(e,t={})=>({value:function(r={}){var i=r,{memberId:o}=i,n=Lt(i,["memberId"]);return this.execute({method:e,params:Ot({room_session_id:this.roomSessionId,member_id:o||this.memberId},n)},t)}}),ao=no("video.list_available_layouts",{transformResolve:e=>({layouts:e.layouts})}),co=no("video.members.get",{transformResolve:e=>({members:e.members})}),lo=no("video.set_layout",{transformResolve:oo}),uo=no("video.set_position",{transformResolve:oo}),ho=no("video.hide_video_muted",{transformResolve:oo}),mo=no("video.show_video_muted",{transformResolve:oo}),po=no("video.lock",{transformResolve:oo}),go=no("video.unlock",{transformResolve:oo}),fo={value:function(e){return this.execute({method:e?"video.hide_video_muted":"video.show_video_muted",params:{room_session_id:this.roomSessionId}},{transformResolve:oo})}},vo={value:function(){return new Promise((async(e,t)=>{try{const{recordings:t}=await this.execute({method:"video.recording.list",params:{room_session_id:this.roomSessionId}}),r=[];t.forEach((e=>{let t=this.instanceMap.get(e.id);t?t.setPayload({room_id:this.roomId,room_session_id:this.roomSessionId,recording:e}):t=Qo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,recording:e}}),r.push(t),this.instanceMap.set(t.id,t)})),e({recordings:r})}catch(e){t(e)}}))}},yo={value:function(){return new Promise((async(e,t)=>{try{const{recording:t}=await this.execute({method:"video.recording.start",params:{room_session_id:this.roomSessionId}}),r=Qo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,recording:t}});this.instanceMap.set(r.id,r),e(r)}catch(e){t(e)}}))}},bo={value:function(){return new Promise((async(e,t)=>{try{const{playbacks:t}=await this.execute({method:"video.playback.list",params:{room_session_id:this.roomSessionId}}),r=[];t.forEach((e=>{let t=this.instanceMap.get(e.id);t?t.setPayload({room_id:this.roomId,room_session_id:this.roomSessionId,playback:e}):t=Yo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,playback:e}}),r.push(t),this.instanceMap.set(t.id,t)})),e({playbacks:r})}catch(e){t(e)}}))}},_o={value:function(e){var t=e,{seekPosition:r,currentTimecode:i}=t,o=Lt(t,["seekPosition","currentTimecode"]);return new Promise((async(e,t)=>{try{const t=r||i,{playback:n}=await this.execute({method:"video.playback.start",params:Ot({room_session_id:this.roomSessionId,seek_position:t},o)}),s=Yo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,playback:n}});this.instanceMap.set(s.id,s),e(s)}catch(e){t(e)}}))}},wo=e=>no(e,{transformResolve:oo,transformParams:e=>{const t=e,{room_session_id:r}=t;return{room_session_id:r,meta:Lt(t,["room_session_id"])}}}),ko=no("video.get_meta",{transformResolve:({meta:e})=>({meta:e})}),So=wo("video.set_meta"),Co=wo("video.update_meta"),Io={value:function(e){return this.execute({method:"video.delete_meta",params:{room_session_id:this.roomSessionId,keys:e}})}},To={value:function(){return new Promise((async(e,t)=>{try{const{streams:t}=await this.execute({method:"video.stream.list",params:{room_session_id:this.roomSessionId}}),r=[];t.forEach((e=>{let t=this.instanceMap.get(e.id);t?t.setPayload({room_id:this.roomId,room_session_id:this.roomSessionId,stream:e}):t=en({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,stream:e}}),r.push(t),this.instanceMap.set(t.id,t)})),e({streams:r})}catch(e){t(e)}}))}},Eo={value:function(e){return new Promise((async(t,r)=>{try{const{stream:r}=await this.execute({method:"video.stream.start",params:Ot({room_session_id:this.roomSessionId},e)}),i=en({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,stream:r}});this.instanceMap.set(i.id,i),t({stream:i})}catch(e){r(e)}}))}},Po={value:function(e){return this.execute({method:"video.prioritize_handraise",params:{room_session_id:this.roomSessionId,enable:e}})}},Mo=so("video.member.audio_mute",{transformResolve:oo}),Ro=so("video.member.audio_unmute",{transformResolve:oo}),Ao=so("video.member.video_mute",{transformResolve:oo}),xo=so("video.member.video_unmute",{transformResolve:oo}),Oo=so("video.member.deaf",{transformResolve:oo}),jo=so("video.member.undeaf",{transformResolve:oo}),Lo={value:function(e){return this.execute({method:e?"video.member.deaf":"video.member.undeaf",params:{room_session_id:this.roomSessionId,member_id:this.memberId}},{transformResolve:oo})}},Do=so("video.member.set_input_volume",{transformResolve:oo}),Wo=so("video.member.set_output_volume",{transformResolve:oo}),Vo=so("video.member.set_input_sensitivity",{transformResolve:oo}),No={value:function(e){var t=e,{memberId:r,mediaAllowed:i,joinAudioMuted:o,joinVideoMuted:n}=t,s=Lt(t,["memberId","mediaAllowed","joinAudioMuted","joinVideoMuted"]);return this.execute({method:"video.member.promote",params:Ot({room_session_id:this.roomSessionId,member_id:r,media_allowed:i,join_audio_muted:o,join_video_muted:n},s)},{transformResolve:oo})}},$o={value:function({memberId:e,mediaAllowed:t}){return this.execute({method:"video.member.demote",params:{room_session_id:this.roomSessionId,member_id:e,media_allowed:t}},{transformResolve:oo})}},Uo=so("video.member.set_position",{transformResolve:oo}),zo={value:function(e){var t=e,{memberId:r}=t,i=Lt(t,["memberId"]);if(!r)throw new TypeError('Invalid or missing "memberId" argument');return this.execute({method:"video.member.remove",params:Ot({room_session_id:this.roomSessionId,member_id:r},i)},{transformResolve:oo})}},Bo={value:function(){return this.execute({method:"video.member.remove",params:{room_session_id:this.roomSessionId,member_id:"all"}},{transformResolve:oo})}},Fo=so("video.member.get_meta",{transformResolve:({meta:e})=>({meta:e})}),Ho=so("video.member.set_meta",{transformResolve:oo}),qo=so("video.member.update_meta",{transformResolve:oo}),Ko=so("video.member.delete_meta",{transformResolve:oo}),Go={value:function(e){const{raised:t=!0,memberId:r=this.memberId}=e||{};if(!r)throw new TypeError('Invalid or missing "memberId" argument');return this.execute({method:t?"video.member.raisehand":"video.member.lowerhand",params:{room_session_id:this.roomSessionId,member_id:r}},{transformResolve:oo})}},Jo=class extends qi{constructor(e){super(e),Nt(this,"_payload"),this._payload=e.payload}get id(){return this._payload.recording.id}get roomId(){return this._payload.room_id}get roomSessionId(){return this._payload.room_session_id}get state(){return this._payload.recording.state}get duration(){return this._payload.recording.duration}get startedAt(){if(this._payload.recording.started_at)return new Date(1e3*this._payload.recording.started_at)}get endedAt(){if(this._payload.recording.ended_at)return new Date(1e3*this._payload.recording.ended_at)}setPayload(e){this._payload=e}async pause(){await this.execute({method:"video.recording.pause",params:{room_session_id:this.getStateProperty("roomSessionId"),recording_id:this.getStateProperty("id")}})}async resume(){await this.execute({method:"video.recording.resume",params:{room_session_id:this.getStateProperty("roomSessionId"),recording_id:this.getStateProperty("id")}})}async stop(){await this.execute({method:"video.recording.stop",params:{room_session_id:this.getStateProperty("roomSessionId"),recording_id:this.getStateProperty("id")}})}},Qo=e=>$i({store:e.store,Component:Jo})(e),Xo=class extends qi{constructor(e){super(e),Nt(this,"_payload"),this._payload=e.payload}get id(){return this._payload.playback.id}get roomId(){return this._payload.room_id}get roomSessionId(){return this._payload.room_session_id}get url(){return this._payload.playback.url}get state(){return this._payload.playback.state}get volume(){return this._payload.playback.volume}get startedAt(){if(this._payload.playback.started_at)return new Date(1e3*this._payload.playback.started_at)}get endedAt(){if(this._payload.playback.ended_at)return new Date(1e3*this._payload.playback.ended_at)}get position(){return this._payload.playback.position}get seekable(){return this._payload.playback.seekable}setPayload(e){this._payload=e}async pause(){await this.execute({method:"video.playback.pause",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id")}})}async resume(){await this.execute({method:"video.playback.resume",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id")}})}async stop(){await this.execute({method:"video.playback.stop",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id")}})}async setVolume(e){await this.execute({method:"video.playback.set_volume",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),volume:e}})}async seek(e){await this.execute({method:"video.playback.seek_absolute",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),position:Math.abs(e)}})}async forward(e=5e3){await this.execute({method:"video.playback.seek_relative",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),position:Math.abs(e)}})}async rewind(e=5e3){await this.execute({method:"video.playback.seek_relative",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),position:-Math.abs(e)}})}},Yo=e=>$i({store:e.store,Component:Xo})(e),Zo=class extends qi{constructor(e){super(e),Nt(this,"_payload"),this._payload=e.payload}get id(){return this._payload.stream.id}get roomId(){return this._payload.room_id}get roomSessionId(){return this._payload.room_session_id}get state(){return this._payload.stream.state}get duration(){return this._payload.stream.duration}get url(){return this._payload.stream.url}get startedAt(){if(this._payload.stream.started_at)return new Date(1e3*this._payload.stream.started_at)}get endedAt(){if(this._payload.stream.ended_at)return new Date(1e3*this._payload.stream.ended_at)}setPayload(e){this._payload=e}async stop(){await this.execute({method:"video.stream.stop",params:{room_session_id:this.getStateProperty("roomSessionId"),stream_id:this.getStateProperty("id")}})}},en=e=>$i({store:e.store,Component:Zo})(e),tn={};Dt(tn,{BaseChatAPI:()=>kn,BaseChatConsumer:()=>wn,ChatMember:()=>In,ChatMessage:()=>Cn,applyCommonMethods:()=>Pn,createBaseChatObject:()=>Sn,getMemberState:()=>mn,getMembers:()=>ln,getMessages:()=>dn,publish:()=>cn,setMemberState:()=>hn});var rn=e=>{const t=!e||Array.isArray(e)?e:[e];return Array.isArray(t)?t.map((e=>({name:e}))):[]},on=e=>Array.isArray(e)||"string"==typeof e,nn=()=>{},sn=(e,t={})=>({value:function(r={}){return this.execute({method:e,params:r},t)}}),an=(e,t={})=>({value:function(r={}){var i=r,{memberId:o}=i,n=Lt(i,["memberId"]);return this.execute({method:e,params:Ot({member_id:o},n)},t)}}),cn=sn("chat.publish",{transformResolve:nn}),dn=sn("chat.messages.get",{transformResolve:e=>({messages:e.messages.map((e=>ar(e))),cursor:e.cursor})}),ln=sn("chat.members.get",{transformResolve:e=>({members:e.members.map((e=>ar(e)))})}),un=e=>{const t=on(null==e?void 0:e.channels)?rn(e.channels):void 0;return jt(Ot({},e),{channels:t})},hn=an("chat.member.set_state",{transformResolve:nn,transformParams:un}),mn=an("chat.member.get_state",{transformResolve:e=>({channels:e.channels}),transformParams:un}),pn={};Dt(pn,{BasePubSubConsumer:()=>vn,PubSubMessage:()=>bn,createBasePubSubObject:()=>yn});var gn=function*(e){Zt().trace("pubSubWorker started");const{instance:t,channels:{swEventChannel:r}}=e;function*i(e){const{type:r,payload:i}=e;switch(r){case`${zt}.channel.message`:{const{channel:e,message:r}=i,o=Lt(r,["member"]),n=ar(jt(Ot({},o),{channel:e})),s=new bn(n);t.emit("message",s);break}default:Zt().warn(`Unknown pubsub event: "${r}"`)}}const o=e=>e.type.startsWith(`${zt}.`);for(;;){const e=yield xe(r,o);yield De(i,e)}Zt().trace("pubSubWorker ended")},fn=e=>e.map((e=>({name:e}))),vn=class extends Gi{constructor(e){super(e),Nt(this,"subscribeMethod",`${zt}.subscribe`),this.initWorker()}initWorker(){this.runWorker("pubSub",{worker:gn})}_getChannelsParam(e,t){const r=!e||Array.isArray(e)?e:[e];if(!Array.isArray(r)||0===r.length)throw new Error(`Please specify one or more channels when calling .${t}()`);return{channels:fn(r)}}_setSubscribeParams(e){this.subscribeParams=Ot(Ot({},this.subscribeParams),e)}_getSubscribeParams({channels:e}){return Ot({},this._getChannelsParam(e,"subscribe"))}_getUnsubscribeParams({channels:e}){const t=this._getChannelsParam(e,"unsubscribe");return Ot({},t)}_checkMissingSubscriptions(){0===this.getSubscriptions().length&&(this.logger.info("Subscribe was called before any listeners were attached. Move `.subscribe()` right after your event listeners to suppress this message."),this.once("message",(()=>{})))}getSubscriptions(){const e=this.eventNames().map((e=>`${zt}.${String(e)}`));return br(e)}async subscribe(e){this._checkMissingSubscriptions();const t=this._getSubscribeParams({channels:e});return this._setSubscribeParams(t),super.subscribe()}async unsubscribe(e){if("unknown"===this._sessionAuthStatus||"unauthorized"===this._sessionAuthStatus)throw new Error("You must be authenticated to unsubscribe from a channel");const t=this._getUnsubscribeParams({channels:e});return new Promise((async(e,r)=>{const i=this.getSubscriptions();if(i.length>0){const e={method:`${zt}.unsubscribe`,params:jt(Ot({},t),{events:i})};try{await this.execute(e)}catch(e){return r(e)}}else this.logger.warn("`unsubscribe()` was called without any listeners attached.");return e()}))}updateToken(e){return new Promise(((t,r)=>{this.session.once("session.auth_error",(e=>{r(e)})),this.session.once("session.connected",(()=>{t()})),this.store.dispatch(Ur.reauthAction({token:e}))}))}publish(e){return this.execute({method:`${zt}.publish`,params:e})}async getAllowedChannels(){await this._waitUntilSessionAuthorized();const e=this.select(Wi);return e&&"channels"in e&&e.channels?e.channels:{}}},yn=e=>$i({store:e.store,Component:vn})(e),bn=class{constructor(e){this.payload=e}get id(){return this.payload.id}get channel(){return this.payload.channel}get content(){return this.payload.content}get meta(){return this.payload.meta}get publishedAt(){return this.payload.publishedAt}},_n=function*(e){Zt().trace("chatWorker started");const{instance:t,channels:{swEventChannel:r}}=e;function*i(e){const{type:r,payload:i}=e;switch(r){case"chat.channel.message":{const{channel:e,message:r}=i,o=ar(jt(Ot({},r),{channel:e})),n=new Cn(o);t.emit("message",n);break}case"chat.member.joined":case"chat.member.updated":case"chat.member.left":{const{member:e}=i,o=ar(e),n=new In(o),s=ur(r);t.emit(s,n);break}default:Zt().warn(`Unknown chat event: "${r}"`)}}const o=e=>e.type.startsWith("chat.");for(;;){const e=yield xe(r,o);yield De(i,e)}Zt().trace("chatWorker ended")},wn=class extends vn{constructor(e){super(e),Nt(this,"subscribeMethod","chat.subscribe")}initWorker(){this.runWorker("chat",{worker:_n})}},kn=lr(wn,{publish:cn,getMembers:ln,getMessages:dn,setMemberState:hn,getMemberState:mn}),Sn=e=>$i({store:e.store,Component:kn})(e),Cn=class extends bn{get member(){return this.payload.member}},In=class{constructor(e){this.payload=e}get id(){return this.payload.id}get channel(){return this.payload.channel}get state(){var e;return null!=(e=this.payload.state)?e:{}}},Tn=e=>{const t=on(null==e?void 0:e.channels)?rn(e.channels):void 0;return jt(Ot({},e),{channels:t})},En=()=>{};function Pn(e){return class extends e{getMembers(e){return this._client.execute({method:"chat.members.get",params:e},{transformResolve:e=>({members:e.members.map((e=>ar(e)))})})}getMessages(e){return this._client.execute({method:"chat.messages.get",params:e},{transformResolve:e=>({messages:e.messages.map((e=>ar(e))),cursor:e.cursor})})}setMemberState(e={}){var t=e,{memberId:r}=t,i=Lt(t,["memberId"]);return this._client.execute({method:"chat.member.set_state",params:Ot({member_id:r},i)},{transformResolve:En,transformParams:Tn})}getMemberState(e={}){var t=e,{memberId:r}=t,i=Lt(t,["memberId"]);return this._client.execute({method:"chat.member.get_state",params:Ot({member_id:r},i)},{transformResolve:e=>({channels:e.channels}),transformParams:Tn})}}}var Mn={};Dt(Mn,{memberPositionWorker:()=>On,memberUpdatedWorker:()=>xn});var Rn=function*(e,t,r){const i=ur(e);r.emit(i,t)};function*An(e){const{action:t,memberList:r,instance:i,dispatcher:o=Rn}=e,n={};t.payload.layout.layers.forEach((e=>{var t;const i=e.member_id;if(!i)return;const o=r.get(i);o&&e.position!==(null==(t=o.member)?void 0:t.current_position)?(jn({memberList:r,memberId:i,currentPosition:e.position}),n[i]=!0):n[i]=!1}));for(const[e,t]of r)if(n[e])yield null==o?void 0:o("video.member.updated",t,i);else if(void 0===n[e]){const t=jn({memberList:r,memberId:e,currentPosition:"off-canvas"});if(!t)return;yield null==o?void 0:o("video.member.updated",t,i)}}function*xn({action:e,memberList:t,instance:r,dispatcher:i=Rn}){var o,n;const s=e.payload.member.id,a=jn({memberList:t,memberId:s,currentPosition:null==(n=null==(o=t.get(s))?void 0:o.member)?void 0:n.current_position});if(!a)return;const{member:{updated:c=[]}}=e.payload,d=jt(Ot({},a),{member:Ot(Ot({},a.member),e.payload.member)});t.set(s,d);for(const t of c){const o=`${e.type}.${t}`;yield null==i?void 0:i(o,d,r)}yield null==i?void 0:i(e.type,d,r)}var On=function*({instance:e,channels:t,initialState:r,getSession:i,instanceMap:o,dispatcher:n=Rn}){if(!r)return;const{swEventChannel:s}=t;let a=Ln(r);const c=e=>{a.has(e.member.id)||a.set(e.member.id,e)};for(;;){const r=yield xe(s,(e=>"video.member.joined"===e.type||"video.member.updated"===e.type||"video.member.left"===e.type||"video.layout.changed"===e.type));switch(r.type){case"video.member.joined":c(r.payload);break;case"video.member.updated":c(r.payload),yield De(xn,{action:r,channels:t,memberList:a,instance:e,getSession:i,instanceMap:o,dispatcher:n});break;case"video.member.left":a.delete(r.payload.member.id);break;case"video.layout.changed":yield De(An,{action:r,channels:t,memberList:a,instance:e,dispatcher:n})}}},jn=({memberList:e,memberId:t,currentPosition:r})=>{const i=e.get(t);if(!i)return;if(!r)return i;const o=jt(Ot({},i),{member:jt(Ot({},null==i?void 0:i.member),{current_position:r})});return e.set(t,o),o},Ln=e=>{const t=e.room_session.members,r=/* @__PURE__ */new Map;return t.forEach((t=>{r.set(t.id,{room_id:e.room_session.room_id,room_session_id:e.room_session.id||e.room_session.room_session_id,member:t})})),r};Dt({},{configureFullStack:()=>$n,configureJestStore:()=>Nn,createMockedLogger:()=>Vn,createSessionChannel:()=>Fn,createSwEventChannel:()=>Bn,rpcConnectResultVRT:()=>zn,wait:()=>Un});var Dn="8f0a119a-cda7-4497-a47d-c81493b824d4",Wn="<VRT>",Vn=()=>({fatal:jest.fn(),error:jest.fn(),warn:jest.fn(),info:jest.fn(),debug:jest.fn(),trace:jest.fn(),wsTraffic:jest.fn()}),Nn=e=>zi(Ot({userOptions:{project:Dn,token:Wn,devTools:!1},SessionConstructor:mi,runRootSaga:!1},e)),$n=()=>{const e={dispatch:console.log,connect:jest.fn(),disconnect:jest.fn(),execute:jest.fn()},t=new St,r=zi({userOptions:{project:Dn,token:Wn,devTools:!1},SessionConstructor:jest.fn().mockImplementation((()=>e))});return r.dispatch(Ur.initAction()),r.dispatch(Ur.authSuccessAction()),{store:r,session:e,emitter:t,destroy:()=>r.dispatch(Ur.destroyAction())}},Un=e=>new Promise((t=>{setTimeout(t,e)})),zn={identity:"f3bc99df-2c3d-4fa4-b1dc-e8a8ffc579e6@e3fefa44-1bad-4be9-ad9b-1cbb9abd60c7.west-us",authorization:{type:"video",project_id:"8f0a119a-cda7-4497-a47d-c81493b824d4",project:"8f0a119a-cda7-4497-a47d-c81493b824d4",scopes:["video"],scope_id:"26675883-8499-4ee9-85eb-691c4aa209f8",resource:"9c80f1e8-9430-4070-a043-937eb3a96b38",join_as:"member",user_name:"Joe",room:{name:"lobby",display_name:"Lobby",scopes:["room.self.audio_mute","room.self.audio_unmute"],meta:{}},signature:"SGZtkRD9fvuBAOUp1UF56zESxdEvGT6qSGZtkRD9fvuBAOUp1UF56zESxdEvGT6q",media_allowed:"all",audio_allowed:"both",video_allowed:"both",meta:{}},protocol:"signalwire_SGZtkRD9fvuBAOUp1UF56zESxdEvGT6qSGZtkRD9fvuBAOUp1UF56zESxdEvGT6q_03e8c927-8ea3-4661-86d5-778c3e03296a_8f0a119a-cda7-4497-a47d-c81493b824d4",ice_servers:[{urls:"turn.swire.io:443",credential:"sFTwvi8ShXcYNOcyYjFy3ATIUpQ=",credentialType:"password",username:"1619521908:8f0a119a-cda7-4497-a47d-c81493b824d4"}]},Bn=()=>it(),Fn=()=>tt(),Hn=Ot({},xi);const qn=e=>new window.RTCPeerConnection(e),Kn=()=>"undefined"!=typeof navigator&&!!navigator.mediaDevices,Gn=()=>{if(!Kn())throw new Error("The media devices API isn't supported in this environment");return navigator.mediaDevices},Jn=()=>Gn().getSupportedConstraints(),Qn=e=>e&&e instanceof MediaStream,Xn=()=>"sinkId"in HTMLMediaElement.prototype,Yn=async(e,t)=>{if(null!==e)if("string"==typeof t)if(Xn())try{return await e.setSinkId(t)}catch(e){throw"SecurityError"===e.name?Zt().error(`You need to use HTTPS for selecting audio output device: ${e}`):Zt().error(`Error: ${e}`),e}else Zt().warn("Browser does not support output device selection.");else Zt().warn(`Invalid speaker deviceId: '${t}'`);else Zt().warn("No HTMLMediaElement to attach the speakerId")},Zn=e=>{var t;Qn(e)&&(null===(t=null==e?void 0:e.getTracks())||void 0===t||t.forEach(es))},es=e=>{e&&"live"===e.readyState&&(e.stop(),e.dispatchEvent(new Event("ended")))},ts={camera:"videoinput",microphone:"audioinput",speaker:"audiooutput"},rs=e=>{if(e)return ts[e]},is=()=>Gn().enumerateDevices(),os=async e=>{let t=await is().catch((e=>[]));return e&&(t=t.filter((({kind:t})=>t===e))),t},ns=async e=>{if("permissions"in navigator&&"function"==typeof navigator.permissions.query&&e)try{return"granted"===(await navigator.permissions.query({name:e})).state}catch(e){}return(async e=>{const t=await os(e);return t.length?t.every((({deviceId:e,label:t})=>Boolean(e&&t))):(Zt().warn(`No ${e} devices to check for permissions!`),null)})(rs(e))},ss=()=>ns("camera"),as=()=>ns("microphone"),cs=()=>ns("speaker"),ds=async(e={audio:!0,video:!0})=>{var t;try{const t=Gn().getUserMedia(e),r=await(async e=>{const t=[];return(null==e?void 0:e.audio)&&t.push(as()),(null==e?void 0:e.video)&&t.push(ss()),!!t.length&&(await Promise.all(t)).every(Boolean)})(e);if(r){const e=new Error("Timeout reading from your devices");return await fr(t,5e3,e)}return await t}catch(r){switch(r.name){case"Error":Zt().error(null!==(t=null==r?void 0:r.message)&&void 0!==t?t:"navigator.mediaDevices.getUserMedia doesn't seem to be supported.");break;case"NotFoundError":Zt().error("No media tracks of the type specified were found that satisfy the given constraints.");break;case"NotReadableError":Zt().error("Hardware error occurred at the operating system, browser, or Web page level which prevented access to the device. This could have been caused by having the Camera or Mic being user by another application.");break;case"OverconstrainedError":Zt().error(`The constraint: ${r.constraint} cannot be met by the selected device.`),Zt().info("List of available constraints:",Jn());break;case"NotAllowedError":Zt().error("The user has mostly likely denied access to the device. This could also happen if the browsing context is insecure (using HTTP rather than HTTPS)");break;case"TypeError":0===Object.keys(e).length?Zt().error('Constraints can\'t be empty nor have "video" and "audio" set to false.'):Zt().error("Please check that you are calling this method from a secure context (using HTTPS rather than HTTP).");break;case"SecurityError":Zt().error("User media support is disabled on the Document on which getUserMedia() was called. The mechanism by which user media support is enabled and disabled is left up to the individual user agent.")}throw r}},ls=e=>Gn().getDisplayMedia(e),us=async(e,t=!1)=>ms(e,t),hs=(e,t={})=>{const r=[];return e.filter((({deviceId:e,kind:i,groupId:o})=>{var n;if(!e||t.targets&&!(null===(n=t.targets)||void 0===n?void 0:n.includes(i)))return!1;if(!o)return!0;const s=`${i}-${o}`,a=!(null==t?void 0:t.excludeDefault)||"default"!==e;return!(r.includes(s)||!a||(r.push(s),0))}))},ms=async(e,t=!1)=>{let r;if(!1===await ns(e)){const t={audio:!(i=e)||"all"===i||"microphone"===i||"speaker"===i,video:!i||"all"===i||"camera"===i};r=await ds(t)}var i;const o=await os(rs(e));return r&&Zn(r),!0===t?o:hs(o)},ps=()=>ms("speaker"),gs=async(e,t,r)=>{const i=await ms(r,!0);for(let r=0;r<i.length;r++){const{deviceId:o,label:n}=i[r];if(e===o||t===n)return o}return null},fs=e=>{const t=new Map;return e.forEach((e=>{e.deviceId&&t.set(e.deviceId,e)})),t},vs={camera:ss,microphone:as,speaker:cs},ys=["camera","microphone","speaker"],bs=`Allowed targets are: '${ys.join("', '")}'`,_s={speaker:Xn},ws=async(e={})=>{const t=await(async e=>{var t;const r=(null!==(t=e.targets)&&void 0!==t?t:ys).filter((e=>!!ys.includes(e)||(Zt().warn(`We'll ignore the "${e}" target as it is not allowed. ${bs}.`),!1)));if(!r.length)throw new Error(`At least one "target" is required for createDeviceWatcher(). ${bs}.`);const i=await(async e=>{const t=e.targets;return(await Promise.all(t.map((e=>vs[e]())))).reduce(((e,r,i)=>{var o;const n=t[i];return e[!(n in _s)||(null===(o=_s[n])||void 0===o?void 0:o.call(_s))?"supported":"unsupported"].push([n,!!r]),e}),{supported:[],unsupported:[]})})({targets:r});if(i.unsupported.length>0&&r.length===i.unsupported.length)throw new Error(`The platform doesn't support "${r.join(", ")}" as target/s, which means it's not possible to watch for changes on those devices.`);if(i.supported.every((([e,t])=>!t)))throw new Error("You must ask the user for permissions before being able to listen for device changes. Try calling getUserMedia() before calling `createDeviceWatcher()`.");let o=[];const n=i.supported.reduce(((e,[t,r])=>(r?e.push(t):o.push(t),e)),[]);if(n.length!==r.length){const e=i.unsupported.length>0?`The platform doesn't support "${i.unsupported.map((([e])=>e)).join(", ")}" as target/s, which means it's not possible to watch for changes on those devices. `:"",t=o.length>0?`The user hasn't granted permissions for the following targets: ${o.join(", ")}. `:"";Zt().warn(`${e}${t}We'll be watching for the following targets instead: "${n.join(", ")}"`)}return Zt().debug(`Watching these targets: "${n.join(", ")}"`),n})({targets:e.targets}),r=new St,i=await is(),o=null==t?void 0:t.reduce(((e,t)=>{const r=rs(t);return r&&e.push(r),e}),[]);let n=hs(i,{excludeDefault:!0,targets:o});return Gn().addEventListener("devicechange",(async()=>{const e=await is(),t=n,i=hs(e,{excludeDefault:!0,targets:o});n=i;const s=((e,t)=>{const r=fs(e),i=fs(e),o=[];Zt().debug("[_getDeviceListDiff] <- oldDevices",e),Zt().debug("[_getDeviceListDiff] -> newDevices",t);const n=t.filter((e=>{const t=e.deviceId,n=r.get(t);return n&&(i.delete(t),e.label!==n.label&&o.push(e)),void 0===n}));return{updated:o.map((e=>({type:"updated",payload:e}))),removed:Array.from(i,(([e,t])=>t)).map((e=>({type:"removed",payload:e}))),added:n.map((e=>({type:"added",payload:e})))}})(t,i),a=s.added.length>0,c=s.removed.length>0,d=s.updated.length>0;(a||c||d)&&r.emit("changed",{changes:s,devices:i}),a&&r.emit("added",{changes:s.added,devices:i}),c&&r.emit("removed",{changes:s.removed,devices:i}),d&&r.emit("updated",{changes:s.updated,devices:i})})),r},ks=()=>ws({targets:["speaker"]}),Ss=e=>"function"==typeof(null==e?void 0:e.getTracks),Cs=async e=>(await ps()).find((t=>t.deviceId===e||"default"===t.deviceId&&""===e||""===t.deviceId&&"default"===e)),Is=e=>{Zt().info("RTCService.getUserMedia",e);const{audio:t,video:r}=e;if(t||r)return ds(e)},Ts=async e=>{var t,r;const{micLabel:i="",micId:o}=e;let n=null===(t=e.audio)||void 0===t||t;if(o&&n){const e=await gs(o,i,"microphone").catch((e=>null));e&&("boolean"==typeof n&&(n={}),n.deviceId={exact:e})}const{camLabel:s="",camId:a}=e;let c=null===(r=e.video)||void 0===r||r;if(a&&c){const e=await gs(a,s,"camera").catch((e=>null));e&&("boolean"==typeof c&&(c={}),c.deviceId={exact:e})}return{audio:n,video:c}},Es=(e,t)=>{const{disableUdpIceServers:r=!1}=t,i=e=>{const t="transport=udp";return Array.isArray(e)?e.filter((e=>!e.includes(t))):e.includes(t)?"":e};return e.map((e=>Object.assign(Object.assign({},e),{urls:r?i(e.urls):e.urls})))};var Ps={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;t.push("rtp"===r?1:"rtcp"===r?2:r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)r=i[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{i.push(void 0!==e.parameters[t]?t+"="+e.parameters[t]:t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],o=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&o?{usernameFragment:i.substring(12),password:o.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let o=3;o<i.length;o++){const n=i[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const i=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(i.parameters=o.length?t.parseFmtp(o[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),r.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const o=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{o.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let o=0;return r.codecs.forEach((e=>{e.maxptime>o&&(o=e.maxptime)})),o>0&&(i+="a=maxptime:"+o+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),o=-1!==i.fecMechanisms.indexOf("RED"),n=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),o&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:n?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach((e=>{e.maxBitrate=l}))),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const o=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=o.length>0,r.compound=0===o.length;const n=t.matchPrefix(e,"a=rtcp-mux");return r.mux=n.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return o.length>0?(r=o[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let o;i.length>0&&(o=parseInt(i[0].substring(19),10)),isNaN(o)&&(o=65536);const n=t.matchPrefix(e,"a=sctp-port:");if(n.length>0)return{port:parseInt(n[0].substring(12),10),protocol:r.fmt,maxMessageSize:o};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:o}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let o;const n=void 0!==r?r:2;return o=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+o+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(Ps);var Ms=Ps.exports;const Rs=e=>/^m=audio/.test(e),As=e=>/^m=video/.test(e),xs=e=>{const t="\r\n",r=e.split(t),i=r.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const o=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),r=e.match(t);return r&&2==r.length?r[1]:null})(r[i]),n=new RegExp(`a=fmtp:${o}`),s=r.findIndex((e=>n.test(e)));return s>=0?/stereo=1;/.test(r[s])||(r[s]+="; stereo=1; sprop-stereo=1"):r[i]+=`${t}a=fmtp:${o} stereo=1; sprop-stereo=1`,r.join(t)},Os=e=>{try{const t=/typ (?:srflx|prflx|relay)/,r=Ms.getMediaSections(e);for(const e of r)if(!Ms.splitLines(e).some((e=>0===e.indexOf("a=candidate")&&t.test(e))))return!1;return!0}catch(e){return Zt().error("Error checking SDP",e),!1}},js=(e,t)=>{const r=(e=>e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"))(e).split("\n");let i=!1;const o=["inactive","recvonly","sendonly","sendrecv","stopped"];for(let e of r)if(e.startsWith("m="))i=e.startsWith(`m=${t}`);else if(i&&e.startsWith("a=")){const t=e.substring(2);if(o.includes(t))return t}return i?"sendrecv":"stopped"},Ls=({localSdp:e,remoteSdp:t,media:r})=>{const i=(e=>{switch(e){case"sendrecv":return"sendrecv";case"sendonly":return"recvonly";case"recvonly":return"sendonly";default:return"inactive"}})(js(e,r));return js(t,r)===i};function Ds(e){"live"===e.readyState&&e.stop(),e._mockOscillator&&(e._mockOscillator.stop(),e._mockOscillator.disconnect(),delete e._mockOscillator),e._mockContext&&(e._mockContext.close(),delete e._mockContext)}function Ws(e){e&&("live"===e.readyState&&e.stop(),e._mockCanvas&&(e._mockCanvas.remove(),delete e._mockCanvas))}class Vs{constructor(e,t=3,r=!1){this.pool=new Map,this.turnRefreshInterval=24e4,this.logger=Zt();const i=e.iceCandidatePoolSize||10;this.config=Object.assign(Object.assign({},e),{iceCandidatePoolSize:i>20?20:i}),this.poolSize=t>4?4:t,this.forceRefresh=r}async initializePool(){this.logger.info(`Initializing RTCPeerConnection pool with size ${this.poolSize}`);const e=[];for(let t=0;t<this.poolSize;t++)e.push(this.createPooledConnection());(await Promise.all(e)).forEach((e=>{e&&this.pool.set(e.id,e)})),this.logger.info(`Pool initialized with ${this.pool.size} connections`),this.forceRefresh&&(this.logger.info("Manual force refresh mode enabled, TURN allocations will not be refreshed by this manager."),this.startMaintenanceWorker())}getConnection(){for(const[e,t]of this.pool.entries())if(this.logger.debug(`Checking pooled connection ${e}`),this.logger.debug(`Connection state: ${t.pc.connectionState}`),this.logger.debug(`Signaling state: ${t.pc.signalingState}`),this.logger.debug(`ICE connection state: ${t.pc.iceConnectionState}`),this.isConnectionValid(t))return this.logger.info(`Providing pooled connection ${e}`),this.pool.delete(e),this.cleanupMockTracks(t),this.replenishPool().catch((e=>{this.logger.error("Failed to replenish pool:",e)})),t.pc;return this.logger.warn("No valid pooled connections available"),null}cleanup(){this.logger.info("Cleaning up RTCPeerConnectionManager"),this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0);for(const[,e]of this.pool.entries())this.closeConnection(e);this.pool.clear()}async createPooledConnection(){var e;try{const t=qn(this.config),r=`conn_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;this.logger.debug(`Creating pooled connection ${r}`);const i=function(){const e=new(window.AudioContext||window.webkitAudioContext),t=e.createOscillator(),r=e.createMediaStreamDestination();t.frequency.value=0,t.connect(r),t.start();const i=r.stream.getAudioTracks()[0];return i._mockContext=e,i._mockOscillator=t,i}(),o=function(){const e=document.createElement("canvas");if(!e.captureStream)return console.warn("canvas.captureStream not supported, using audio-only mock"),null;e.width=320,e.height=240;const t=e.getContext("2d");t&&(t.fillStyle="#000000",t.fillRect(0,0,e.width,e.height));const r=e.captureStream(1).getVideoTracks()[0];return r._mockCanvas=e,r}(),n=[],s=t.addTrack(i);n.push(s);let a=null;o&&(a=t.addTrack(o),n.push(a));const c=await t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});await t.setLocalDescription(c),await this.waitForIceGathering(t);const d={id:r,pc:t,createdAt:Date.now(),lastRefreshed:Date.now(),iceGatheringComplete:!0,mockTracks:{audio:i,video:o||void 0},senders:n};return this.logger.debug(`Pooled connection ${r} created successfully`),this.logger.debug(`ICE candidates gathered for connection ${r}:`,null===(e=t.localDescription)||void 0===e?void 0:e.sdp),d}catch(e){return this.logger.error("Failed to create pooled connection:",e),null}}waitForIceGathering(e){return new Promise((t=>{if("complete"===e.iceGatheringState)return void t();const r=()=>{"complete"===e.iceGatheringState&&(i(),t())},i=()=>{e.removeEventListener("icegatheringstatechange",r),clearTimeout(o)};e.addEventListener("icegatheringstatechange",r);const o=setTimeout((()=>{this.logger.warn("ICE gathering timeout, proceeding anyway"),i(),t()}),1e4)}))}cleanupMockTracks(e){this.logger.debug(`Cleaning up mock tracks for connection ${e.id}`),e.mockTracks.audio&&Ds(e.mockTracks.audio),e.mockTracks.video&&Ws(e.mockTracks.video),e.senders.forEach((t=>{try{e.pc.removeTrack(t)}catch(e){this.logger.warn("Error removing track:",e)}})),this.cleanupEventListeners(e.pc),e.mockTracks={},e.senders=[]}cleanupEventListeners(e){["icecandidate","icegatheringstatechange","iceconnectionstatechange","connectionstatechange","signalingstatechange","negotiationneeded","track","datachannel","addstream","removestream"].forEach((t=>{e[`on${t}`]=null}))}isConnectionValid(e){if("closed"===e.pc.connectionState||"failed"===e.pc.connectionState)return this.logger.debug(`Pooled connection ${e.id} is not valid: ${e.pc.connectionState}`),!1;if("closed"===e.pc.signalingState)return this.logger.debug(`Pooled connection ${e.id} signalingState is not valid: ${e.pc.signalingState}`),!1;if("failed"===e.pc.iceConnectionState||"disconnected"===e.pc.iceConnectionState)return this.logger.debug(`Pooled connection ${e.id} iceConnectionState is not valid: ${e.pc.iceConnectionState}`),!1;const t=Date.now()-e.lastRefreshed;return!(this.forceRefresh&&t>this.turnRefreshInterval&&(this.logger.debug(`Pooled connection ${e.id} is not valid: TURN allocation age ${t}`),1))}async replenishPool(){const e=this.poolSize-this.pool.size;if(!(e<=0)){this.logger.debug(`Replenishing pool with ${e} connections`);for(let t=0;t<e;t++){const e=await this.createPooledConnection();e&&this.pool.set(e.id,e)}}}startMaintenanceWorker(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval((()=>{this.refreshTurnAllocations().catch((e=>{this.logger.error("TURN refresh error:",e)}))}),this.turnRefreshInterval)}async refreshTurnAllocations(){const e=Date.now();for(const[t,r]of this.pool.entries())if(e-r.lastRefreshed>this.turnRefreshInterval)try{await this.refreshConnection(r)}catch(e){this.logger.error(`Failed to refresh connection ${t}:`,e),this.pool.delete(t),this.closeConnection(r)}this.replenishPool().catch((e=>{this.logger.error("Failed to replenish after refresh:",e)}))}async refreshConnection(e){var t;this.logger.debug(`Refreshing TURN allocation for connection ${e.id}`),e.pc.restartIce();const r=await e.pc.createOffer({iceRestart:!0});await e.pc.setLocalDescription(r),await this.waitForIceGathering(e.pc),e.lastRefreshed=Date.now(),this.logger.debug(`TURN allocation refreshed for connection ${e.id}`),this.logger.debug(`New ICE candidates for connection ${e.id}:`,null===(t=e.pc.localDescription)||void 0===t?void 0:t.sdp)}closeConnection(e){try{e.mockTracks.audio&&Ds(e.mockTracks.audio),e.mockTracks.video&&Ws(e.mockTracks.video),"closed"!==e.pc.connectionState&&e.pc.close()}catch(t){this.logger.error(`Error closing connection ${e.id}:`,t)}}}const Ns=new class{constructor(){this.logger=Zt()}async initializePool(e,t={}){var r,i;if(this.manager)return void this.logger.warn("Connection pool already initialized");this.logger.info("Initializing connection pool");const o={iceServers:e,iceCandidatePoolSize:null!==(r=t.iceCandidatePoolSize)&&void 0!==r?r:10};this.manager=new Vs(o,null!==(i=t.poolSize)&&void 0!==i?i:2),await this.manager.initializePool()}getConnection(){return this.manager?this.manager.getConnection():(this.logger.warn("Connection pool not initialized"),null)}cleanup(){this.manager&&(this.logger.info("Cleaning up connection pool"),this.manager.cleanup(),this.manager=void 0)}get isInitialized(){return!!this.manager}};class $s{get logger(){return Zt()}constructor(e,t){this.call=e,this.type=t,this.uuid=b(),this._negotiating=!1,this._processingRemoteSDP=!1,this._restartingIce=!1,this._candidatesSnapshot=[],this._allCandidates=[],this._processingLocalSDP=!1,this.logger.debug("New Peer with type:",this.type,"Options:",this.options),this._onIce=this._onIce.bind(this),this._onEndedTrackHandler=this._onEndedTrackHandler.bind(this),this.options.prevCallId&&(this.uuid=this.options.prevCallId),this.options.prevCallId=void 0,this.options.localStream&&Qn(this.options.localStream)&&(this._localStream=this.options.localStream),this.rtcConfigPolyfill=this.config}get options(){return this.call.options}get watchMediaPacketsTimeout(){var e;return null!==(e=this.options.watchMediaPacketsTimeout)&&void 0!==e?e:2e3}get isNegotiating(){return this._negotiating}get localStream(){return this._localStream}set localStream(e){this._localStream=e}get remoteStream(){return this._remoteStream}get isOffer(){return"offer"===this.type}get isAnswer(){return"answer"===this.type}get isSimulcast(){return!0===this.options.simulcast}get isSfu(){return!0===this.options.sfu}get localVideoTrack(){const e=this._getSenderByKind("video");return(null==e?void 0:e.track)||null}get localAudioTrack(){const e=this._getSenderByKind("audio");return(null==e?void 0:e.track)||null}get remoteVideoTrack(){const e=this._getReceiverByKind("video");return(null==e?void 0:e.track)||null}get remoteAudioTrack(){const e=this._getReceiverByKind("audio");return(null==e?void 0:e.track)||null}get hasAudioSender(){return!!this._getSenderByKind("audio")}get hasVideoSender(){return!!this._getSenderByKind("video")}get hasAudioReceiver(){return!!this._getReceiverByKind("audio")}get hasVideoReceiver(){return!!this._getReceiverByKind("video")}get config(){const{rtcPeerConfig:e={}}=this.options,t=Object.assign({bundlePolicy:"max-compat",iceServers:Es(this.call.iceServers,{disableUdpIceServers:this.options.disableUdpIceServers}),sdpSemantics:"unified-plan"},e);return this.logger.debug("RTC config",t),t}get localSdp(){var e,t;return null===(t=null===(e=this.instance)||void 0===e?void 0:e.localDescription)||void 0===t?void 0:t.sdp}get remoteSdp(){var e,t;return null===(t=null===(e=this.instance)||void 0===e?void 0:e.remoteDescription)||void 0===t?void 0:t.sdp}get hasIceServers(){if(this.instance){const{iceServers:e=[]}=this.getConfiguration();return Boolean(null==e?void 0:e.length)}return!1}stopTrackSender(e){var t;try{const r=this._getSenderByKind(e);if(!r)return this.logger.info(`There is not a '${e}' sender to stop.`);r.track&&(es(r.track),null===(t=this._localStream)||void 0===t||t.removeTrack(r.track))}catch(t){this.logger.error("RTCPeer stopTrackSender error",e,t)}}stopTrackReceiver(e){var t;try{const r=this._getReceiverByKind(e);if(!r)return this.logger.info(`There is not a '${e}' receiver to stop.`);r.track&&(es(r.track),null===(t=this._remoteStream)||void 0===t||t.removeTrack(r.track))}catch(t){this.logger.error("RTCPeer stopTrackReceiver error",e,t)}}async restoreTrackSender(e){var t;try{const r=this._getSenderByKind(e);if(!r)return this.logger.info(`There is not a '${e}' sender to restore.`);if(r.track&&"ended"!==r.track.readyState)return this.logger.info(`There is already an active ${e} track.`);const i=await Ts(this.options),o=await Is({[e]:i[e]});if(o&&Qn(o)){const i=o.getTracks().find((t=>t.kind===e));i&&(await r.replaceTrack(i),null===(t=this._localStream)||void 0===t||t.addTrack(i))}}catch(t){this.logger.error("RTCPeer restoreTrackSender error",e,t)}}getDeviceId(e){try{const t=this._getSenderByKind(e);if(!t||!t.track)return null;const{deviceId:r=null}=t.track.getSettings();return r}catch(t){return this.logger.error("RTCPeer getDeviceId error",e,t),null}}getTrackSettings(e){try{const t=this._getSenderByKind(e);return t&&t.track?t.track.getSettings():null}catch(t){return this.logger.error("RTCPeer getTrackSettings error",e,t),null}}getTrackConstraints(e){try{const t=this._getSenderByKind(e);return t&&t.track?t.track.getConstraints():null}catch(t){return this.logger.error("RTCPeer getTrackConstraints error",e,t),null}}getDeviceLabel(e){try{const t=this._getSenderByKind(e);return t&&t.track?t.track.label:null}catch(t){return this.logger.error("RTCPeer getDeviceLabel error",e,t),null}}restartIceWithRelayOnly(){var e,t;try{if(this.isAnswer)return this.logger.warn("Skip restartIceWithRelayOnly since we need to generate answer");const e=this.getConfiguration();if("relay"===e.iceTransportPolicy)return this.logger.warn("RTCPeer already with iceTransportPolicy relay only");const t=Object.assign(Object.assign({},e),{iceTransportPolicy:"relay"});this.setConfiguration(t),this.restartIce()}catch(r){this.logger.error("restartIceWithRelayOnly",r),null===(e=this._rejectStartMethod)||void 0===e||e.call(this,r),null===(t=this._pendingNegotiationPromise)||void 0===t||t.reject(r)}}restartIce(){if(this._negotiating||this._restartingIce)return this.logger.warn("Skip restartIce");this._restartingIce=!0,this.logger.debug("Restart ICE"),this.type="offer",this.instance.restartIce()}triggerResume(){this.logger.info("Probably half-open so force close from client"),this._resumeTimer?this.logger.info('[skipped] Already in "resume" state'):(this.call.emit("media.disconnected"),this.call.emit("media.reconnecting"),this.clearTimers(),this._resumeTimer=setTimeout((()=>{this.logger.warn("Disconnecting due to RECONNECTION_ATTEMPT_TIMEOUT"),this.call.emit("media.disconnected"),this.call.leaveReason="RECONNECTION_ATTEMPT_TIMEOUT",this.call.setState("hangup")}),12e3),this.call._closeWSConnection())}resetNeedResume(){this.clearResumeTimer(),this.options.watchMediaPackets&&this.startWatchMediaPackets()}stopWatchMediaPackets(){this._mediaWatcher&&this._mediaWatcher.stop()}startWatchMediaPackets(){var e;this.stopWatchMediaPackets(),this._mediaWatcher=(e=>{if(!e.hasAudioReceiver&&!e.hasVideoReceiver)return void Zt().warn(`Missing receivers to inspect media for RTCPeer "${e.uuid}"`);Zt().debug(`Start watching media for RTCPeer "${e.uuid}"`);let t,r=0,i=0,o=!0;const n=()=>{clearTimeout(t)},s=async()=>{var a,c;let d=0,l=0;try{const t=await e.instance.getStats(null),r=null===(a=e.remoteAudioTrack)||void 0===a?void 0:a.id,i=null===(c=e.remoteVideoTrack)||void 0===c?void 0:c.id;t.forEach((e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&e.trackIdentifier===r&&(Zt().trace(`audio inbound-rtp: packetsReceived: ${e.packetsReceived} (at ${e.lastPacketReceivedTimestamp})`),d=e.packetsReceived),"inbound-rtp"===e.type&&"video"===e.kind&&e.trackIdentifier===i&&(Zt().trace(`video inbound-rtp: packetsReceived: ${e.packetsReceived} (at ${e.lastPacketReceivedTimestamp})`),l=e.packetsReceived)}))}catch(e){Zt().warn("getStats error",e)}finally{d&&d<=r&&l&&l<=i?(Zt().warn(`audioPacketsReceived: ${d} - previousAudioValue: ${r}`),Zt().warn(`videoPacketsReceived: ${l} - previousVideoValue: ${i}`),e.triggerResume()):(r=null!=d?d:r,i=null!=l?l:i,n(),o&&"closed"!==e.instance.connectionState&&(t=setTimeout((()=>s()),e.watchMediaPacketsTimeout)))}};return{start:()=>{n(),s()},stop:()=>{o=!1,n()}}})(this),null===(e=this._mediaWatcher)||void 0===e||e.start()}async applyMediaConstraints(e,t){try{const r=this._getSenderByKind(e);if(!r||!r.track)return this.logger.info("No sender to apply constraints",e,t);if("live"===r.track.readyState){const i=Object.assign(Object.assign({},r.track.getConstraints()),t),o=this.getDeviceId(e);o&&!this.options.screenShare&&(i.deviceId={exact:o}),this.logger.info(`Apply ${e} constraints`,this.call.id,i),await r.track.applyConstraints(i)}}catch(r){this.logger.error("Error applying constraints",e,t)}}_getSenderByKind(e){var t;return(null===(t=this.instance)||void 0===t?void 0:t.getSenders)?this.instance.getSenders().find((({track:t})=>t&&t.kind===e)):(this.logger.warn("RTCPeerConnection.getSenders() not available."),null)}_getReceiverByKind(e){var t;return(null===(t=this.instance)||void 0===t?void 0:t.getReceivers)?this.instance.getReceivers().find((({track:t})=>t&&t.kind===e)):(this.logger.warn("RTCPeerConnection.getReceivers() not available."),null)}async startNegotiation(e=!1){var t,r,i;if(this._negotiating)return this.logger.warn("Skip twice onnegotiationneeded!");this._negotiating=!0;try{if((this.options.additionalDevice||this.options.screenShare)&&(null===(r=null===(t=this.instance)||void 0===t?void 0:t.getTransceivers)||void 0===r||r.call(t).forEach((e=>{e.direction="sendonly"}))),this.instance.removeEventListener("icecandidate",this._onIce),this.instance.addEventListener("icecandidate",this._onIce),this.isOffer){this.logger.debug("Trying to generate offer");const e={voiceActivityDetection:!1};this._supportsAddTransceiver()||(e.offerToReceiveAudio=this.options.negotiateAudio,e.offerToReceiveVideo=this.options.negotiateVideo);const t=await this.instance.createOffer(e);await this._setLocalDescription(t)}if(this.isAnswer){this.logger.debug("Trying to generate answer"),await this._setRemoteDescription({sdp:this.options.remoteSdp,type:"offer"});const e=await this.instance.createAnswer({voiceActivityDetection:!1});await this._setLocalDescription(e)}e&&"have-local-offer"===this.instance.signalingState&&this._sdpReady(),this.logger.info("iceGatheringState",this.instance.iceGatheringState),"gathering"===this.instance.iceGatheringState&&(this._iceTimeout=setTimeout((()=>{this._onIceTimeout()}),this.options.maxIceGatheringTimeout))}catch(e){this.logger.error(`Error creating ${this.type}:`,e),null===(i=this._pendingNegotiationPromise)||void 0===i||i.reject(e)}}onRemoteBye({code:e,message:t}){var r,i;const o={code:e,message:t};null===(r=this._rejectStartMethod)||void 0===r||r.call(this,o),null===(i=this._pendingNegotiationPromise)||void 0===i||i.reject(o),this.stop()}async onRemoteSdp(e){var t,r;if(this._processingRemoteSDP||this.remoteSdp&&this.remoteSdp===e)this.logger.warn("Ignore same remote SDP",e);else try{const r=this.isOffer?"answer":"offer";if("answer"===r&&"have-local-offer"!==this.instance.signalingState)return void this.logger.warn("Ignoring offer SDP as signaling state is not have-local-offer");this._processingRemoteSDP=!0,await this._setRemoteDescription({sdp:e,type:r}),this._processingRemoteSDP=!1,this.isOffer&&(this._resolveStartMethod(),null===(t=this._pendingNegotiationPromise)||void 0===t||t.resolve()),this.resetNeedResume()}catch(e){this._processingRemoteSDP=!1,this.logger.error(`Error handling remote SDP on call ${this.call.id}:`,e),this.call.hangup(),this._rejectStartMethod(e),null===(r=this._pendingNegotiationPromise)||void 0===r||r.reject(e)}}_setupRTCPeerConnection(){if(!this.instance){let e=null;try{e=Ns.getConnection()}catch(e){this.logger.debug("Could not access session connection pool",e)}e?(this.logger.info("Using pre-warmed connection from session pool with ICE candidates ready"),this.instance=e):(this.logger.debug("Creating new RTCPeerConnection (no pooled connection available)"),this.instance=qn(this.config)),this._attachListeners()}}async start(){return new Promise((async(e,t)=>{var r,i,o;this._resolveStartMethod=e,this._rejectStartMethod=t;try{this._localStream=await this._retrieveLocalStream()}catch(e){return this._rejectStartMethod(e),null===(r=this._pendingNegotiationPromise)||void 0===r||r.reject(e),this.call.setState("hangup")}this._setupRTCPeerConnection();let n=!1;if(this._localStream&&Qn(this._localStream)){const e=this._localStream.getAudioTracks();this.logger.debug("Local audio tracks: ",e);const t=this._localStream.getVideoTracks();if(this.logger.debug("Local video tracks: ",t),n=Boolean(e.length||t.length),this.isOffer&&this._supportsAddTransceiver()){const r={direction:this.options.negotiateAudio?"sendrecv":"sendonly",streams:[this._localStream]};this.logger.debug("Applying audioTransceiverParams",r);const i=this.instance.getTransceivers().filter((e=>{var t,r;return"audio"===(null===(t=e.receiver.track)||void 0===t?void 0:t.kind)||!e.sender.track&&!e.receiver.track&&(null===(r=e.mid)||void 0===r?void 0:r.includes("audio"))}));e.forEach(((e,t)=>{var o;if(t<i.length){const n=i[t];this.logger.debug("Reusing existing audio transceiver",n.mid),n.sender.replaceTrack(e),n.direction=r.direction||"sendrecv",(null===(o=r.streams)||void 0===o?void 0:o[0])&&(n.sender.streams=r.streams)}else this.logger.debug("Creating new audio transceiver"),this.instance.addTransceiver(e,r)}));const o={direction:this.options.negotiateVideo?"sendrecv":"sendonly",streams:[this._localStream]};this.isSimulcast&&(o.sendEncodings=["0","1","2"].map((e=>({active:!0,rid:e,scaleResolutionDownBy:6*Number(e)||1})))),this.logger.debug("Applying videoTransceiverParams",o);const n=this.instance.getTransceivers().filter((e=>{var t,r;return"video"===(null===(t=e.receiver.track)||void 0===t?void 0:t.kind)||!e.sender.track&&!e.receiver.track&&(null===(r=e.mid)||void 0===r?void 0:r.includes("video"))}));if(t.forEach(((e,t)=>{var r;if(t<n.length){const i=n[t];if(this.logger.debug("Reusing existing video transceiver",i.mid),i.sender.replaceTrack(e),i.direction=o.direction||"sendrecv",(null===(r=o.streams)||void 0===r?void 0:r[0])&&(i.sender.streams=o.streams),o.sendEncodings){const e=i.sender.getParameters();e.encodings=o.sendEncodings,i.sender.setParameters(e)}}else this.logger.debug("Creating new video transceiver"),this.instance.addTransceiver(e,o)})),this.isSfu){const{msStreamsNumber:e=5}=this.options;this.logger.debug("Add ",e,"recvonly MS Streams"),o.direction="recvonly";for(let t=0;t<Number(e);t++)this.instance.addTransceiver("video",o)}}else if("function"==typeof this.instance.addTrack){const r=this._localStream;e.forEach((e=>this.instance.addTrack(e,r))),t.forEach((e=>this.instance.addTrack(e,r)))}else this.instance.addStream(this._localStream)}if(this.isOffer){if("have-local-offer"===this.instance.signalingState){this.logger.debug("Reusing pooled connection, managing transceivers");const e=(null===(i=this._localStream)||void 0===i?void 0:i.getAudioTracks())||[],t=(null===(o=this._localStream)||void 0===o?void 0:o.getVideoTracks())||[];this.instance.getTransceivers().forEach((r=>{var i,o,n,s;const a="audio"===(null===(i=r.receiver.track)||void 0===i?void 0:i.kind)||!r.sender.track&&!r.receiver.track&&(null===(o=r.mid)||void 0===o?void 0:o.includes("audio")),c="video"===(null===(n=r.receiver.track)||void 0===n?void 0:n.kind)||!r.sender.track&&!r.receiver.track&&(null===(s=r.mid)||void 0===s?void 0:s.includes("video"));a&&0===e.length&&(this.logger.debug("Setting unused audio transceiver to inactive",r.mid),r.direction="inactive"),c&&0===t.length&&(this.logger.debug("Setting unused video transceiver to inactive",r.mid),r.direction="inactive")}))}this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video"),"have-local-offer"===this.instance.signalingState&&(this.logger.debug("Reusing pooled connection with local offer"),this.startNegotiation(!0)),this._supportsAddTransceiver()||n||this.startNegotiation()}else this.startNegotiation()}))}detachAndStop(){var e;"function"==typeof(null===(e=this.instance)||void 0===e?void 0:e.getTransceivers)&&this.instance.getTransceivers().forEach((e=>{e.sender.track&&e.sender.track.stop(),e.receiver.track&&e.receiver.track.stop()})),this.stop()}stop(){var e,t,r;null===(e=this._localStream)||void 0===e||e.getTracks().forEach((e=>e.stop())),null===(t=this._remoteStream)||void 0===t||t.getTracks().forEach((e=>e.stop())),null===(r=this.instance)||void 0===r||r.close(),this.stopWatchMediaPackets()}_supportsAddTransceiver(){return"function"==typeof this.instance.addTransceiver}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)&&this._supportsAddTransceiver()){const t=this.instance.getTransceivers().find((t=>{var r,i;return(null===(r=t.receiver.track)||void 0===r?void 0:r.kind)===e||!t.sender.track&&!t.receiver.track&&(null===(i=t.mid)||void 0===i?void 0:i.includes(e))}));if(t)this.logger.debug("Found existing transceiver for",e,t.mid),"inactive"!==t.direction&&"sendonly"!==t.direction||(t.direction="recvonly");else{const t=this.instance.addTransceiver(e,{direction:"recvonly"});this.logger.debug("Add transceiver",e,t)}}}async _sdpReady(){var e,t;if(this._processingLocalSDP)return void this.logger.debug("Already processing local SDP, skipping");if("offer"===this.type&&!["have-local-offer","have-local-pranswer"].includes(this.instance.signalingState))return void this.logger.warn(`_sdpReady called in wrong state: ${this.instance.signalingState}`);if(this._processingLocalSDP=!0,clearTimeout(this._iceTimeout),!this.instance.localDescription)return void this.logger.error("Missing localDescription",this.instance);const{sdp:r}=this.instance.localDescription;if(!(e=>{try{const t=Ms.getMediaSections(e);for(const e of t)if(!Ms.splitLines(e).some((e=>0===e.indexOf("a=candidate"))))return!1;return!0}catch(e){return Zt().error("Error checking SDP",e),!1}})(r))return this.logger.info("No candidate - retry \n"),this._processingLocalSDP=!1,void this.startNegotiation(!0);if(!this._sdpIsValid())return this.logger.info("SDP ready but not valid"),this._processingLocalSDP=!1,void this._onIceTimeout();try{await this.call.onLocalSDPReady(this),this._processingLocalSDP=!1,this.isAnswer&&(this._resolveStartMethod(),null===(e=this._pendingNegotiationPromise)||void 0===e||e.resolve())}catch(e){this._rejectStartMethod(e),null===(t=this._pendingNegotiationPromise)||void 0===t||t.reject(e),this._processingLocalSDP=!1}}_sdpIsValid(){return this.localSdp&&this.hasIceServers?Os(this.localSdp):Boolean(this.localSdp)}_forceNegotiation(){this.logger.info("Force negotiation again"),this._negotiating=!1,this.startNegotiation()}_onIceTimeout(){var e;if(this._sdpIsValid())return void this._sdpReady();this.logger.info("ICE gathering timeout");const t=this.getConfiguration();if("relay"===t.iceTransportPolicy){this.logger.info('RTCPeer already with "iceTransportPolicy: relay"');const t={code:"ICE_GATHERING_FAILED",message:"Ice gathering timeout"};return this._rejectStartMethod(t),null===(e=this._pendingNegotiationPromise)||void 0===e||e.reject(t),void this.call.setState("destroy")}this.setConfiguration(Object.assign(Object.assign({},t),{iceTransportPolicy:"relay"})),this._forceNegotiation()}_onIce(e){var t,r;if(this._iceTimeout&&clearTimeout(this._iceTimeout),!e.candidate)return this.instance.removeEventListener("icecandidate",this._onIce),void(this._candidatesSnapshot.length>0&&(this.logger.debug("No more candidates, calling _sdpReady"),this._sdpReady()));this._allCandidates.push(e.candidate),this.logger.debug("RTCPeer Candidate:",e.candidate),"host"===e.candidate.type?this._iceTimeout=setTimeout((()=>{this.instance.removeEventListener("icecandidate",this._onIce),this._onIceTimeout()}),this.options.maxIceGatheringTimeout):(null===(t=this.instance.localDescription)||void 0===t?void 0:t.sdp)&&(Os(this.instance.localDescription.sdp)?0===this._candidatesSnapshot.length&&"offer"===this.type&&(this._candidatesSnapshot=[...this._allCandidates],this.logger.info("SDP has candidates for all media sections, calling _sdpReady for early invite"),setTimeout((()=>this._sdpReady()),0)):(this.logger.info("SDP does not have candidates for all media sections, waiting for more candidates"),this.logger.debug(null===(r=this.instance.localDescription)||void 0===r?void 0:r.sdp)))}_retryWithMoreCandidates(){this._hasMoreCandidates()&&"connected"!==this.instance.connectionState&&(this.logger.info("More candidates found after ICE gathering complete, triggering renegotiation"),this._negotiating=!1,this._candidatesSnapshot=[],this._allCandidates=[],this.type="offer","stable"===this.instance.signalingState?this.startNegotiation(!0):(this.logger.warn("Signaling state is not stable, cannot start negotiation immediately"),this.restartIce()))}_hasMoreCandidates(){return this._allCandidates.length>this._candidatesSnapshot.length}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:r,googleMinBitrate:i,googleStartBitrate:o}=this.options;return e.sdp&&t&&(e.sdp=xs(e.sdp)),e.sdp&&r&&i&&o&&(e.sdp=((e,t,r,i)=>{const o=e.split("\r\n");return o.forEach(((e,n)=>{/^a=fmtp:\d*/.test(e)?o[n]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${r};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(o[n]+=`\r\nb=AS:${t}`)})),o.join("\r\n")})(e.sdp,r,i,o)),this.instance.setLocalDescription(e)}_setRemoteDescription(e){e.sdp&&this.options.useStereo&&(e.sdp=xs(e.sdp)),e.sdp&&this.instance.localDescription&&(e.sdp=(e=>{const t="\r\n",r=this.instance.localDescription.sdp.split(t),i=r.findIndex(Rs),o=r.findIndex(As);if(-1==o||-1==i||i<o)return e;const n=e.split(t),s=n.findIndex(Rs),a=n.findIndex(As),c=n.slice(s,a),d=n.slice(a,n.length-1);return[...n.slice(0,s),...d,...c,""].join(t)})(e.sdp));const t=e;return this.logger.debug("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}async _retrieveLocalStream(){if(Qn(this.options.localStream))return this.options.localStream;const e=await Ts(this.options);return Is(e)}_attachListeners(){this.instance.addEventListener("signalingstatechange",(()=>{switch(this.logger.debug("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1,this._restartingIce=!1,this.resetNeedResume(),"connected"===this.instance.connectionState&&this.emitMediaConnected();break;case"have-local-offer":"complete"===this.instance.iceGatheringState&&(this.instance.removeEventListener("icecandidate",this._onIce),this._sdpReady());break;case"closed":delete this.instance;break;default:this._negotiating=!0}})),this.instance.addEventListener("connectionstatechange",(()=>{switch(this.logger.debug("connectionState:",this.instance.connectionState),this.instance.connectionState){case"connecting":this._connectionStateTimer=setTimeout((()=>{this.logger.warn("connectionState timed out"),this._hasMoreCandidates()?this._retryWithMoreCandidates():this.restartIceWithRelayOnly()}),this.options.maxConnectionStateTimeout);break;case"connected":this.clearConnectionStateTimer(),this.emitMediaConnected();break;case"disconnected":this.logger.debug("[test] Prevent reattach!");break;case"failed":this.triggerResume()}})),this.instance.addEventListener("negotiationneeded",(()=>{this.logger.debug("Negotiation needed event"),this.startNegotiation()})),this.instance.addEventListener("iceconnectionstatechange",(()=>{this.logger.debug("iceConnectionState:",this.instance.iceConnectionState)})),this.instance.addEventListener("icegatheringstatechange",(()=>{this.logger.debug("iceGatheringState:",this.instance.iceGatheringState),"complete"===this.instance.iceGatheringState&&(this.logger.debug("ICE gathering complete"),this._sdpReady())})),this.instance.addEventListener("track",(e=>{this.call.emit("track",e),this._remoteStream=e.streams[0]})),this.instance.addEventListener("addstream",(e=>{e.stream&&(this._remoteStream=e.stream)})),this._attachAudioTrackListener(),this._attachVideoTrackListener()}clearTimers(){this.clearResumeTimer(),this.clearWatchMediaPacketsTimer(),this.clearConnectionStateTimer()}clearConnectionStateTimer(){clearTimeout(this._connectionStateTimer)}clearWatchMediaPacketsTimer(){clearTimeout(this._watchMediaPacketsTimer)}clearResumeTimer(){clearTimeout(this._resumeTimer),this._resumeTimer=void 0}emitMediaConnected(){this.call.emit("media.connected")}_onEndedTrackHandler(e){const t=e.target;this.call.emit(("audio"===t.kind?"microphone":"camera")+".disconnected",{deviceId:t.id,label:t.label})}_attachAudioTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getAudioTracks().forEach((e=>{e.addEventListener("ended",this._onEndedTrackHandler)}))}_attachVideoTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getVideoTracks().forEach((e=>{e.addEventListener("ended",this._onEndedTrackHandler)}))}_detachAudioTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getAudioTracks().forEach((e=>{e.removeEventListener("ended",this._onEndedTrackHandler)}))}_detachVideoTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getVideoTracks().forEach((e=>{e.removeEventListener("ended",this._onEndedTrackHandler)}))}setConfiguration(e){var t;this.rtcConfigPolyfill=e,this.instance&&"function"==typeof(null===(t=this.instance)||void 0===t?void 0:t.setConfiguration)&&this.instance.setConfiguration(e)}getConfiguration(){var e;return this.instance&&"function"==typeof(null===(e=this.instance)||void 0===e?void 0:e.getConfiguration)?this.instance.getConfiguration():this.rtcConfigPolyfill||this.config}}"function"==typeof SuppressedError&&SuppressedError;const Us=e=>ir(e.type),zs=function*(e){Zt().debug("vertoEventWorker started");const{channels:t,instance:r,initialState:i}=e,{swEventChannel:o}=t,{rtcPeerId:n}=i;if(!n)throw new Error("Missing rtcPeerId for roomSubscribedWorker");const s=_i.createCatchableSaga((function*(e){var t,i;const{id:o,method:s,params:a={}}=e.payload,{callID:c,nodeId:d}=a,l=r.getRTCPeerById(c);if(!l)return void Zt().warn(`RTCPeer '${c}' not found for method: '${s}'`,a);const u=r.peer;switch(s){case"verto.media":case"verto.answer":l.uuid===(null==u?void 0:u.uuid)&&r.setState("verto.media"===s?"early":"active"),(null==a?void 0:a.sdp)&&l.onRemoteSdp(a.sdp),yield Oe(vi.upsert({id:null===(t=e.payload.params)||void 0===t?void 0:t.callID,nodeId:null===(i=e.payload.params)||void 0===i?void 0:i.nodeId})),yield Le([r,r.execute],{method:r._getRPCMethod(),params:{message:$r(o,s),node_id:d}});break;case"verto.bye":yield Le([r,r.onVertoBye],{rtcPeerId:c,byeCause:null==a?void 0:a.cause,byeCauseCode:null==a?void 0:a.causeCode,redirectDestination:null==a?void 0:a.redirectDestination}),yield Le([r,r.execute],{method:r._getRPCMethod(),params:{message:$r(o,s),node_id:d}});break;case"verto.ping":{const{nodeId:e}=a,t=function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(r[i[o]]=e[i[o]])}return r}(a,["nodeId"]);yield Le([r,r.execute],{method:r._getRPCMethod(),params:{message:Nr(t),node_id:e}});break}case"verto.mediaParams":{if(!c||!a.mediaParams){Zt().warn("Invalid mediaParams event",a);break}const{audio:e,video:t}=a.mediaParams;l&&t&&l.applyMediaConstraints("video",t),l&&e&&l.applyMediaConstraints("audio",e);break}case"verto.display":r.setActiveRTCPeer(n),r.emit("verto.display",e.payload.params);break;default:return Zt().warn(`Unknown Verto method: ${s}`,a)}}),(e=>{Zt().error("Verto Error",e)}));try{for(;;){const e=yield xe(o,(e=>{var t;return Zt().debug(`vertoEventWorker for: ${n} checking action...`),!!Us(e)&&(null===(t=e.payload.params)||void 0===t?void 0:t.callID)===n}));yield De(s,e)}}finally{Zt().debug(`vertoEventWorker for ${n} [cancelled]`)}},Bs=function*(e){var t;Zt().debug("roomSubscribedWorker started");const{channels:r,instance:i,initialState:o}=e,{swEventChannel:n}=r,{rtcPeerId:s}=o;if(!s)throw new Error("Missing rtcPeerId for roomSubscribedWorker");try{const e=yield xe(n,(e=>("video.room.subscribed"===e.type||"call.joined"===e.type)&&e.payload.call_id===s)),r=JSON.parse(JSON.stringify(e.payload));i.setActiveRTCPeer(s);const o=e.payload.room_session.id||e.payload.room_session.room_session_id;yield Oe(vi.upsert({id:e.payload.call_id,roomId:null===(t=e.payload.room_session)||void 0===t?void 0:t.room_id,roomSessionId:o,memberId:e.payload.member_id,previewUrl:e.payload.room_session.preview_url})),i.emit("room.subscribed",e.payload),i.emit("room.joined",Fs.call(i,r)),Zt().debug("roomSubscribedWorker ended",s)}finally{Zt().debug(`roomSubscribedWorker for ${s} [cancelled]`)}};function Fs(e){return["room_session","room"].forEach((t=>{e[t]&&e[t].recordings&&(e[t].recordings=(e[t].recordings||[]).map((t=>{let r=this.instanceMap.get(t.id);return r?r.setPayload({room_id:e.room.room_id,room_session_id:e.room_session.id,recording:t}):r=io.createRoomSessionRecordingObject({store:this.store,payload:{room_id:e.room.room_id,room_session_id:e.room_session.id,recording:t}}),this.instanceMap.set(t.id,r),r}))),e[t]&&e[t].playbacks&&(e[t].playbacks=(e[t].playbacks||[]).map((t=>{let r=this.instanceMap.get(t.id);return r?r.setPayload({room_id:e.room.room_id,room_session_id:e.room_session.id,playback:t}):r=io.createRoomSessionPlaybackObject({store:this.store,payload:{room_id:e.room.room_id,room_session_id:e.room_session.id,playback:t}}),this.instanceMap.set(t.id,r),r}))),e[t]&&e[t].streams&&(e[t].streams=(e[t].streams||[]).map((t=>{let r=this.instanceMap.get(t.id);return r?r.setPayload({room_id:e.room.room_id,room_session_id:e.room_session.id,stream:t}):r=io.createRoomSessionStreamObject({store:this.store,payload:{room_id:e.room.room_id,room_session_id:e.room_session.id,stream:t}}),this.instanceMap.set(t.id,r),r})))})),e}const Hs=function*(e){Zt().debug("promoteDemoteWorker started");const{channels:t,instance:r,initialState:i}=e,{swEventChannel:o}=t,{rtcPeerId:n}=i;if(!n)throw new Error("Missing rtcPeerId for promoteDemoteWorker");try{const e=yield xe(o,(e=>("video.member.promoted"===e.type||"video.member.demoted"===e.type)&&e.payload.member_id===r.memberId));Zt().debug("promoteDemoteWorker:",e.type,e.payload),yield Oe(li.updateAuthorization(e.payload.authorization));const t=yield We(Hn.getAuthorization);if(!t)throw new Error(`Invalid authorization for '${e.type}'`);const{audio_allowed:i,video_allowed:s}=t;switch(e.type){case"video.member.promoted":r.updateMediaOptions({audio:"both"===i,video:"both"===s,negotiateAudio:"none"!==i,negotiateVideo:"none"!==s});break;case"video.member.demoted":r.updateMediaOptions({audio:!1,video:!1,negotiateAudio:"none"!==i,negotiateVideo:"none"!==s})}r._triggerNewRTCPeer(),Zt().debug("promoteDemoteWorker ended",n)}finally{Zt().debug(`promoteDemoteWorker for ${n} [cancelled]`)}},qs=function*(e){Zt().debug("sessionAuthWorker started");const{instance:t}=e;switch((yield xe([Ur.authSuccessAction.type,Ur.authErrorAction.type])).type){case Ur.authSuccessAction.type:yield Le([t,t.resume]);break;case Ur.authErrorAction.type:yield Le([t,t.setState],"hangup")}Zt().debug("sessionAuthWorker ended")},Ks=function*(e){var t;const r=Zt();r.debug("sessionConnectionPoolWorker started");const i=e.initialState||{};try{r.debug("Waiting for session/connected action");const e=(null===(t=(yield xe("session/connected")).payload)||void 0===t?void 0:t.ice_servers)||[];if(!e||0===e.length)return void r.warn("No ICE servers available, cannot initialize connection pool");r.info("Session authorized, initializing connection pool"),yield Le([Ns,Ns.initializePool],e,i),r.info("Connection pool initialized successfully"),yield xe(Ur.sessionDisconnectedAction.type),r.info("Session disconnected, cleaning up connection pool"),yield Le([Ns,Ns.cleanup])}catch(e){r.error("Error in sessionConnectionPoolWorker",e)}finally{r.debug("sessionConnectionPoolWorker ended")}},Gs={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},Js=Object.assign(Object.assign({},Gs),{noiseSuppression:!1,autoGainControl:!1,googAutoGainControl:!1}),Qs={width:{ideal:1280,min:320},height:{ideal:720,min:180},aspectRatio:{ideal:16/9}},Xs={destinationNumber:"room",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:Gs,video:Qs,useStereo:!1,attach:!1,screenShare:!1,additionalDevice:!1,userVariables:{},requestTimeout:1e4,autoApplyMediaParams:!0,iceGatheringTimeout:2e3,maxIceGatheringTimeout:5e3,maxConnectionStateTimeout:3e3,watchMediaPackets:!0,watchMediaPacketsTimeout:2e3};class Ys extends qi{constructor(e){super(e),this.leaveReason=void 0,this.gotEarly=!1,this.state="new",this.prevState="new",this.rtcPeerMap=new Map,this.resuming=!1,this._myWorkers=[],this.onVertoBye=e=>{this.logger.debug("onVertoBye",e);const{rtcPeerId:t,byeCause:r="NORMAL_CLEARING",byeCauseCode:i="16",redirectDestination:o}=e;this.cause=String(r),this.causeCode=String(i);const n=this.getRTCPeerById(t);return n?o&&n.localSdp?(this.logger.debug("Redirect Destination to:",o,"for RTCPeer:",n.uuid),void this.executeInvite(n.localSdp,n.uuid,o)):(n.onRemoteBye({code:this.causeCode,message:this.cause}),void(this.activeRTCPeerId===(null==n?void 0:n.uuid)&&(this.logger.debug("onVertoBye go hangup"),this.setState("hangup")))):this.logger.warn("Invalid RTCPeer to hangup",e)},this.options=Object.assign(Object.assign({},Xs),e),this._checkDefaultMediaConstraints(),this.setState("new"),this.logger.trace("New Call with Options:",this.options),this._initPeer()}get id(){return this.__uuid}get active(){return"active"===this.state}get requesting(){return"requesting"===this.state}get trying(){return"trying"===this.state}get memberId(){return this.component.memberId}get previewUrl(){return this.component.previewUrl}get roomId(){return this.component.roomId}get roomSessionId(){return this.component.roomSessionId}get nodeId(){return this.component.nodeId||this.options.nodeId}get callId(){var e;return(null===(e=this.peer)||void 0===e?void 0:e.uuid)||""}get localStream(){var e;return null===(e=this.peer)||void 0===e?void 0:e.localStream}set localStream(e){this.peer&&(this.peer.localStream=e)}get remoteStream(){var e;return null===(e=this.peer)||void 0===e?void 0:e.remoteStream}get iceServers(){var e,t;return null!==(t=null===(e=this.options)||void 0===e?void 0:e.iceServers)&&void 0!==t?t:this.select(Hn.getIceServers)}get component(){return this.select((e=>Xi.getComponent(e,this.callId)))||{}}get cameraId(){return this.peer?this.peer.getDeviceId("video"):null}get cameraLabel(){return this.peer?this.peer.getDeviceLabel("video"):null}get cameraConstraints(){return this.peer?this.peer.getTrackConstraints("video"):null}get microphoneId(){return this.peer?this.peer.getDeviceId("audio"):null}get microphoneLabel(){return this.peer?this.peer.getDeviceLabel("audio"):null}get microphoneConstraints(){return this.peer?this.peer.getTrackConstraints("audio"):null}get withAudio(){var e;return Boolean(null===(e=this.peer)||void 0===e?void 0:e.hasAudioReceiver)}get withVideo(){var e;return Boolean(null===(e=this.peer)||void 0===e?void 0:e.hasVideoReceiver)}get localAudioTrack(){return this.peer?this.peer.localAudioTrack:null}get localVideoTrack(){return this.peer?this.peer.localVideoTrack:null}get peer(){return this.getRTCPeerById(this.activeRTCPeerId)}set peer(e){if(e){if(this.logger.debug("Set RTCPeer",e.uuid,e),this.rtcPeerMap.set(e.uuid,e),this.peer&&this.peer.instance&&this.callId!==e.uuid){const e=this.peer.uuid;this.logger.debug(">>> Stop old RTCPeer",e),this.hangup(e).catch(console.error),this.peer.detachAndStop()}this.logger.debug(">>> Replace RTCPeer with",e.uuid),this.activeRTCPeerId=e.uuid}else this.logger.warn("Invalid RTCPeer",e)}emit(e,...t){return super.emit(e,...t)}dialogParams(e){const{destinationNumber:t,attach:r,callerName:i,callerNumber:o,remoteCallerName:n,remoteCallerNumber:s,userVariables:a,screenShare:c,additionalDevice:d,fromFabricAddressId:l,pingSupported:u=!0}=this.options;return{dialogParams:{id:e,destinationNumber:t,attach:r,reattaching:r,callerName:i,callerNumber:o,remoteCallerName:n,remoteCallerNumber:s,userVariables:a,screenShare:c,additionalDevice:d,fromFabricAddressId:l,pingSupported:u,version:1e3}}}getRTCPeerById(e){return this.rtcPeerMap.get(e)}appendRTCPeer(e){return this.rtcPeerMap.set(e.uuid,e)}removeRTCPeer(e){return this.rtcPeerMap.delete(e)}setActiveRTCPeer(e){this.peer=this.getRTCPeerById(e)}setLocalStream(e){return new Promise((async(t,r)=>{try{if(!this.peer||!this.localStream)return r(new Error("Invalid RTCPeerConnection."));if(!Qn(e))return r(new Error("Invalid stream provided."));const i=this.localStream.getAudioTracks(),o=e.getAudioTracks();o.length<=0?this.logger.info("No audio track found in the stream provided. Audio will be unaffected."):(i.forEach((e=>{var t;es(e),null===(t=this.localStream)||void 0===t||t.removeTrack(e)})),o.forEach((e=>{var t;null===(t=this.localStream)||void 0===t||t.addTrack(e)})));const n=this.localStream.getVideoTracks(),s=e.getVideoTracks();s.length<=0?this.logger.info("No video track found in the stream provided. Video will be unaffected."):(n.forEach((e=>{var t;es(e),null===(t=this.localStream)||void 0===t||t.removeTrack(e)})),s.forEach((e=>{var t;null===(t=this.localStream)||void 0===t||t.addTrack(e)}))),await this.updateStream(this.localStream),this.logger.debug("setLocalStream done"),t(this.localStream)}catch(e){this.logger.error("setLocalStream",e),r(e)}}))}vertoExecute(e){return this.execute({method:this._getRPCMethod(),params:e})}_getRPCMethod(){const e=this.select(Hn.getAuthorization);return e&&kr(e)?"webrtc.verto":"video.message"}async _triggerNewRTCPeer(){this.logger.debug("_triggerNewRTCPeer Start");try{this.logger.debug("Build a new RTCPeer");const e=this._buildPeer("offer");this.logger.debug("Trigger start for the new RTCPeer!"),await e.start()}catch(e){this.logger.error("Error building new RTCPeer to promote/demote",e)}}updateCamera(e){return this.applyConstraintsAndRefreshStream({video:Object.assign({aspectRatio:16/9},e)})}updateMicrophone(e){return this.applyConstraintsAndRefreshStream({audio:e})}_getTransceiverDirection(e){let t="inactive";return"audio"===e&&(t=this.options.audio&&this.options.negotiateAudio?"sendrecv":this.options.audio&&!this.options.negotiateAudio?"sendonly":!this.options.audio&&this.options.negotiateAudio?"recvonly":"inactive"),"video"===e&&(t=this.options.video&&this.options.negotiateVideo?"sendrecv":this.options.video&&!this.options.negotiateVideo?"sendonly":!this.options.video&&this.options.negotiateVideo?"recvonly":"inactive"),t}manageSendersWithConstraints(e){return!1===e.audio&&(this.logger.info("Switching off the microphone"),this.stopOutboundAudio()),!1===e.video&&(this.logger.info("Switching off the camera"),this.stopOutboundVideo()),e.audio||e.video}updateConstraints(e,{attempt:t=0}={}){return t>1?Promise.reject(new Error("Failed to update constraints")):new Promise((async(r,i)=>{var o;try{if(!this.peer)return i(new Error("Invalid RTCPeerConnection."));if(!Object.keys(e).length)return i(new Error("Invalid audio/video constraints."));if(this.logger.debug("updateConstraints trying constraints",this.__uuid,e),!this.manageSendersWithConstraints(e))return this.logger.debug("Either `video` and `audio` (or both) constraints were set to `false` so their corresponding senders (if any) were stopped"),r();let n,s={};null===(o=this.localStream)||void 0===o||o.getTracks().forEach((t=>{var r;s[t.kind]=t.getConstraints(),void 0!==e[t.kind]&&(this.logger.debug("updateConstraints stop old tracks first?"),this.logger.debug("Track readyState:",t.kind,t.readyState),es(t),t.stop(),null===(r=this.localStream)||void 0===r||r.removeTrack(t))}));try{this.logger.info("updateConstraints with",e),n=await ds(e)}catch(e){return this.logger.error("Error updating device constraints:",e.name,e.message,e),this.logger.info("Restoring previous constraints",s),await this.updateConstraints(s,{attempt:t+1}),i(e)}this.logger.debug("updateConstraints done"),r(n)}catch(e){this.logger.error("updateConstraints",e),i(e)}}))}async updateStream(e){try{if(!this.peer)throw new Error("Invalid RTCPeerConnection.");const t=this.localVideoTrack,r=this.localAudioTrack;this.logger.debug("updateStream got stream",e),this.localStream||(this.localStream=new MediaStream);const i=e.getTracks();this.logger.debug(`updateStream got ${i.length} tracks`);for(const e of i)this.logger.debug("updateStream apply track: ",e),await this.handleTransceiverForTrack(e),this.emitDeviceUpdatedEvents({newTrack:e,prevAudioTrack:r,prevVideoTrack:t});this.logger.debug("updateStream done")}catch(e){throw this.logger.error("updateStream error",e),e}}async handleTransceiverForTrack(e){var t,r;if(!this.peer)return this.logger.error("Invalid RTCPeerConnection");const i=this.peer.instance.getTransceivers().find((({mid:t,sender:r,receiver:i})=>r.track&&r.track.kind===e.kind?(this.logger.debug("Found transceiver by sender"),!0):i.track&&i.track.kind===e.kind?(this.logger.debug("Found transceiver by receiver"),!0):null===t&&(this.logger.debug("Found disassociated transceiver"),!0)));if(i){this.logger.debug("handleTransceiverForTrack got transceiver",i.currentDirection,i.mid),(null===(t=i.sender.track)||void 0===t?void 0:t.id)!==e.id&&(await i.sender.replaceTrack(e),this.logger.debug(`handleTransceiverForTrack replaceTrack for ${e.kind}`));const r=this._getTransceiverDirection(e.kind);i.direction!==r&&(i.direction=r,this.logger.debug(`handleTransceiverForTrack set direction to ${r}`)),this.replaceOldTrack(e)}else{this.logger.debug("handleTransceiverForTrack no transceiver found; addTransceiver and start dancing!");const t=this._getTransceiverDirection(e.kind);this.peer.type="offer",null===(r=this.localStream)||void 0===r||r.addTrack(e),this.peer.instance.addTransceiver(e,{direction:t,streams:[this.localStream]})}}replaceOldTrack(e){if(!this.peer||!this.localStream)return this.logger.error("Invalid RTCPeerConnection");this.peer._detachAudioTrackListener(),this.peer._detachVideoTrackListener(),this.localStream.getTracks().forEach((t=>{var r;t.kind===e.kind&&t.id!==e.id&&(this.logger.debug("replaceOldTrack stop old track and apply new one"),es(t),null===(r=this.localStream)||void 0===r||r.removeTrack(t))})),this.localStream.addTrack(e),"audio"===e.kind&&(this.options.micId=e.getSettings().deviceId),"video"===e.kind&&(this.options.camId=e.getSettings().deviceId),this.peer._attachAudioTrackListener(),this.peer._attachVideoTrackListener()}emitDeviceUpdatedEvents({newTrack:e,prevAudioTrack:t,prevVideoTrack:r}){"audio"===e.kind?this.emit("microphone.updated",{previous:{deviceId:null==t?void 0:t.id,label:null==t?void 0:t.label},current:{deviceId:e.id,label:e.label}}):"video"===e.kind&&this.emit("camera.updated",{previous:{deviceId:null==r?void 0:r.id,label:null==r?void 0:r.label},current:{deviceId:e.id,label:e.label}})}async applyConstraintsAndRefreshStream(e){const t=await this.updateConstraints(e);t&&await this.updateStream(t)}runRTCPeerWorkers(e){const t=this.runWorker("vertoEventWorker",{worker:zs,initialState:{rtcPeerId:e}});if(this._myWorkers.push(t),!this.options.additionalDevice&&!this.options.screenShare){const t=this.runWorker("roomSubscribedWorker",{worker:Bs,initialState:{rtcPeerId:e}});this._myWorkers.push(t);const r=this.runWorker("promoteDemoteWorker",{worker:Hs,initialState:{rtcPeerId:e}});this._myWorkers.push(r)}}removeRTCWorkers(){for(const e of this._myWorkers)this.cancelWorker(e);this._myWorkers=[]}_destroyPeer(){this.peer&&(this.peer.detachAndStop(),this.removeRTCWorkers(),this.removeRTCPeer(this.peer.uuid),this.peer=void 0)}invite(){return pr({asyncCallable:async()=>new Promise((async(e,t)=>{await this._waitUntilSessionAuthorized(),this.direction="outbound",this.peer=this._buildPeer("offer");try{await this.peer.start(),e(this)}catch(e){this.logger.error("Invite error",e),this._destroyPeer(),t(e)}})),maxRetries:5,delayFn:mr({initialDelay:0}),expectedErrorHandler:e=>!this.requesting||![Bt,Ft].includes(e)||(this.logger.debug("Retrying verto.invite with new RTCPeer"),!1)})}answer(){return new Promise((async(e,t)=>{this.direction="inbound",this.peer||(this.peer=this._buildPeer("answer"));try{await this.peer.start(),e(this)}catch(e){this.logger.error("Answer error",e),t(e)}}))}async onLocalSDPReady(e){if(!e.instance.localDescription)throw this.logger.error("Missing localDescription",e),new Error("Invalid RTCPeerConnection localDescription");const{type:t,sdp:r}=e.instance.localDescription,i=this._mungeSDP(r);switch(this.logger.debug("LOCAL SDP \n",`Type: ${t}`,"\n\n",i),t){case"offer":return this._watchSessionAuth(),!this.resuming&&e.instance.remoteDescription?this.executeUpdateMedia(i,e.uuid):this.executeInvite(i,e.uuid);case"answer":return this.executeAnswer(i,e.uuid);default:return this.logger.error(`Unknown SDP type: '${t}' on call ${this.id}`)}}_closeWSConnection(){this._watchSessionAuth(),this.store.dispatch(Ur.sessionForceCloseAction())}_watchSessionAuth(){this.sessionAuthTask&&this.sessionAuthTask.cancel(),this.sessionAuthTask=this.runWorker("sessionAuthWorker",{worker:qs})}async resume(){var e;if(this.logger.warn(`[resume] Call ${this.id}`),null===(e=this.peer)||void 0===e?void 0:e.instance){const{connectionState:e}=this.peer.instance;this.logger.debug(`[resume] connectionState for ${this.id} is '${e}'`),"closed"!==e&&(this.resuming=!0,this.peer.restartIce())}}async executeInvite(e,t,r){const i=this.getRTCPeerById(t);if(!i||i.instance.remoteDescription&&!this.resuming)throw new Error(`RTCPeer '${t}' already has a remoteDescription. Invalid invite.`);"new"===this.state&&this.setState("requesting");try{const i=this.options.screenShare?{layout:this.options.layout,positions:this.options.positions}:{},o=Or(Object.assign(Object.assign(Object.assign({},this.dialogParams(t)),i),{sdp:e}));let n=[];n=this.options.screenShare?["video.room.screenshare"]:this.options.additionalDevice?["video.room.additionaldevice"]:this.getSubscriptions(),this.logger.debug("Subscribing to",n);const s=await this.vertoExecute({message:o,callID:t,node_id:null!=r?r:this.options.nodeId,subscribe:n});"requesting"===this.state&&this.setState("trying"),this.logger.debug("Invite response",s),this.resuming=!1}catch(e){throw this.setState("hangup"),e}}async executeAnswer(e,t,r){"new"===this.state&&this.setState("answering");try{const i=Wr(Object.assign(Object.assign({},this.dialogParams(t)),{sdp:e})),o=await this.vertoExecute({message:i,callID:t,node_id:null!=r?r:this.options.nodeId,subscribe:this.getSubscriptions()});this.logger.debug("Answer response",o),this.resuming=!1,this.setActiveRTCPeer(t)}catch(e){throw this.setState("hangup"),e}}async executeUpdateMedia(e,t){var r,i;try{const r=Lr(Object.assign(Object.assign({},this.dialogParams(t)),{sdp:e,action:"updateMedia"})),i=await this.vertoExecute({message:r,callID:t,node_id:this.nodeId});if(this.logger.debug("UpdateMedia response",i),!this.peer)return this.logger.error("Invalid RTCPeer to updateMedia");if(!i.sdp)return this.logger.error("UpdateMedia invalid SDP answer",i);await this.peer.onRemoteSdp(i.sdp)}catch(e){throw this.logger.error("UpdateMedia error",e),null===(i=null===(r=this.peer)||void 0===r?void 0:r._pendingNegotiationPromise)||void 0===i||i.reject(e),e}}async hangup(e){const t=null!=e?e:this.callId;if(!t)throw new Error("Invalid RTCPeer ID to hangup");try{const e=jr(this.dialogParams(t));await this.vertoExecute({message:e,callID:t,node_id:this.nodeId})}catch(e){this.logger.error("Hangup error:",e)}finally{if(t!==this.callId)return this.logger.warn("Prevent setState hangup",t,this.callId);this.setState("hangup")}}async hangupAll(){const e=this.callId;if(!e)throw new Error("Invalid RTCPeer ID to hangup");try{const t=jr(Object.assign({cause:"REJECT_ALL",causeCode:"825"},this.dialogParams(e)));await this.vertoExecute({message:t,callID:e,node_id:this.nodeId})}catch(e){this.logger.error("HangupAll error:",e)}finally{this.setState("hangup")}}async sendDigits(e){const t=this.callId;if(!t)throw new Error("Invalid RTCPeer ID to send DTMF");const r=Dr(Object.assign(Object.assign({},this.dialogParams(t)),{dtmf:e}));await this.vertoExecute({message:r,callID:t,node_id:this.nodeId})}doReinviteWithRelayOnly(){this.peer&&this.active&&this.peer.restartIceWithRelayOnly()}stopOutboundAudio(){this.peer&&this.active&&this.peer.stopTrackSender("audio")}restoreOutboundAudio(){this.peer&&this.active&&this.peer.restoreTrackSender("audio")}stopOutboundVideo(){this.peer&&this.active&&this.peer.stopTrackSender("video")}restoreOutboundVideo(){this.peer&&this.active&&this.peer.restoreTrackSender("video")}setState(e){switch(this.prevState=this.state,this.state=e,this.logger.trace(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this.emit(this.state,this),e){case"purge":case"destroy":this._finalize();break;case"hangup":this.setState("destroy")}}updateMediaOptions(e){this.logger.debug("updateMediaOptions",Object.assign({},e)),this.options=Object.assign(Object.assign({},this.options),e),this._checkDefaultMediaConstraints()}_mungeSDP(e){return(e=>{const t=/^a=candidate.*.local\ .*/;return e.split("\r\n").filter((e=>!t.test(e))).join("\r\n")})(e)}_checkDefaultMediaConstraints(){!0===this.options.video&&(this.options.video=Qs),!0===this.options.audio&&(this.options.audio=this.options.screenShare?Js:Gs)}_initPeer(){this.options.remoteSdp&&(this.peer=this._buildPeer("answer"))}_buildPeer(e){const t=new $s(this,e);return this.appendRTCPeer(t),this.runRTCPeerWorkers(t.uuid),t}_finalize(){this.rtcPeerMap.forEach((e=>{e.stop()})),this.rtcPeerMap.clear()}_upsertTransceiverByKind(e,t){if(!this.peer)return this.logger.error("Invalid RTCPeerConnection");let r=this.peer.instance.getTransceivers().find((e=>{var r,i;return(null===(r=e.sender.track)||void 0===r?void 0:r.kind)===t||(null===(i=e.receiver.track)||void 0===i?void 0:i.kind)===t}));if(r){if(r.direction===e)return void this.logger.info(`Transceiver ${t} has the same direction "${e}".`);r.direction=e,this.logger.info(`Updated ${t} transceiver to "${e}" mode.`)}else"inactive"!==e&&(this.peer.type="offer",r=this.peer.instance.addTransceiver(t,{direction:e}),this.logger.info(`Added ${t} transceiver in "${e}" mode.`));"stopped"===e||"inactive"===e?(this.peer.stopTrackReceiver(t),this.peer.stopTrackSender(t)):"sendonly"===e?this.peer.stopTrackReceiver(t):"recvonly"===e&&this.peer.stopTrackSender(t)}async updateMedia(e){var t,r,i,o,n,s;try{const{audio:n,video:s}=e;if(!this.peer)throw new Error("Invalid RTCPeerConnection");if(this.peer.isNegotiating)throw new Error("The peer is already negotiating the media!");const a=this.peer,c=new Promise(((e,t)=>{a._pendingNegotiationPromise={resolve:e,reject:t}})),d=["sendonly","sendrecv"].includes((null==n?void 0:n.direction)||""),l=["sendonly","sendrecv"].includes((null==s?void 0:s.direction)||""),u=["sendrecv","receive"].includes((null==n?void 0:n.direction)||""),h=["sendrecv","receive"].includes((null==s?void 0:s.direction)||"");if(this.updateMediaOptions(Object.assign(Object.assign(Object.assign(Object.assign({},n&&{audio:null!==(t=null==n?void 0:n.constraints)&&void 0!==t?t:d}),s&&{video:null!==(r=null==s?void 0:s.constraints)&&void 0!==r?r:l}),n&&{negotiateAudio:u}),s&&{negotiateVideo:h})),await this.applyConstraintsAndRefreshStream(Object.assign(Object.assign({},n&&{audio:null!==(i=null==n?void 0:n.constraints)&&void 0!==i?i:d}),s&&{video:null!==(o=null==s?void 0:s.constraints)&&void 0!==o?o:l})),n&&!d&&this._upsertTransceiverByKind(n.direction,"audio"),s&&!l&&this._upsertTransceiverByKind(s.direction,"video"),await this.peer.startNegotiation(),await c,!Ls({localSdp:this.peer.localSdp,remoteSdp:this.peer.remoteSdp,media:"audio"}))throw new Error("The server did not set the audio direction correctly");if(!Ls({localSdp:this.peer.localSdp,remoteSdp:this.peer.remoteSdp,media:"video"}))throw new Error("The server did not set the video direction correctly")}catch(e){throw null===(s=null===(n=this.peer)||void 0===n?void 0:n._pendingNegotiationPromise)||void 0===s||s.reject(e),e}}async setAudioDirection(e){if(!["sendonly","sendrecv","recvonly","inactive"].includes(e))throw new Error("Invalid direction specified");return this.updateMedia({audio:{direction:e}})}async setVideoDirection(e){if(!["sendonly","sendrecv","recvonly","inactive"].includes(e))throw new Error("Invalid direction specified");return this.updateMedia({video:{direction:e}})}async hold(){const e=Lr(Object.assign(Object.assign({},this.dialogParams(this.callId)),{action:"hold"}));await this.vertoExecute({message:e,callID:this.callId,node_id:this.nodeId})}async unhold(){const e=Lr(Object.assign(Object.assign({},this.dialogParams(this.callId)),{action:"unhold"}));this.vertoExecute({message:e,callID:this.callId,node_id:this.nodeId})}}const Zs=Ur.createAction("swJs/audioSetSpeakerAction"),ea=({speakerId:e})=>function*({instance:t,runSaga:r}){if("undefined"!=typeof Audio)try{const i=t.getAudioEl();let o;t.on("track",(function(n){"audio"===n.track.kind&&(o=r(ra,{track:n.track,element:i,speakerId:e,room:t}))})),t.once("destroy",(()=>{o?.cancel()}))}catch(e){Zt().error("audioElementSaga",e)}else Zt().warn("`Audio` is not supported on this environment.")};function*ta({element:e,room:t}){const r=Ur.getCustomSagaActionType(t.__uuid,Zs);for(;;){const i=yield xe([r]);try{if(i.type===r){const r=yield Le(Yn,e,i.payload);t.emit(`${$t}.speaker.updated`,i.payload),t.settleCustomSagaTrigger({dispatchId:i.dispatchId,payload:r,kind:"resolve"})}}catch(e){t.settleCustomSagaTrigger({dispatchId:i.dispatchId,payload:e,kind:"reject"}),Zt().error(e)}}}function*ra({track:e,element:t,speakerId:r,room:i}){(({track:e,element:t})=>{t.autoplay=!0,t.playsinline=!0,t.srcObject=new MediaStream([e]),e.addEventListener("ended",(()=>{t.srcObject=null,t.remove()}))})({track:e,element:t}),r&&Yn(t,r).catch((()=>{})),yield De(ta,{element:t,room:i})}const ia=function*(e){Zt().trace("videoManagerRoomsWorker started");const{instance:t,action:{type:r,payload:i}}=e,o={rooms:i.rooms.map((e=>ar(e)))};t.emit(ur(r),o),Zt().trace("videoManagerRoomsWorker ended")},oa=function*(e){Zt().trace("videoManagerRoomWorker started");const{instance:t,action:{type:r,payload:i}}=e;t.emit(ur(r),ar(i)),Zt().trace("videoManagerRoomWorker ended")},na=function*(e){Zt().trace("videoManagerWorker started");const{channels:{swEventChannel:t}}=e;function*r(t){const{type:r}=t;switch(r){case"video-manager.rooms.subscribed":yield De(ia,{action:t,...e});break;case"video-manager.room.added":case"video-manager.room.deleted":case"video-manager.room.ended":case"video-manager.room.started":case"video-manager.room.updated":yield De(oa,{action:t,...e});break;default:Zt().warn(`Unknown video-manager event: "${r}"`)}}for(;;){const e=yield xe(t,(e=>e.type.startsWith("video-manager.")));yield De(r,e)}Zt().trace("videoManagerWorker ended")};class sa extends Gi{constructor(e){super(e),this.runWorker("videoManagerWorker",{worker:na})}getSubscriptions(){const e=this.eventNames().map((e=>`video-manager.${e}`));return br(e)}}const aa={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,googAutoGainControl:!1},ca="sw-sdk-",da="sw-overlay-",la=e=>`${da}${e}`,ua=lr(class extends Ys{join(){return super.invite()}leave(){return super.hangup()}},{audioMute:io.audioMuteMember,audioUnmute:io.audioUnmuteMember,videoMute:io.videoMuteMember,videoUnmute:io.videoUnmuteMember,setMicrophoneVolume:io.setInputVolumeMember,setInputVolume:io.setInputVolumeMember,setInputSensitivity:io.setInputSensitivityMember}),ha=()=>{},ma="memberList.updated",pa=(e=>{const t=e.split(".")[0];return e.split(".").reduce(((e,r)=>(e.push(r),r===t&&e.push(Ut),e)),[]).join(".")})((({event:e,namespace:t})=>("string"==typeof e&&(e=(({namespace:e,event:t})=>!e||t.startsWith(e)?t:`${e}:${t}`)({event:e,namespace:t}),e=tr(e)),e))({event:ma})),ga=["video.room.joined","video.member.joined","video.member.left","video.member.updated"];function*fa({swEventChannel:e,instance:t}){const r=new Map;function*i(e){const i="video.room.joined"===e.type?e.payload.room_session.id:e.payload.room_session_id,o=(({action:e,memberList:t})=>{const r=(e=>"video.room.joined"===e.type?e.payload.room_session.members:[e.payload.member])(e);return r.forEach("video.member.left"===e.type?e=>{t.delete(e.id)}:e=>{t.set(e.id,e)}),Array.from(t.values())})({action:e,memberList:r});t.emit(pa,{room_session_id:i,members:o})}for(;;){const t=yield xe(e,(({type:e})=>ga.includes(e)));yield De(i,t)}}const va=function*({channels:{swEventChannel:e},instance:t}){const r=t.getSubscriptions();if(!(e=>e.some((e=>e.includes(ma))))(r))return;const{cleanup:i}=((e,t)=>{const r=(e=>br(ga).filter((t=>!e.includes(t))))(t);r.forEach((t=>{e.once(t,ha)}));const i=({members:t})=>{e.emit(ma,{members:t})};return e.on(pa,i),{cleanup:()=>{e.off(pa,i)}}})(t,r);yield De(fa,{swEventChannel:e,instance:t}),t.once("destroy",(()=>{i()}))},ya=function*(e){Zt().trace("childMemberJoinedWorker started");const{channels:t,instance:r,initialState:i,onDone:o,onFail:n}=e,{swEventChannel:s}=t,{parentId:a}=i;if(!a)throw new Error("Missing parentId for childMemberJoinedWorker");const c=yield xe(s,(e=>"video.member.joined"===e.type&&e.payload.member.parent_id===a)),{member:d}=c.payload;if(d?.parent_id){const e=yield We(Xi.getComponentsById);Object.values(e).find((e=>"memberId"in e&&e.memberId===d.parent_id))?(yield Oe(vi.upsert({id:r.callId,roomId:c.payload.room_id,roomSessionId:c.payload.room_session_id,memberId:d.id})),o?.()):n?.({error:new Error("Unknown parent_id")})}Zt().trace("childMemberJoinedWorker ended")},ba=function*(e){Zt().trace("videoStreamWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e;let a=o(i.stream.id);switch(a?a.setPayload(i):a=io.createRoomSessionStreamObject({store:t.store,payload:i}),n(i.stream.id,a),r){case"video.stream.started":t.emit("stream.started",a);break;case"video.stream.ended":t.emit("stream.ended",a),s(i.stream.id);break;default:Zt().warn(`Unknown video.stream event: "${r}"`)}Zt().trace("videoStreamWorker ended")},_a=function*(e){Zt().trace("videoRecordWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e;let a=o(i.recording.id);a?a.setPayload(i):a=io.createRoomSessionRecordingObject({store:t.store,payload:i}),n(i.recording.id,a);const c=ur(r);switch(r){case"video.recording.started":case"video.recording.updated":t.emit(c,a);break;case"video.recording.ended":t.emit(c,a),s(i.recording.id);break;default:Zt().warn(`Unknown video.stream event: "${r}"`)}Zt().trace("videoRecordWorker ended")},wa=function*(e){Zt().trace("videoPlaybackWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e;let a=o(i.playback.id);a?a.setPayload(i):a=io.createRoomSessionPlaybackObject({store:t.store,payload:i}),n(i.playback.id,a);const c=ur(r);switch(r){case"video.playback.started":case"video.playback.updated":t.emit(c,a);break;case"video.playback.ended":t.emit(c,a),s(i.playback.id);break;default:Zt().warn(`Unknown video.stream event: "${r}"`)}Zt().trace("videoPlaybackWorker ended")},ka=function*(e){Zt().trace("videoWorker started");const{channels:t,instance:r}=e,{swEventChannel:i}=t;function*o(t){const{type:i,payload:o}=t;switch(i){case"video.room.subscribed":return void(yield De(Mn.memberPositionWorker,{...e,instance:r,initialState:o}));case"video.playback.started":case"video.playback.updated":case"video.playback.ended":return void(yield De(wa,{action:t,...e}));case"video.recording.started":case"video.recording.updated":case"video.recording.ended":return void(yield De(_a,{action:t,...e}));case"video.stream.ended":case"video.stream.started":return void(yield De(ba,{action:t,...e}));case"video.room.audience_count":return void r.emit("room.audienceCount",o);case"video.member.talking":{const{member:e}=o;"talking"in e&&(r.emit("member.talking."+(e.talking?"started":"ended"),o),r.emit("member.talking."+(e.talking?"start":"stop"),o));break}case"video.layout.changed":r.currentLayoutEvent=t.payload}const n=ur(i,"video");r.emit(n,o)}const n=e=>e.type.startsWith("video.");for(;;){const e=yield xe(i,n);yield De(o,e)}Zt().trace("videoWorker ended")};class Sa extends Ys{_screenShareList=new Set;_audioEl;_overlayMap;_localVideoOverlay;get audioEl(){return this._audioEl}set overlayMap(e){this._overlayMap=e}get overlayMap(){return this._overlayMap}set localVideoOverlay(e){this._localVideoOverlay=e}get localVideoOverlay(){return this._localVideoOverlay}get screenShareList(){return Array.from(this._screenShareList)}_attachSpeakerTrackListener(){Xn()&&ks().then((e=>{e.on("removed",(async e=>{const t=this._audioEl.sinkId,r=e.changes.find((e=>{const r=e.payload.deviceId;return r===t||""===r&&"default"===t||"default"===r&&""===t}));if(r){this.emit("speaker.disconnected",{deviceId:r.payload.deviceId,label:r.payload.label}),await(this._audioEl.setSinkId?.(""));const e=await Cs("default");if(!e?.deviceId)return;this.emit("speaker.updated",{previous:{deviceId:r.payload.deviceId,label:r.payload.label},current:{deviceId:e.deviceId,label:e.label}})}}))}))}_finalize(){this._screenShareList.clear(),super._finalize()}async hangup(e){return this._screenShareList.forEach((e=>{e.leave()})),super.hangup(e)}leave(){return this.hangup()}attachPreConnectWorkers(){this.runWorker("memberListUpdated",{worker:va})}getAudioEl(){return this._audioEl||(this._audioEl=new Audio,this._attachSpeakerTrackListener()),this._audioEl}getMemberOverlay(e){return this.overlayMap.get(la(e))}async startScreenShare(e={}){return new Promise((async(t,r)=>{const{autoJoin:i=!0,audio:o=!1,video:n=!0,layout:s,positions:a}=e;try{const e=await ls({audio:!0===o?aa:o,video:n}),c={...this.options,screenShare:!0,recoverCall:!1,localStream:e,remoteStream:void 0,userVariables:{...this.options?.userVariables||{},memberCallId:this.callId,memberId:this.memberId},layout:s,positions:a},d=$i({store:this.store,Component:ua})(c);return e.getVideoTracks().forEach((e=>{e.addEventListener("ended",(()=>{d&&d.active&&d.leave()}))})),d.once("destroy",(()=>{d.emit("room.left"),this._screenShareList.delete(d)})),d.runWorker("childMemberJoinedWorker",{worker:ya,onDone:()=>t(d),onFail:r,initialState:{parentId:this.memberId}}),this._screenShareList.add(d),i?await d.join():t(d)}catch(e){this.logger.error("ScreenShare Error",e),r(e)}}))}updateSpeaker({deviceId:e}){const t=this.audioEl.sinkId;return this.once(`${$t}.speaker.updated`,(async e=>{const r=await Cs(t),i=await Cs(e),o=i?.deviceId===r?.deviceId;i?.deviceId&&!o&&this.emit("speaker.updated",{previous:{deviceId:r?.deviceId,label:r?.label},current:{deviceId:i.deviceId,label:i.label}})})),this.triggerCustomSaga(Zs(e))}}const Ca=lr(class extends Ys{join(){return super.invite()}leave(){return super.hangup()}},{audioMute:io.audioMuteMember,audioUnmute:io.audioUnmuteMember,videoMute:io.videoMuteMember,videoUnmute:io.videoUnmuteMember,setInputVolume:io.setInputVolumeMember,setMicrophoneVolume:io.setInputVolumeMember,setInputSensitivity:io.setInputSensitivityMember});class Ia extends Sa{_deviceList=new Set;_currentLayoutEvent;constructor(e){super(e),this.initWorker()}set currentLayoutEvent(e){this._currentLayoutEvent=e}get currentLayoutEvent(){return this._currentLayoutEvent}get currentLayout(){return this._currentLayoutEvent?.layout}get currentPosition(){return this._currentLayoutEvent?.layout.layers.find((e=>e.member_id===this.memberId))?.position}get deviceList(){return Array.from(this._deviceList)}get interactivityMode(){return this.select((({session:e})=>{const{authorization:t}=e;return t?.join_as??""}))}get permissions(){return this.select((({session:e})=>{const{authorization:t}=e;return t?.room?.scopes??[]}))}initWorker(){this.runWorker("videoWorker",{worker:ka})}getSubscriptions(){const e=this.eventNames().map((e=>`video.${String(e)}`));return br(e)}_finalize(){this._deviceList.clear(),super._finalize()}async hangup(e){return this._deviceList.forEach((e=>{e.leave()})),super.hangup(e)}join(){return super.invite()}getLayoutList(){return this.getLayouts()}getMemberList(){return this.getMembers()}async createScreenShareObject(e={}){return this.startScreenShare(e)}addCamera(e={}){const{autoJoin:t=!0,...r}=e;return this.addDevice({autoJoin:t,video:r})}addMicrophone(e={}){const{autoJoin:t=!0,...r}=e;return this.addDevice({autoJoin:t,audio:r})}async addDevice(e={}){return new Promise((async(t,r)=>{const{autoJoin:i=!0,audio:o=!1,video:n=!1}=e;if(!o&&!n)throw new TypeError("At least one of `audio` or `video` must be requested.");const s={...this.options,localStream:void 0,remoteStream:void 0,audio:o,video:n,additionalDevice:!0,recoverCall:!1,userVariables:{...this.options?.userVariables||{},memberCallId:this.callId,memberId:this.memberId}},a=$i({store:this.store,Component:Ca})(s);a.once("destroy",(()=>{a.emit("room.left"),this._deviceList.delete(a)}));try{return a.runWorker("childMemberJoinedWorker",{worker:ya,onDone:()=>t(a),onFail:r,initialState:{parentId:this.memberId}}),this._deviceList.add(a),i?await a.join():t(a)}catch(e){this.logger.error("RoomDevice Error",e),r(e)}}))}}const Ta=lr(Ia,{audioMute:io.audioMuteMember,audioUnmute:io.audioUnmuteMember,videoMute:io.videoMuteMember,videoUnmute:io.videoUnmuteMember,deaf:io.deafMember,undeaf:io.undeafMember,setInputVolume:io.setInputVolumeMember,setOutputVolume:io.setOutputVolumeMember,setMicrophoneVolume:io.setInputVolumeMember,setSpeakerVolume:io.setOutputVolumeMember,setInputSensitivity:io.setInputSensitivityMember,removeMember:io.removeMember,removeAllMembers:io.removeAllMembers,getMembers:io.getMembers,getLayouts:io.getLayouts,setLayout:io.setLayout,setPositions:io.setPositions,setMemberPosition:io.setMemberPosition,hideVideoMuted:io.hideVideoMuted,showVideoMuted:io.showVideoMuted,getRecordings:io.getRecordings,startRecording:io.startRecording,getPlaybacks:io.getPlaybacks,play:io.play,setHideVideoMuted:io.setHideVideoMuted,getMeta:io.getMeta,setMeta:io.setMeta,updateMeta:io.updateMeta,deleteMeta:io.deleteMeta,getMemberMeta:io.getMemberMeta,setMemberMeta:io.setMemberMeta,updateMemberMeta:io.updateMemberMeta,deleteMemberMeta:io.deleteMemberMeta,promote:io.promote,demote:io.demote,getStreams:io.getStreams,startStream:io.startStream,lock:io.lock,unlock:io.unlock,setRaisedHand:io.setRaisedHand,setPrioritizeHandraise:io.setPrioritizeHandraise}),Ea=e=>e instanceof Ia;function Pa(e){this.message=e}(Pa.prototype=new Error).name="InvalidCharacterError";var Ma="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Pa("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,o=0,n=0,s="";i=t.charAt(n++);~i&&(r=o%4?64*r+i:i,o++%4)?s+=String.fromCharCode(255&r>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};function Ra(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Ma(e).replace(/(.)/g,(function(e,t){var r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(e){return Ma(t)}}function Aa(e){this.message=e}function xa(e,t){if("string"!=typeof e)throw new Aa("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(Ra(e.split(".")[r]))}catch(e){throw new Aa("Invalid token specified: "+e.message)}}(Aa.prototype=new Error).name="InvalidTokenError";const Oa=()=>{if(window&&window.sessionStorage)return window.sessionStorage},ja=e=>{let t="";try{const r=xa(e);t=r?.r??""}catch(r){try{t=xa(e,{header:!0}).typ||""}catch{t=""}}const r=Boolean(t);return{authStateKey:r&&`as-${t}`,protocolKey:r&&`pt-${t}`,callIdKey:r&&`ci-${t}`}},La="ci-SAT",Da=function*(e){Zt().debug("wsClientWorker started");const{channels:t,initialState:r,instance:i}=e,{swEventChannel:o}=t,{handleIncomingInvite:n}=r;function*s(e){i.emit(e.type,e.payload)}function*a(e){n(e.payload.params)}const c=e=>"webrtc.message"===e.type&&"verto.invite"===e.payload.method;try{for(;;){const e=yield xe(o,(()=>!0));yield De(s,e),c(e)&&(Zt().debug("Receiving a call over WebSocket",e),yield De(a,e))}}finally{Zt().trace("wsClientWorker ended")}};class Wa extends qi{_payload;constructor(e){super(e),this._payload=e.payload}get id(){return this._payload.member.member_id}get callId(){return this._payload.member.call_id}get nodeId(){return this._payload.member.node_id}get memberId(){return this.id}get roomSessionId(){return this._payload.room_session_id}get roomId(){return this._payload.room_id}get parentId(){return this._payload.member.parent_id}get subscriberId(){return this._payload.member.subscriber_id}get addressId(){return this._payload.member.address_id}get name(){return this._payload.member.name}get type(){return this._payload.member.type}get requestedPosition(){return this._payload.member.requested_position}get currentPosition(){return this._payload.member.current_position}get meta(){return this._payload.member.meta}get handraised(){return this._payload.member.handraised}get talking(){return this._payload.member.talking}get audioMuted(){return this._payload.member.audio_muted}get videoMuted(){return this._payload.member.video_muted}get deaf(){return this._payload.member.deaf}get visible(){return this._payload.member.visible}get inputVolume(){return this._payload.member.input_volume}get outputVolume(){return this._payload.member.output_volume}get inputSensitivity(){return this._payload.member.input_sensitivity}get echoCancellation(){return this._payload.member.echo_cancellation}get autoGain(){return this._payload.member.auto_gain}get noiseSuppression(){return this._payload.member.noise_suppression}setPayload(e){const t={...this._payload,...e,member:{...this._payload.member,...e.member}};this._payload=t}}const Va=e=>$i({store:e.store,Component:Wa})(e),Na=function*(e){Zt().trace("callLeftWorker started");const{action:{payload:t},instance:r,instanceMap:i}=e,{room_session_id:o}=t;i.getAll().forEach((([e,t])=>{t instanceof Wa&&t.roomSessionId===o&&i.remove(e)})),r.emit("call.left",t),r.emit("room.left",t),Zt().trace("callLeftWorker ended")},$a=function*(e){Zt().trace("fabricMemberWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e,a=i.member.member_id;let c=o(a);if(c||"member.talking"===r||(c=Va({store:t.store,payload:i})),c&&c.setPayload(i),n(a,c),r.startsWith("member.updated.")){const e=cr(r);t.emit(e,i)}switch(r){case"member.joined":case"member.updated":case"member.talking":t.emit(r,i);break;case"member.left":t.emit(r,i),s(a)}Zt().trace("fabricMemberWorker ended")};class Ua{_flags;constructor(e){this._flags=e}get on(){return this._flags.some((e=>!e.endsWith(".off")))}get off(){return this._flags.some((e=>!e.endsWith(".on")))}}class za{_flags;_memberType;_muteAudio;_muteVideo;_deaf;_raisehand;constructor(e,t){this._flags=e,this._memberType=t}get muteAudio(){return this._muteAudio=this._muteAudio??new Ua(this._flags.filter((e=>e===this._memberType||e===`${this._memberType}.mute`||e.startsWith(`${this._memberType}.mute.audio`)))),this._muteAudio}get muteVideo(){return this._muteVideo=this._muteVideo??new Ua(this._flags.filter((e=>e===this._memberType||e===`${this._memberType}.mute`||e.startsWith(`${this._memberType}.mute.video`)))),this._muteVideo}get microphoneVolume(){return this._flags.some((e=>e===this._memberType||e===`${this._memberType}.microphone`||e.startsWith(`${this._memberType}.microphone.volume`)))}get microphoneSensitivity(){return this._flags.some((e=>e===this._memberType||e===`${this._memberType}.microphone`||e.startsWith(`${this._memberType}.microphone.sensitivity`)))}get speakerVolume(){return this._flags.some((e=>e===this._memberType||e===`${this._memberType}.speaker`||e.startsWith(`${this._memberType}.speaker.volume`)))}get deaf(){return this._deaf=this._deaf??new Ua(this._flags.filter((e=>e===this._memberType||e.startsWith(`${this._memberType}.deaf`)))),this._deaf}get raisehand(){return this._raisehand=this._raisehand??new Ua(this._flags.filter((e=>e===this._memberType||e.startsWith(`${this._memberType}.raisehand`)))),this._raisehand}get position(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.position`)))}get meta(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.meta`)))}get remove(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.remove`)))}get audioFlags(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.audioflags.set`)))}}class Ba{_flags;_self;_member;_vmutedHide;_lock;constructor(e){this._flags=e}_buildMemberCapability(e){return new za(this._flags.filter((t=>t.startsWith(e))),e)}get self(){return this._self=this._self??this._buildMemberCapability("self"),this._self}get member(){return this._member=this._member??this._buildMemberCapability("member"),this._member}get end(){return this._flags.some((e=>"end"===e))}get setLayout(){return this._flags.some((e=>e.startsWith("layout")))}get sendDigit(){return this._flags.some((e=>e.startsWith("digit")))}get vmutedHide(){return this._vmutedHide=this._vmutedHide??new Ua(this._flags.filter((e=>e.startsWith("vmuted")))),this._vmutedHide}get lock(){return this._lock=this._lock??new Ua(this._flags.filter((e=>e.startsWith("lock")))),this._lock}get device(){return this._flags.some((e=>"device"===e))}get screenshare(){return this._flags.some((e=>"screenshare"===e))}}const Fa=e=>({...e,id:e.member_id}),Ha=e=>({...Fa(e),updated:e.updated.map((e=>"member_id"===e?"id":e))}),qa=function*(e){Zt().trace("callJoinWorker started");const{action:t,instanceMap:r,instance:i}=e,{payload:o}=t,{get:n,set:s}=r;var a;yield De(Mn.memberPositionWorker,{...e,initialState:(a=o,{...a,room:{...a.room_session,members:a.room_session.members.map(Fa)},room_session:{...a.room_session,members:a.room_session.members.map(Fa)}}),dispatcher:function*(t,r){const i=ur(t,"video"),o={...r,member:{...r.member,member_id:r.member.id}};yield De($a,{...e,action:{type:i,payload:o}})}}),o.room_session.members?.forEach((e=>{let t=n(e.member_id);t?t.setPayload({member:e,room_id:o.room_id,room_session_id:o.room_session_id}):t=Va({store:i.store,payload:{member:e,room_id:o.room_id,room_session_id:o.room_session_id}}),s(e.member_id,t)})),i.member=n(o.member_id),i.capabilities=new Ba(o.capabilities);const c={...o,capabilities:i.capabilities};i.emit("call.joined",c),Zt().trace("callJoinWorker ended")},Ka=function*(e){const{action:t,channels:{swEventChannel:r},instance:i}=e,o=t.payload.call_id,n=t.payload.room_session_id;function*s(t){const{type:o,payload:n}=t;switch(o){case"call.joined":break;case"call.left":return yield Le(Na,{...e,action:t}),!0;case"call.updated":i.emit(o,n),i.emit("room.updated",n);break;case"call.play":case"call.connect":case"call.room":i.emit(o,n);break;case"member.joined":case"member.left":{yield De($a,{...e,action:t});const i=(e=>{return{type:`video.${e.type}`,payload:(t=e.payload,{room_session_id:t.room_session_id,room_id:t.room_id,member:Fa(t.member)})};var t})(t);yield Oe(r,i);break}case"member.updated":{const e=(e=>{return{type:`video.${e.type}`,payload:(t=e.payload,{room_session_id:t.room_session_id,room_id:t.room_id,member:Ha(t.member)})};var t})(t);yield Oe(r,e);break}case"layout.changed":{i.currentLayoutEvent=t.payload,i.emit(o,n);const e=(e=>({type:`video.${e.type}`,payload:e.payload}))(t);yield Oe(r,e);break}case"member.talking":yield De($a,{...e,action:t});break;default:Zt().warn("Got an unknown fabric event",t)}return!1}Zt().debug(`callSegmentWorker started for: callId ${o}, roomSessionId ${n}`),yield De(qa,{...e,action:t});const a=e=>{const{type:t,payload:r}=e;return!(!(t.startsWith("call.")||t.startsWith("member.")||t.startsWith("layout."))||(!("call_id"in r)||o!==r.call_id)&&n!==r.room_session_id)};for(;;){const e=yield xe(r,a),t=yield De(s,e);if(yield(c=t,Ae(Pe,c)))return}var c},Ga=function*(e){Zt().trace("fabricWorker started");const{channels:{swEventChannel:t},instance:r}=e;function*i(t){const{type:i,payload:o}=t;switch(i){case"call.joined":if(!r.selfMember){const e=Va({store:r.store,payload:{member:t.payload.room_session.members.find((e=>e.member_id===t.payload.member_id)),room_id:t.payload.room_id,room_session_id:t.payload.room_session_id}});r.selfMember=e}yield De(Ka,{...e,instance:r,action:t});break;case"call.state":r.emit(i,o)}}let o=!1;const n=e=>"call.state"===e.type||"call.joined"===e.type&&(!!o||e.payload.call_id===e.payload.origin_call_id&&(o=!0,!0));for(;;){const e=yield xe(t,n);yield De(i,e)}Zt().trace("fabricWorker ended")},Ja=(e,t)=>!e?.memberId||e.memberId===t.member.id,Qa={audioMute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteAudio.off:this.capabilities?.member.muteAudio.off))throw new Ei("Missing audio mute capability")},audioUnmute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteAudio.on:this.capabilities?.member.muteAudio.on))throw new Ei("Missing audio unmute capability")},videoMute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteVideo.off:this.capabilities?.member.muteVideo.off))throw new Ei("Missing video mute capability")},videoUnmute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteVideo.on:this.capabilities?.member.muteVideo.on))throw new Ei("Missing video unmute capability")},deaf:function(e){if(!(Ja(e,this)?this.capabilities?.self.deaf.on:this.capabilities?.member.deaf.on))throw new Ei("Missing deaf capability")},undeaf:function(e){if(!(Ja(e,this)?this.capabilities?.self.deaf.off:this.capabilities?.member.deaf.off))throw new Ei("Missing undeaf capability")},removeMember:function(e){if(!e?.memberId)throw new TypeError('Invalid or missing "memberId" argument');const t=this.capabilities?.member.remove;if(!t)throw new Ei("Missing remove member capability")},setRaisedHand:function(e){const{raised:t=!0}=e||{},r=Ja(e,this),i=r?this.capabilities?.self.raisehand.on:this.capabilities?.member.raisehand.on,o=r?this.capabilities?.self.raisehand.off:this.capabilities?.member.raisehand.off;if(t&&!i)throw new Ei("Missing raisehand capability");if(!t&&!o)throw new Ei("Missing lowerhand capability")},setLayout:function(){if(!this.capabilities?.setLayout)throw new Ei("Missing setLayout capability")},setInputVolume:function(e){if(!(Ja(e,this)?this.capabilities?.self?.microphoneVolume:this.capabilities?.member?.microphoneVolume))throw new Ei("Missing setInputVolume capability");if(e.volume<-50||e.volume>50)throw new RangeError("The volume ranges from -50 to 50")},setOutputVolume:function(e){if(!(Ja(e,this)?this.capabilities?.self?.speakerVolume:this.capabilities?.member?.speakerVolume))throw new Ei("Missing setOutputVolume capability");if(e.volume<-50||e.volume>50)throw new RangeError("The volume ranges from -50 to 50")},setInputSensitivity:function(e){if(!(Ja(e,this)?this.capabilities?.self.microphoneSensitivity:this.capabilities?.member.microphoneSensitivity))throw new Ei("Missing setInputSensitivity capability");if(e.value<0||e.value>100)throw new RangeError("The sensitivity value ranges from 0 to 100")},setPositions:function(e){if(e.positions&&!Object.keys(e.positions).length)throw new TypeError("Invalid positions specified");if(!(Object.keys(e.positions).some((e=>["self",`${this.memberId}`].includes(e)))?this.capabilities?.self.position:this.capabilities?.member.position))throw new Ei("Missing setPositions capability")},lock:function(){if(!this.capabilities?.lock.on)throw new Ei("Missing lock capability")},unlock:function(){if(!this.capabilities?.lock.off)throw new Ei("Missing unlock capability")},setAudioFlags:function(e){if(!(Ja(e,this)?this.capabilities?.self.audioFlags:this.capabilities?.member.audioFlags))throw new Ei("Missing audio flags capability");const{echoCancellation:t,autoGain:r,noiseSuppression:i}=e||{};if(void 0===t&&void 0===r&&void 0===i)throw new TypeError("Invalid parameters: you must specify at least one of `echoCancellation`, `autoGain`, or `noiseSuppression`")}};class Xa extends Sa{_self;_member;_currentLayoutEvent;_capabilities;constructor(e){super(e),this.initWorker()}get memberId(){return this._member?.memberId}dialogParams(e){const t=super.dialogParams(e);return t.dialogParams.attach=this.options.attach||this.resuming,t.dialogParams.reattaching=this.options.attach||this.resuming,t}set currentLayoutEvent(e){this._currentLayoutEvent=e}get currentLayoutEvent(){return this._currentLayoutEvent}get currentLayout(){return this._currentLayoutEvent?.layout}get currentPosition(){return this._currentLayoutEvent?.layout.layers.find((e=>e.member_id===this.memberId))?.position}get capabilities(){return this._capabilities}set capabilities(e){this._capabilities=e}get selfMember(){return this._self}set selfMember(e){this._self=e}set member(e){this._member=e}get member(){return this._member}initWorker(){this.runWorker("fabricWorker",{worker:Ga}),this.runWorker("makeAudioElement",{worker:ea({speakerId:this.options.speakerId})})}async join(){return this.options.attach&&(this.options.prevCallId=Oa()?.getItem(La)??void 0,this.logger.debug(`Tying to reattach to previuos call? ${!!this.options.prevCallId} - prevCallId: ${this.options.prevCallId}`)),super.invite()}executeAction(e,t={}){const{method:r,channel:i,memberId:o,extraParams:n={}}=e,s=o&&"all"!==o?this.instanceMap.get(o):this.member;if(!s)throw new Error(o&&"all"!==o?`Member ${o} not found`:"No target member available");return this.execute({method:r,params:{...i&&{channels:[i]},self:{member_id:this.selfMember?.id,call_id:this.selfMember?.callId,node_id:this.selfMember?.nodeId},target:{member_id:"all"===o?o:s.id,call_id:s.callId,node_id:s.nodeId},...n}},t)}async resume(){if(this.logger.warn(`[resume] Call ${this.id}`),this.peer?.instance){const{connectionState:e}=this.peer.instance;this.logger.debug(`[resume] connectionState for ${this.id} is '${e}'`),["closed","failed","disconnected"].includes(e)&&(this.resuming=!this.selfMember,this.peer.restartIce())}}async start(){return new Promise((async(e,t)=>{try{this.once("room.subscribed",(t=>{Oa()?.setItem(La,t.call_id),e()})),this.once("destroy",(()=>{Oa()?.removeItem(La)})),await this.join()}catch(e){this.logger.error("WSClient call start",e),t(e)}}))}async audioMute(e){return this.executeAction({method:"call.mute",channel:"audio",memberId:e?.memberId})}async audioUnmute(e){return this.executeAction({method:"call.unmute",channel:"audio",memberId:e?.memberId})}async videoMute(e){return this.executeAction({method:"call.mute",channel:"video",memberId:e?.memberId})}async videoUnmute(e){return this.executeAction({method:"call.unmute",channel:"video",memberId:e?.memberId})}async deaf(e){return this.executeAction({method:"call.deaf",memberId:e?.memberId})}async undeaf(e){return this.executeAction({method:"call.undeaf",memberId:e?.memberId})}async getLayouts(){return this.executeAction({method:"call.layout.list"},{transformResolve:e=>({layouts:e.layouts})})}async getMembers(){return this.executeAction({method:"call.member.list"},{transformResolve:e=>({members:e.members})})}async removeMember(e){return this.executeAction({method:"call.member.remove",memberId:e.memberId})}async setRaisedHand(e){const{raised:t=!0,memberId:r}=e||{};return this.executeAction({method:t?"call.raisehand":"call.lowerhand",memberId:r})}async setLayout(e){return this.executeAction({method:"call.layout.set",extraParams:{layout:e.name,positions:e.positions}})}async setInputVolume(e){return this.executeAction({method:"call.microphone.volume.set",memberId:e.memberId,extraParams:{volume:e.volume}})}async setOutputVolume(e){return this.executeAction({method:"call.speaker.volume.set",memberId:e.memberId,extraParams:{volume:e.volume}})}async setInputSensitivity(e){return this.executeAction({method:"call.microphone.sensitivity.set",memberId:e.memberId,extraParams:{sensitivity:e.value}})}async setPositions(e){const t=[];if(Object.entries(e.positions).forEach((([e,r])=>{const i="self"===e?this.member:this.instanceMap.get(e);i&&t.push({target:{member_id:i.id,call_id:i.callId,node_id:i.nodeId},position:r})})),!t.length)throw new Error("Invalid targets");return this.execute({method:"call.member.position.set",params:{self:{member_id:this.selfMember?.id,call_id:this.selfMember?.callId,node_id:this.selfMember?.nodeId},targets:t}})}async lock(){return this.executeAction({method:"call.lock"})}async unlock(){return this.executeAction({method:"call.unlock"})}async setAudioFlags(e){const{memberId:t,...r}=e;return this.executeAction({method:"call.audioflags.set",memberId:t,extraParams:dr(r)})}}const Ya=e=>e instanceof Xa;class Za{id;_domElement;_status;constructor(e){this.id=e.id,this._status="hidden"}get userId(){return this.id.split(da)[1]}get domElement(){return this._domElement}set domElement(e){Zt().debug("Setting domElement for ",this.id),this._domElement=e}get status(){return this._status}set status(e){this._status=e}hide(){if(!this.domElement)return Zt().warn("Missing overlay to hide");this.domElement.style.opacity="0",this.status="hidden"}show(){if(!this.domElement)return Zt().warn("Missing overlay to show");this.domElement.style.opacity="1",this.status="visible"}}class ec extends Za{_mirrored;_room;constructor(e){super(e),this._mirrored=e.mirrorLocalVideoOverlay,this._room=e.room,this.fabricMemberVideoMutedHandler=this.fabricMemberVideoMutedHandler.bind(this),this.videoMemberVideoMutedHandler=this.videoMemberVideoMutedHandler.bind(this),this.attachListeners()}get userId(){return this.id.split(ca)[1]}get mirrored(){return this._mirrored}attachListeners(){Ya(this._room)?this._room.on("member.updated.videoMuted",this.fabricMemberVideoMutedHandler):Ea(this._room)&&this._room.on("member.updated.videoMuted",this.videoMemberVideoMutedHandler)}detachListeners(){Ya(this._room)?this._room.off("member.updated.videoMuted",this.fabricMemberVideoMutedHandler):Ea(this._room)&&this._room.off("member.updated.videoMuted",this.videoMemberVideoMutedHandler)}memberVideoMutedHandler(e,t){try{e===this._room.memberId&&(t?this.hide():this.show())}catch(e){Zt().error("Error handling videoMuted in LocalVideoOverlay",e)}}fabricMemberVideoMutedHandler(e){this.memberVideoMutedHandler(e.member.member_id,e.member.video_muted)}videoMemberVideoMutedHandler(e){this.memberVideoMutedHandler(e.member.id,e.member.video_muted)}setMediaStream(e){if(!this.domElement)return Zt().warn("Missing local overlay to set the stream");const t=this.domElement.querySelector("video");t&&(t.srcObject=e)}setMirror(e=this._mirrored){if(!this.domElement||!this.domElement.firstChild)return Zt().warn("Missing local overlay to set the mirror");const t=this.domElement.firstChild;t.style.transform=e?"scale(-1, 1)":"scale(1, 1)",t.style.webkitTransform=e?"scale(-1, 1)":"scale(1, 1)",this._mirrored=e}}const tc=()=>{const e=document.createElement("video");return e.muted=!0,e.autoplay=!0,e.playsInline=!0,e.addEventListener("pause",(()=>{e.play().catch((t=>{Zt().error("Video Element Paused",e,t)}))})),e},rc=({x:e,y:t,width:r,height:i})=>({top:`${t}%`,left:`${e}%`,width:`${r}%`,height:`${i}%`}),ic=({location:e})=>{const{top:t,left:r,width:i,height:o}=rc(e),n=document.createElement("div");return n.style.position="absolute",n.style.overflow="hidden",n.style.top=t,n.style.left=r,n.style.width=i,n.style.height=o,n},oc=({location:e,element:t})=>{const{top:r,left:i,width:o,height:n}=rc(e);return t.style.top=r,t.style.left=i,t.style.width=o,t.style.height=n,t},nc=({video:e,rootElement:t,paddingWrapper:r})=>{const i=function(e,t=0,r){let i=null,o=null;const n=function(){i&&(clearTimeout(i),o=null,i=null)},s=function(){if(!t)return e.apply(this,arguments);const s=this,a=arguments,c=r&&!i;return n(),o=function(){e.apply(s,a)},i=setTimeout((function(){if(i=null,!c){const e=o;return o=null,null==e?void 0:e()}}),t),c&&o?o():void 0};return s.cancel=n,s.flush=function(){const e=o;n(),e&&e()},s}((({width:t,height:i})=>{const o=e.videoHeight/e.videoWidth*100;if(r){const n=i/t*100;r.style.paddingBottom=`${n>o?o:n}%`,r.style.width=((t,r)=>{const i=e.videoWidth/e.videoHeight;return i>t/r?"100%":r*i+"px"})(t,i)}}),100),o=new ResizeObserver((e=>{e.forEach((e=>{if(e.contentBoxSize){const{inlineSize:t,blockSize:r}=Array.isArray(e.contentBoxSize)?e.contentBoxSize[0]:e.contentBoxSize;i({width:t,height:r})}else e.contentRect&&i({width:e.contentRect.width,height:e.contentRect.height})}))})),n=()=>{i({width:t.clientWidth,height:t.clientHeight})};return{start:()=>{o.observe(t),e.addEventListener("resize",n)},stop:()=>{o.disconnect(),e.removeEventListener("resize",n)}}},sc=async e=>{try{const{room:t,rootElement:r,applyLocalVideoOverlay:i=!0,applyMemberOverlay:o=!0,mirrorLocalVideoOverlay:n=!0}=e;let s=!1;const a=new Map,c=b();let d;r?d=r:(d=document.createElement("div"),d.id=`rootElement-${c}`);const l=(e=>`${ca}${e}`)(c),u=new ec({id:l,mirrorLocalVideoOverlay:n,room:t});i&&a.set(l,u);const h=(e=>{const{applyLocalVideoOverlay:t,applyMemberOverlay:r,overlayMap:i,localVideoOverlay:o,mirrorLocalVideoOverlay:n,rootElement:s}=e;return async e=>{Zt().debug("Process layout.changed");try{const{layout:a,memberId:c,localStream:d}=e,{layers:l=[]}=a,u=s.querySelector(".mcuLayers"),h=document.createDocumentFragment(),m=new Set;if(t){const e=l.find((({member_id:e})=>e===c)),t=o.id;let r=o.domElement;if(m.add(t),e){if(r)Zt().debug("Update local video overlay"),oc({location:e,element:r});else{Zt().debug("Build local video overlay"),r=ic({location:e}),r.id=t;const i=tc();i.srcObject=d,i.disablePictureInPicture=!0,i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.objectFit="cover",r.appendChild(i),o.domElement=r,n&&o.setMirror()}const i=d.getVideoTracks().filter((e=>e.enabled&&"live"===e.readyState)).length>0;i&&e.visible?(o.setMediaStream(d),o.show()):o.hide(),h.appendChild(r)}else Zt().warn("Local video overlay location not found"),o.status="hidden",r&&o.hide()}r&&l.forEach((e=>{const t=e.member_id;if(!t)return;const r=la(t);m.add(r);let o=i.get(r);if(o&&o.domElement)Zt().debug("Update an overlay for ",t),oc({location:e,element:o.domElement});else{Zt().debug("Build an overlay for ",t),o=new Za({id:r}),i.set(r,o);const n=ic({location:e});n.id=`${r}-${b()}`,o.domElement=n}e.visible?o.show():o.hide(),h.appendChild(o.domElement)})),i.forEach(((e,t)=>{m.has(t)||(e.domElement&&e.domElement.parentNode&&e.domElement.parentNode.removeChild(e.domElement),i.delete(t))})),u&&(u.innerHTML="",u.appendChild(h))}catch(e){Zt().error("Layout Changed Error",e)}}})({applyLocalVideoOverlay:i,applyMemberOverlay:o,overlayMap:a,localVideoOverlay:u,mirrorLocalVideoOverlay:n,rootElement:d}),m=e=>{t.peer?.hasVideoSender&&t.localStream?h({layout:e.layout,localStream:t.localStream,memberId:t.memberId}):u.hide()},p=e=>{Zt().debug("Received layout.changed - videoTrack",s),s&&m(e)},g=async e=>{s=!0,await ac({applyLocalVideoOverlay:i,applyMemberOverlay:o,rootElement:d,track:e});const r=t.currentLayoutEvent;r&&m(r)},f=t.peer?.remoteVideoTrack;f&&await g(f);const v=async function(e){"video"===e.track.kind&&await g(e.track)},y=()=>{(e=>{for(;e.firstChild;)e.removeChild(e.firstChild)})(d),a.clear(),t.overlayMap=a,(Ya(t)||Ea(t))&&(t.off("track",v),t.off("layout.changed",p),t.off("destroy",y)),u.detachListeners()};return(Ya(t)||Ea(t))&&(t.on("track",v),t.on("layout.changed",p),t.once("destroy",y)),t.overlayMap=a,t.localVideoOverlay=u,{element:d,overlayMap:a,localVideoOverlay:u,unsubscribe:y}}catch(e){throw Zt().error("Unable to build the video element"),e}},ac=async e=>{try{const{applyLocalVideoOverlay:t,applyMemberOverlay:r,track:i,rootElement:o}=e,n=tc();if((({track:e,element:t})=>{t.srcObject=new MediaStream([e]),e.addEventListener("ended",(()=>{t.srcObject=null,t.remove()}))})({element:n,track:i}),n.style.width="100%",n.style.maxHeight="100%",o.querySelector(".mcuContent"))return void Zt().debug("MCU Content already there");const s=document.createElement("div");s.style.position="absolute",s.style.top="0",s.style.left="0",s.style.right="0",s.style.bottom="0",s.appendChild(n);const a=document.createElement("div");a.classList.add("paddingWrapper"),a.style.paddingBottom="56.25%",a.style.position="relative",a.style.width="100%",a.appendChild(s);let c=null;(t||r)&&(c=document.createElement("div"),c.classList.add("mcuLayers"),c.style.display="none",a.appendChild(c));const d=document.createElement("div");d.classList.add("mcuContent"),d.style.position="relative",d.style.width="100%",d.style.height="100%",d.style.margin="0 auto",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.appendChild(a),o.style.width="100%",o.style.height="100%",o.appendChild(d),Zt().debug("MCU readyState 1 >>",n.readyState),n.readyState===HTMLMediaElement.HAVE_NOTHING&&(Zt().debug("Wait for the MCU to be ready"),await(({element:e})=>new Promise((t=>{e.addEventListener("canplay",(function r(){e.removeEventListener("canplay",r),t()})),e.addEventListener("resize",(function r(){e.removeEventListener("resize",r),t()}))})))({element:n})),Zt().debug("MCU is ready..");const l=nc({rootElement:o,video:n,paddingWrapper:a});l.start(),i.addEventListener("ended",(()=>{l&&l.stop()})),c&&(c.style.display="block")}catch(e){Zt().error("Handle video track error",e)}};class cc extends Ki{_videoManager;_chat;_pubSub;get rooms(){return{makeRoomObject:e=>{const{rootElement:t,applyLocalVideoOverlay:r=!0,applyMemberOverlay:i=!0,mirrorLocalVideoOverlay:o=!0,stopCameraWhileMuted:n=!0,stopMicrophoneWhileMuted:s=!0,...a}=e,c=[];c.push(ea({speakerId:a.speakerId}));const d=(l={...a,store:this.store,customSagas:c},$i({store:l.store,customSagas:l.customSagas,Component:Ta})(l));var l;if(t)try{sc({applyLocalVideoOverlay:r,applyMemberOverlay:i,mirrorLocalVideoOverlay:o,room:d,rootElement:t})}catch(e){this.logger.error("Unable to build the video element automatically")}return d.on("room.subscribed",(e=>{const t=e.room_session.members?.find((e=>e.id===d.memberId));if(t?.audio_muted)try{d.stopOutboundAudio()}catch(e){this.logger.error("Error handling audio_muted",e)}if(t?.video_muted)try{d.stopOutboundVideo()}catch(e){this.logger.error("Error handling video_muted",e)}})),s&&d.on("member.updated.audio_muted",(({member:e})=>{try{e.id===d.memberId&&"audio_muted"in e&&(e.audio_muted?d.stopOutboundAudio():d.restoreOutboundAudio())}catch(e){this.logger.error("Error handling audio_muted",e)}})),n&&d.on("member.updated.video_muted",(({member:e})=>{try{e.id===d.memberId&&"video_muted"in e&&(e.video_muted?d.stopOutboundVideo():d.restoreOutboundVideo())}catch(e){this.logger.error("Error handling video_muted",e)}})),d}}}get chat(){return this._chat||(this._chat=tn.createBaseChatObject({store:this.store})),this._chat}get pubSub(){return this._pubSub||(this._pubSub=pn.createBasePubSubObject({store:this.store})),this._pubSub}get videoManager(){return this._videoManager||(this._videoManager=(e=>{const t=$i({store:e.store,Component:sa})(e);return new Proxy(t,{get:(e,t,r)=>"_eventsNamespace"===t?"":"eventChannel"===t?"video-manager.rooms":Reflect.get(e,t,r)})})(this.options)),this._videoManager}reauthenticate(e){this.store.dispatch(Ur.reauthAction({token:e}))}}const dc="function"==typeof CloseEvent?CloseEvent:class{constructor(e,t={}){this.type=e,Nt(this,"code"),Nt(this,"reason"),Nt(this,"wasClean"),this.code=void 0===t.code?0:t.code,this.reason=void 0===t.reason?"":t.reason,this.wasClean=void 0!==t.wasClean&&t.wasClean}};class lc extends pi{options;WebSocketConstructor=WebSocket;CloseEventConstructor=dc;agent="@signalwire/js/browser/3.29.1";tokenTyp;constructor(e){let t={};try{t=xa(e.token,{header:!0})}catch(e){}super({...e,host:t?.ch||e.host}),this.options=e,this.tokenTyp=t.typ??"VRT"}get allowReattach(){return!1!==this.options?.reattach&&(this.isVRT()||this.isSAT())}async retrieveRelayProtocol(){if(!this.allowReattach)return"";const{protocolKey:e}=ja(this.options.token);return e?(this.logger.trace("Search protocol for",e),Oa()?.getItem(e)??""):""}async persistRelayProtocol(){if(!this.allowReattach)return;const{protocolKey:e}=ja(this.options.token);e&&(this.logger.trace("Persist protocol",e,this.relayProtocol),Oa()?.setItem(e,this.relayProtocol))}removeRelayProtocol(){const{protocolKey:e}=ja(this.options.token);e&&(this.logger.debug("Remove protocol",e,this.relayProtocol),Oa()?.removeItem(e))}removePrevCallId(){const{callIdKey:e}=ja(this.options.token);e&&(this.logger.debug("Remove Call",e),Oa()?.removeItem(e))}async retrieveSwAuthorizationState(){const{authStateKey:e}=ja(this.options.token);return e?Oa()?.getItem(e)??"":""}async persistSwAuthorizationState(e){if(!this.allowReattach)return;const{authStateKey:t}=ja(this.options.token);t&&(this.logger.trace("Persist auth state",t,e),Oa()?.setItem(t,e))}removeSwAuthorizationState(){const{authStateKey:e}=ja(this.options.token);e&&(this.logger.trace("Remove auth state",e),Oa()?.removeItem(e))}_onSocketClose(e){if("disconnected"===this.status){const{protocolKey:e,authStateKey:t,callIdKey:r}=ja(this.options.token);this.logger.debug("Cleaning up storage"),e&&(this.logger.debug("Remove protocolKey",e),Oa()?.removeItem(e)),t&&(this.logger.debug("Remove authStateKey",t),Oa()?.removeItem(t)),r&&(this.logger.debug("Remove callIdKey",r),Oa()?.removeItem(r))}super._onSocketClose(e)}isVRT(){return"VRT"===this.tokenTyp}isSAT(){return"SAT"===this.tokenTyp}}const uc=e=>{const t={...e,emitter:Ui()},r=zi({userOptions:t,SessionConstructor:lc});return $i({store:r,Component:cc})(t)},hc=["subscribe","publish","getMessages","getMembers","getMemberState","getAllowedChannels","setMemberState"];var mc=/*#__PURE__*/Object.freeze({__proto__:null,Client:function(e){const t=uc(e),r={_session:t,disconnect:()=>t.disconnect()};return new Proxy(t.chat,{get:(e,i,o)=>i in r?r[i]:hc.includes(i)?(e=>async(...r)=>(await t.connect(),t.chat[e](...r)))(i):Reflect.get(e,i,o)})},ChatMember:In,ChatMessage:Cn});const pc=["getAllowedChannels","subscribe","publish"];var gc=/*#__PURE__*/Object.freeze({__proto__:null,PubSubMessage:pn.PubSubMessage,Client:function(e){const t=uc(e),r={_session:t,disconnect:()=>t.disconnect()};return new Proxy(t.pubSub,{get:(e,i,o)=>i in r?r[i]:pc.includes(i)?(e=>async(...r)=>(await t.connect(),t.pubSub[e](...r)))(i):Reflect.get(e,i,o)})}});async function fc(e,t,r,i,o){const n=await pr({asyncCallable:()=>fetch(e,t),maxRetries:r,validator:e=>{if(!e.ok&&e.status>=500)throw new Ti(e.status,e.statusText)},delayFn:hr({initialDelay:i,variation:o})});if(!n.ok){if(401===n.status)throw new Ii(n.status,"Unauthorized");let e;try{e=await n.json()}catch(e){}const t=e?.errors?JSON.stringify(e.errors):"Not Found";throw new Ti(n.status,t,e)}try{n.parsedBody=await n.json()}catch(e){}return n}const vc=({baseUrl:e,maxApiRequestRetries:t=0,apiRequestRetriesDelay:r=0,apiRequestRetriesDelayIncrement:i=0,timeout:o=3e4,...n},s=fc)=>async(a,c)=>{const d={...c?.body?{"Content-Type":"application/json"}:{},...n.headers,...c?.headers},l=yc({...n,...c,headers:d});let u;if(o){const e=new AbortController;l.signal=e.signal,u=setTimeout((()=>{e.abort()}),o)}try{return{body:(await s(bc({path:a,baseUrl:e,searchParams:c?.searchParams}),l,t,r,i)).parsedBody}}catch(e){throw e}finally{u&&clearTimeout(u)}},yc=e=>Object.entries(e).reduce(((e,[t,r])=>{return"body"===t?{...e,body:(i=r,"string"==typeof i?i:JSON.stringify(i))}:null!=r?{...e,[t]:r}:e;var i}),{}),bc=({path:e,baseUrl:t,searchParams:r})=>{const i=new URL(e,t);return r&&Object.entries(r).forEach((([e,t])=>{null!=t&&i.searchParams.append(e,t)})),i.toString()};function _c(e,t){const r=async e=>{if(!e)return Promise.resolve(void 0);const{body:r}=await t(e);return _c(r,t)};return{data:e.data,self:async()=>{const{self:t}=e.links;return r(t)},nextPage:async()=>{const{next:t}=e.links;return r(t)},prevPage:async()=>{const{prev:t}=e.links;return r(t)},firstPage:async()=>{const{first:t}=e.links;return r(t)},hasNext:Boolean(e.links.next),hasPrev:Boolean(e.links.prev)}}class wc{options;httpClient;constructor(e){this.options=e,this.httpClient=vc({baseUrl:`https://${this.httpHost}`,headers:{Authorization:`Bearer ${this.options.token}`},maxApiRequestRetries:this.options.maxApiRequestRetries,apiRequestRetriesDelay:this.options.apiRequestRetriesDelay,apiRequestRetriesDelayIncrement:this.options.apiRequestRetriesDelayIncrement})}get fetch(){return this.httpClient}get httpHost(){let e={};try{e=xa(this.options.token,{header:!0})}catch(e){}const t=this.options.host||e?.ch;return t?`fabric.${t.split(".").splice(1).join(".")}`:"fabric.signalwire.com"}async getAddress(e){let t="/api/fabric/addresses";var r;(r=e)&&"name"in r?t=`${t}?name=${e.name}`:(e=>e&&"id"in e)(e)&&(t=`${t}/${e.id}`);const{body:i}=await this.httpClient(t);if((e=>e&&"data"in e)(i)){if(!i.data[0])throw new Ti(404,"Not Found");return i.data[0]}return i}async getAddresses(e){const{type:t,displayName:r,pageSize:i,sortBy:o,sortOrder:n}=e||{},s=new URLSearchParams;t&&s.append("type",t),r&&s.append("display_name",r),i&&s.append("page_size",i.toString()),o&&s.append("sort_by",o),n&&s.append("sort_order",n);const a=function(e,t){const r=t.toString();return r?`${e}?${r}`:e}("/api/fabric/addresses",s);Zt().debug(`[getAddresses] query URL ${a}`);const{body:c}=await this.httpClient(a);return _c(c,this.httpClient)}async registerDevice(e){const{deviceType:t,deviceToken:r}=e,{body:i}=await this.httpClient("/subscriber/devices",{method:"POST",body:{device_type:t,device_token:r}});return i}async unregisterDevice(e){const{id:t}=e,r=`/subscriber/devices/${t}`;await this.httpClient(r,{method:"DELETE"})}async getSubscriberInfo(){const{body:e}=await this.httpClient("/api/fabric/subscriber/info");return e}}class kc{options;_client;_pendingInvites={};_handlers={};constructor(e){this.options=e,this._client=e.client}_buildNotification(e){const t=async t=>new Promise(((r,i)=>{delete this._pendingInvites[e.callID];try{const i=this.options.buildInboundCall(e,t);i.answer(),r(i)}catch(e){i(e)}})),r=()=>(delete this._pendingInvites[e.callID],this.options.executeVertoBye(e.callID,e.nodeId));return{invite:{details:e,accept:e=>t(e),reject:()=>r()}}}setNotificationHandlers(e){this._handlers.all=e.all,(e.pushNotification&&this._handlers.all!=e.pushNotification||!e.pushNotification)&&(this._handlers.pushNotification=e.pushNotification),(e.websocket&&this._handlers.all!=e.websocket||!e.websocket)&&(this._handlers.websocket=e.websocket)}handleIncomingInvite(e){if(e.callID in this._pendingInvites)return void this._client.logger.debug(`skiping nottification for pending invite to callID: ${e.callID}`);if(this._pendingInvites[e.callID]=e,!this._handlers.all&&!this._handlers[e.source])return void this._client.logger.warn("Skiping nottification due to no listeners");const t=this._buildNotification(e);this._handlers.all?.(t);const r=this._handlers[e.source];r?.(t)}}class Sc extends lc{options;connectVersion=Er;constructor(e){super(e),this.options=e}get signature(){if(this._rpcConnectResult){const{authorization:e}=this._rpcConnectResult;return e.jti}}async _checkTokenExpiration(){}async reauthenticate(){if(this.logger.debug("Session Reauthenticate",{ready:this.ready,expired:this.expired}),!this.ready||this.expired)return this.connect();const e={project:this._rpcConnectResult.authorization.project_id,jwt_token:this.options.token};try{const t=await this.execute(Mr(e));this._rpcConnectResult={...this._rpcConnectResult,...t}}catch(e){throw e}}async execute(e){return pr({asyncCallable:async()=>(await this._waitConnected(),super.execute(e)),maxRetries:this.options.maxApiRequestRetries,delayFn:hr({initialDelay:this.options.apiRequestRetriesDelay,variation:this.options.apiRequestRetriesDelayIncrement}),expectedErrorHandler:t=>(Zt().warn(t),!!Sr(e)||!(!(e=>{var t;return wr(e)&&"webrtc.verto"==e.method&&"verto.invite"===(null==(t=e.params)?void 0:t.message.method)})(e)||[Bt,Ft].includes(t))&&(Zt().debug("skip verto.invite retry on error:",t),!0))})}}class Cc extends Ki{wsClientOptions;_incomingCallManager;_disconnected=!1;constructor(e){super((e=>{const t=zi({userOptions:e,SessionConstructor:Sc});return{...e,store:t}})(e)),this.wsClientOptions=e,this._incomingCallManager=new kc({client:this,buildInboundCall:this.buildInboundCall.bind(this),executeVertoBye:this.executeVertoBye.bind(this)}),this.runWorker("wsClientWorker",{worker:Da,initialState:{handleIncomingInvite:e=>{this._incomingCallManager.handleIncomingInvite({source:"websocket",...e})}}}),this.initializeSessionConnectionPool()}makeFabricObject(e){const{rootElement:t,applyLocalVideoOverlay:r=!0,applyMemberOverlay:i=!0,stopCameraWhileMuted:o=!0,stopMicrophoneWhileMuted:n=!0,mirrorLocalVideoOverlay:s=!0,...a}=e,c=(e=>{const t=$i({store:e.store,Component:Xa})(e);return new Proxy(t,{get(e,t,r){if("string"==typeof t&&t in Qa){const r=e,i=r[t];if("function"==typeof i)return async function(...e){const o=Qa[t];return o&&o.apply(r,e),i.apply(r,e)}}return Reflect.get(e,t,r)}})})({...a,store:this.store});if(t)try{sc({applyLocalVideoOverlay:r,applyMemberOverlay:i,mirrorLocalVideoOverlay:s,room:c,rootElement:t})}catch(e){this.logger.error("Unable to build the video element automatically")}return c.on("room.subscribed",(e=>{const t=e.room_session.members?.find((e=>e.member_id===c.memberId));if(t?.audio_muted)try{c.stopOutboundAudio()}catch(e){this.logger.error("Error handling audio_muted",e)}if(t?.video_muted)try{c.stopOutboundVideo()}catch(e){this.logger.error("Error handling video_muted",e)}})),n&&c.on("member.updated.audioMuted",(({member:e})=>{try{e.member_id===c.memberId&&"audio_muted"in e&&(e.audio_muted?c.stopOutboundAudio():c.restoreOutboundAudio())}catch(e){this.logger.error("Error handling audio_muted",e)}})),o&&c.on("member.updated.videoMuted",(({member:e})=>{try{e.member_id===c.memberId&&"video_muted"in e&&(e.video_muted?c.stopOutboundVideo():c.restoreOutboundVideo())}catch(e){this.logger.error("Error handling video_muted",e)}})),c}buildOutboundCall(e){let t=!1,r=!1;if(e.to){const[i,o]=e.to.split("?");if(!i)throw new Error("Invalid destination address");"video"===new URLSearchParams(o).get("channel")&&(t=!0,r=!0)}const i=this.makeFabricObject({audio:e.audio??!0,video:e.video??t,negotiateAudio:e.negotiateAudio??!0,negotiateVideo:e.negotiateVideo??r,rootElement:e.rootElement||this.wsClientOptions.rootElement,applyLocalVideoOverlay:e.applyLocalVideoOverlay,applyMemberOverlay:e.applyMemberOverlay,stopCameraWhileMuted:e.stopCameraWhileMuted,stopMicrophoneWhileMuted:e.stopMicrophoneWhileMuted,mirrorLocalVideoOverlay:e.mirrorLocalVideoOverlay,watchMediaPackets:!1,destinationNumber:e.to??"",nodeId:e.nodeId,attach:e.attach??!1,disableUdpIceServers:e.disableUdpIceServers||!1,userVariables:e.userVariables||this.wsClientOptions.userVariables,fromFabricAddressId:e.fromFabricAddressId});return i.once("destroy",(()=>{this.logger.debug("RTC Connection Destroyed"),i.destroy()})),this.session.once("session.disconnected",(()=>{this.logger.debug("Session Disconnected"),i.destroy(),this.destroy()})),i.attachPreConnectWorkers(),i}buildInboundCall(e,t){const r=this.makeFabricObject({audio:t.audio??!0,video:t.video??!0,negotiateAudio:t.negotiateAudio??!0,negotiateVideo:t.negotiateVideo??!0,rootElement:t.rootElement||this.wsClientOptions.rootElement,applyLocalVideoOverlay:!0,applyMemberOverlay:!0,stopCameraWhileMuted:!0,stopMicrophoneWhileMuted:!0,watchMediaPackets:!1,nodeId:e.nodeId,remoteSdp:e.sdp,prevCallId:e.callID,disableUdpIceServers:t.disableUdpIceServers||!1,userVariables:t.userVariables||this.wsClientOptions.userVariables});return r.once("destroy",(()=>{this.logger.debug("RTC Connection Destroyed"),r.destroy()})),this.session.once("session.disconnected",(()=>{this.logger.debug("Session Disconnected"),r.destroy(),this.destroy()})),r.attachPreConnectWorkers(),r}async executeVertoBye(e,t){try{return await this.execute({method:"webrtc.verto",params:{callID:e,node_id:t,message:jr({cause:"USER_BUSY",causeCode:"17",dialogParams:{callID:e}})}})}catch(t){throw this.logger.warn("The call is not available anymore",e),t}}async executeVertoSubscribe(e,t){try{return await this.execute({method:"webrtc.verto",params:{callID:e,node_id:t,subscribe:[],message:Vr({sessid:e,eventChannel:[]})}})}catch(t){throw this.logger.warn("The call is not available anymore",e),t}}disconnect(){return new Promise(((e,t)=>{this._disconnected&&e(),this.session.once("session.disconnected",(()=>{this.destroy(),e(),this._disconnected=!0})),super.disconnect()}))}async dial(e){return new Promise((async(t,r)=>{try{Oa()?.removeItem(La),t(this.buildOutboundCall(e))}catch(e){this.logger.error("Unable to connect and dial a call",e),r(e)}}))}async reattach(e){return new Promise((async(t,r)=>{try{t(this.buildOutboundCall({...e,attach:!0}))}catch(e){this.logger.error("Unable to connect and reattach a call",e),r(e)}}))}handlePushNotification(e){const{incomingCallHandler:t}=e;return this._incomingCallManager.setNotificationHandlers({pushNotification:t}),new Promise((async(t,r)=>{const{decrypted:i,type:o}=e;"call_invite"!==o&&(this.logger.warn("Unknown notification type",e),r("Unknown notification type")),this.logger.debug("handlePushNotification",e);const{params:{params:n},node_id:s}=i;try{try{await this.executeVertoSubscribe(n.callID,s)}catch(e){this.logger.warn("Verto Subscribe",e)}this._incomingCallManager.handleIncomingInvite({source:"pushNotification",nodeId:s,...n}),t({resultType:"inboundCall"})}catch(e){r(e)}}))}updateToken(e){return new Promise(((t,r)=>{this.session.once("session.auth_error",(e=>{r(e)})),this.session.once("session.connected",(()=>{t()})),this.store.dispatch(Ur.reauthAction({token:e}))}))}async online({incomingCallHandlers:e}){return(e.all||e.pushNotification)&&this.logger.warn("Make sure the device is not registered to receive Push Notifications while it is online"),this._incomingCallManager.setNotificationHandlers(e),this.execute({method:"subscriber.online",params:{}})}offline(){return this._incomingCallManager.setNotificationHandlers({}),this.execute({method:"subscriber.offline",params:{}})}initializeSessionConnectionPool(){this.runWorker("sessionConnectionPoolWorker",{worker:Ks,initialState:{poolSize:1,iceCandidatePoolSize:10}})}}const Ic=(()=>{let e=null;return t=>(e||(e=new Promise((async(r,i)=>{try{const i={maxApiRequestRetries:10,apiRequestRetriesDelay:300,apiRequestRetriesDelayIncrement:100,...t},o=new Cc(i),n=new wc(i),s=e=>()=>{throw new Error(`This version Conversation.${e} is unsupported by the backend. Use @signalwire/client instead.`)};await o.connect(),r({registerDevice:n.registerDevice.bind(n),unregisterDevice:n.unregisterDevice.bind(n),getSubscriberInfo:n.getSubscriberInfo.bind(n),disconnect:async()=>{await o.disconnect(),e=null},online:o.online.bind(o),offline:o.offline.bind(o),dial:o.dial.bind(o),reattach:o.reattach.bind(o),handlePushNotification:o.handlePushNotification.bind(o),updateToken:o.updateToken.bind(o),address:{getAddresses:n.getAddresses.bind(n),getAddress:n.getAddress.bind(n)},conversation:{getConversations:s("getConversations"),getMessages:s("getMessages"),getConversationMessages:s("getConversationMessages"),subscribe:s("subscribe"),sendMessage:s("sendMessage"),join:s("join")},chat:{getMessages:s("getMessages"),subscribe:s("subscribe"),sendMessage:s("sendMessage"),join:s("join")},on:o.on.bind(o),off:o.off.bind(o),__httpClient:n,__wsClient:o})}catch(e){i(e)}})).catch((t=>{throw e=null,t}))),e)})();var Tc=/*#__PURE__*/Object.freeze({__proto__:null,isFabricRoomSession:Ya,SignalWire:Ic});const Ec={aspectRatio:{ideal:16/9}},Pc=e=>new Promise((async(t,r)=>{const{audio:i=!0,video:o=!0,iceServers:n,rootElementId:s,applyLocalVideoOverlay:a=!0,autoJoin:c=!1,stopCameraWhileMuted:d=!0,stopMicrophoneWhileMuted:l=!0,speakerId:u,...h}=e,m=uc({...h});if(await m.connect(),!m)return;let p;if(s){const e=document.getElementById(s);e?p=e:(p=document.body,Zt().warn(`We couldn't find an element with id: ${s}: using 'document.body' instead.`))}const g=m.rooms.makeRoomObject({audio:i,video:!0===o?Ec:o,negotiateAudio:!0,negotiateVideo:!0,iceServers:n,rootElement:p,applyLocalVideoOverlay:a,stopCameraWhileMuted:d,stopMicrophoneWhileMuted:l,speakerId:u});g.once("destroy",(()=>{g.emit("room.left"),m.disconnect()}));const f=()=>new Promise((async(e,t)=>{try{g.once("room.subscribed",(t=>{e(g)})),await g.join()}catch(e){Zt().error("Join",e),m.disconnect(),t(e)}})),v=new Proxy(g,{get:(e,t,r)=>"join"===t?f:Reflect.get(e,t,r)});if(c)try{await v.join(),t(v)}catch(e){r(e)}else t(v)})),Mc=["audioMute","audioUnmute","deaf","getLayouts","getMembers","getRecordings","hideVideoMuted","leave","removerMember","restoreOutboundAudio","restoreOutboundVideo","setInputSensitivity","setInputVolume","setLayout","setPositions","setMemberPosition","setOutputVolume","showVideoMuted","startRecording","stopOutboundAudio","stopOutboundVideo","undeaf","videoMute","videoUnmute","setMicrophoneVolume","setSpeakerVolume","getMeta","setMeta","updateMeta","deleteMeta","getMemberMeta","setMemberMeta","updateMemberMeta","deleteMemberMeta","promote","demote","lock","unlock"],Rc=["member.joined","layout.changed"],Ac=()=>{};var xc=/*#__PURE__*/Object.freeze({__proto__:null,RoomSession:function(e){const{audio:t=!0,video:r=!0,iceServers:i,rootElement:o,applyLocalVideoOverlay:n=!0,mirrorLocalVideoOverlay:s=!1,stopCameraWhileMuted:a=!0,stopMicrophoneWhileMuted:c=!0,speakerId:d,destinationNumber:l,localStream:u,watchMediaPackets:h,watchMediaPacketsTimeout:m,disableUdpIceServers:p=!1,...g}=e;["audio","video"].forEach((t=>{t in e&&Zt().warn(`The '${t}' parameter on the RoomSession constructor is deprecated. Set it on the '.join()' function instead.`)}));const f=!1!==e?.reattach,{callIdKey:v}=ja(g.token),y={joined:({call_id:e})=>{f&&v&&Oa()?.setItem(v,e)},init:()=>{f&&_.on("room.subscribed",y.joined),_.options.prevCallId=y.getPrevCallId()},destroy:()=>{f&&(_.off("room.subscribed",y.joined),v&&Oa()?.removeItem(v))},getPrevCallId:()=>{if(f&&v)return Oa()?.getItem(v)??void 0}},b=uc(g),_=b.rooms.makeRoomObject({negotiateAudio:!0,negotiateVideo:!0,iceServers:i,rootElement:o,applyLocalVideoOverlay:n,mirrorLocalVideoOverlay:s,stopCameraWhileMuted:a,stopMicrophoneWhileMuted:c,speakerId:d,destinationNumber:l,localStream:u,watchMediaPackets:h,watchMediaPacketsTimeout:m,prevCallId:y.getPrevCallId(),disableUdpIceServers:p});_.once("destroy",(()=>{_.emit("room.left",{reason:_.leaveReason}),y.destroy(),b.disconnect()})),b.session.once("session.disconnected",(()=>{_.destroy()}));const w={join:e=>new Promise((async(i,o)=>{try{_.attachPreConnectWorkers(),await b.connect();const n=e?.audio??t,s=e?.video??r,a=b._sessionAuthorization;if(Zt().debug("getJoinMediaParams authorization?",a),a&&"video"===a.type){const t=(e=>{const{authorization:t,audio:r=!0,video:i=!0,sendAudio:o,sendVideo:n,receiveAudio:s,receiveVideo:a}=e;Zt().debug("getJoinMediaParams options",{...e});const{audio_allowed:c,video_allowed:d,join_as:l}=t,u="member"===(l??"member"),h=u&&"both"===c,m=u&&"both"===d,p="none"!==c,g="none"!==d,f=Boolean(o??r),v=Boolean(n??i),y=Boolean(s??r),b=Boolean(a??i);return!h&&f&&Zt().info("Not allowed to send audio on this room. Default values will be used."),!m&&v&&Zt().info("Not allowed to send video on this room. Default values will be used."),!p&&y&&Zt().info("Not allowed to receive video from the room. Default values will be used."),!g&&b&&Zt().info("Not allowed to receive video from the room. Default values will be used."),{mustSendAudio:h&&f,mustSendVideo:m&&v,mustRecvAudio:p&&y,mustRecvVideo:g&&b}})({authorization:a,sendAudio:Boolean(n),sendVideo:Boolean(s),...e});if(!Object.values(t).some(Boolean))return b.disconnect(),o(new Error(`Invalid arguments to join the room. The token used has join_as: '${a.join_as}'. \n${JSON.stringify(e,null,2)}\n`));Zt().debug("Set mediaOptions",t),_.updateMediaOptions({audio:!!t.mustSendAudio&&(n||!0),video:!!t.mustSendVideo&&(s||!0),negotiateAudio:t.mustRecvAudio,negotiateVideo:t.mustRecvVideo})}_.once("room.subscribed",(()=>{i(_)})),y.init(),Rc.forEach((e=>_.once(e,Ac))),await _.join()}catch(e){Zt().error("RoomSession Join",e),b.disconnect(),o(e)}}))};return new Proxy(_,{get(e,t,r){if(t in w)return w[t];if(!e.active&&Mc.includes(t))throw new Error(`Tried to access the property/method "${t}" before the room was connected. Please call roomSession.join() first.`);return Reflect.get(e,t,r)}})},createRoomObject:Pc,joinRoom:e=>Pc({...e,autoJoin:!0}),createClient:uc,isVideoRoomSession:Ea}),Oc=/*#__PURE__*/Object.freeze({__proto__:null,getDevices:ms,getCameraDevices:()=>ms("camera"),getMicrophoneDevices:()=>ms("microphone"),getSpeakerDevices:ps,getDevicesWithPermissions:us,getCameraDevicesWithPermissions:()=>us("camera"),getMicrophoneDevicesWithPermissions:()=>us("microphone"),getSpeakerDevicesWithPermissions:()=>us("speaker"),checkPermissions:ns,checkCameraPermissions:ss,checkMicrophonePermissions:as,checkSpeakerPermissions:cs,requestPermissions:async e=>{try{const t=await ds(e);Zn(t)}catch(e){throw e}},createDeviceWatcher:ws,createCameraDeviceWatcher:()=>ws({targets:["camera"]}),createMicrophoneDeviceWatcher:()=>ws({targets:["microphone"]}),createSpeakerDeviceWatcher:ks,supportsMediaDevices:Kn,supportsGetUserMedia:()=>"function"==typeof Gn().getUserMedia,supportsGetDisplayMedia:()=>"function"==typeof Gn().getDisplayMedia,getUserMedia:ds,getDisplayMedia:ls,enumerateDevices:is,enumerateDevicesByKind:os,getSupportedConstraints:Jn,supportsMediaOutput:Xn,setMediaElementSinkId:Yn,stopStream:Zn,stopTrack:es,createMicrophoneAnalyzer:async e=>{const t=await(async e=>{if(Ss(e))return e;let t;return t="string"==typeof e?{audio:{deviceId:e}}:{audio:e},ds(t)})(e);if(!t)throw new Error("Failed to get the audio stream");const r=new St,i=new(window.AudioContext||window.webkitAudioContext),o=(e=>{const t=e.createAnalyser();return t.fftSize=64,t.minDecibels=-90,t.maxDecibels=-10,t.smoothingTimeConstant=.85,t})(i);let n,s;try{i.createMediaStreamSource(t).connect(o)}catch(e){throw new Error("No audio track found")}t.getAudioTracks().forEach((e=>{e.addEventListener("ended",(()=>{r.emit("destroyed","disconnected")}))}));const a=()=>{try{const e=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(e);const t=e.reduce(((e,t)=>e+t),0)/20;s!==t&&(s=t,r.emit("volumeChanged",Math.min(s,100))),n=requestAnimationFrame(a)}catch(e){r.emit("destroyed","error")}};n=requestAnimationFrame(a);const c=()=>{n&&cancelAnimationFrame(n),"closed"!==i.state&&i.close().catch((e=>{Zt().error("Error closing the AudioContext",e)})),Ss(e)||t.getTracks().forEach((e=>e.stop())),r.emit("destroyed",null),r.removeAllListeners()};return new Proxy(r,{get:(e,t,r)=>"destroy"===t?c:Reflect.get(e,t,r)})}});e.Chat=mc,e.Fabric=Tc,e.LocalVideoOverlay=ec,e.PubSub=gc,e.SignalWire=Ic,e.UserOverlay=Za,e.Video=xc,e.WebRTC=Oc,e.buildVideoElement=sc,e.isFabricRoomSession=Ya,Object.defineProperty(e,"__esModule",{value:!0})}));
30
+ function(){return function(){return!0}}(),se=function(){},ae=function(e){return e},ce=function(e,t){G(e,t),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(t).forEach((function(r){e[r]=t[r]}))};function de(e,t){var r=e.indexOf(t);r>=0&&e.splice(r,1)}function le(e){var t=!1;return function(){t||(t=!0,e())}}var ue=function(e){throw e},he=function(e){return{value:e,done:!0}};function me(e,t,r){void 0===t&&(t=ue),void 0===r&&(r="iterator");var i={meta:{name:r},next:e,throw:t,return:he,isSagaIterator:!0};return"undefined"!=typeof Symbol&&(i[Symbol.iterator]=function(){return i}),i}function pe(e,t){var r=t.sagaStack;console.error(e),console.error(r)}var ge=function(e){return Array.apply(null,new Array(e))},fe=function(e){return function(t){return e(Object.defineProperty(t,z,{value:!0}))}},ve=function(e){return e===q},ye=function(e){return e===H},be=function(e){return ve(e)||ye(e)};function _e(e,t){var r,i=Object.keys(e),o=i.length,n=0,s=Z(e)?ge(o):{},a={};return i.forEach((function(e){var i=function(i,a){r||(a||be(i)?(t.cancel(),t(i,a)):(s[e]=i,++n===o&&(r=!0,t(s))))};i.cancel=se,a[e]=i})),t.cancel=function(){r||(r=!0,i.forEach((function(e){return a[e].cancel()})))},a}function we(e){return{name:e.name||"anonymous",location:ke(e)}}function ke(e){return e[K]}function Se(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return 0===t.length?function(e){return e}:1===t.length?t[0]:t.reduce((function(e,t){return function(){return e(t.apply(void 0,arguments))}}))}var Ce={isEmpty:ne,put:se,take:se},Ie="TAKE",Te="CALL",Ee="FORK",Pe="JOIN",Me="SELECT",Re="CANCELLED",Ae=function(e,t){var r;return(r={})[N]=!0,r.combinator=!1,r.type=e,r.payload=t,r};function xe(e,t){return void 0===e&&(e="*"),re(e)?(Q(t)&&console.warn("take(pattern) takes one argument but two were provided. Consider passing an array for listening to several action types"),Ae(Ie,{pattern:e})):ie(r=e)&&r[U]&&Q(t)&&re(t)?Ae(Ie,{channel:e,pattern:t}):ie(e)?(Q(t)&&console.warn("take(channel) takes one argument but two were provided. Second argument is ignored."),Ae(Ie,{channel:e})):void 0;var r}function Oe(e,t){return J(t)&&(t=e,e=void 0),Ae("PUT",{channel:e,action:t})}function Le(e,t){var r,i=null;return X(e)?r=e:(Z(e)?(i=e[0],r=e[1]):(i=e.context,r=e.fn),i&&Y(r)&&X(i[r])&&(r=i[r])),{context:i,fn:r,args:t}}function je(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return Ae(Te,Le(e,r))}function De(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return Ae(Ee,Le(e,r))}function We(e){void 0===e&&(e=ae);for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return Ae(Me,{selector:e,args:r})}function Ve(){return Ae(Re,{})}var Ne=[],$e=0;function Ue(e){try{Fe(),e()}finally{He()}}function ze(e){Ne.push(e),$e||(Fe(),qe())}function Be(e){try{return Fe(),e()}finally{qe()}}function Fe(){$e++}function He(){$e--}function qe(){var e;for(He();!$e&&void 0!==(e=Ne.shift());)Ue(e)}var Ke=function(e){return function(t){return e.some((function(e){return Ye(e)(t)}))}},Ge=function(e){return function(t){return e(t)}},Je=function(e){return function(t){return t.type===String(e)}},Qe=function(e){return function(t){return t.type===e}},Xe=function(){return ne};function Ye(e){var t="*"===e?Xe:Y(e)?Je:Z(e)?Ke:function(e){return X(e)&&e.hasOwnProperty("toString")}(e)?Je:X(e)?Ge:oe(e)?Qe:null;if(null===t)throw new Error("invalid pattern: "+e);return t(e)}var Ze={type:V},et=function(e){return e&&e.type===V};function tt(e){void 0===e&&(e=function(e){void 0===e&&(e=10);var t=new Array(e),r=0,i=0,o=0,n=function(){if(0!=r){var i=t[o];return t[o]=null,r--,o=(o+1)%e,i}},s=function(){for(var e=[];r;)e.push(n());return e};return{isEmpty:function(){return 0==r},put:function(n){var a;r<e||(a=2*e,t=s(),r=t.length,i=t.length,o=0,t.length=a,e=a),function(o){t[i]=o,i=(i+1)%e,r++}(n)},take:n,flush:s}}(void 0));var t=!1,r=[];return{take:function(i){t&&e.isEmpty()?i(Ze):e.isEmpty()?(r.push(i),i.cancel=function(){de(r,i)}):i(e.take())},put:function(i){if(!t){if(0===r.length)return e.put(i);r.shift()(i)}},flush:function(r){t&&e.isEmpty()?r(Ze):r(e.flush())},close:function(){if(!t){t=!0;var e=r;r=[];for(var i=0,o=e.length;i<o;i++)(0,e[i])(Ze)}}}}function rt(e,t){void 0===t&&(t=Ce);var r,i=!1,o=tt(t),n=function(){i||(i=!0,X(r)&&r(),o.close())};return r=le(r=e((function(e){et(e)?n():o.put(e)}))),i&&r(),{take:o.take,flush:o.flush,close:n}}function it(){var e,t=!1,r=[],i=r,o=function(){i===r&&(i=r.slice())},n=function(){t=!0;var e=r=i;i=[],e.forEach((function(e){e(Ze)}))};return(e={})[U]=!0,e.put=function(e){if(!t)if(et(e))n();else for(var o=r=i,s=0,a=o.length;s<a;s++){var c=o[s];c[$](e)&&(c.cancel(),c(e))}},e.take=function(e,r){void 0===r&&(r=Xe),t?e(Ze):(e[$]=r,o(),i.push(e),e.cancel=le((function(){o(),de(i,e)})))},e.close=n,e}function ot(){var e=it(),t=e.put;return e.put=function(e){e[z]?t(e):ze((function(){t(e)}))},e}function nt(e,t){var r=e[W];X(r)&&(t.cancel=r),e.then(t,(function(e){t(e,!0)}))}var st,at=0,ct=function(){return++at};function dt(e){e.isRunning()&&e.cancel()}var lt=((st={})[Ie]=function(e,t,r){var i=t.channel,o=void 0===i?e.channel:i,n=t.pattern,s=t.maybe,a=function(e){e instanceof Error?r(e,!0):!et(e)||s?r(e):r(q)};try{o.take(a,Q(n)?Ye(n):null)}catch(e){return void r(e,!0)}r.cancel=a.cancel},st.PUT=function(e,t,r){var i=t.channel,o=t.action,n=t.resolve;ze((function(){var t;try{t=(i?i.put:e.dispatch)(o)}catch(e){return void r(e,!0)}n&&ee(t)?nt(t,r):r(t)}))},st.ALL=function(e,t,r,i){var o=i.digestEffect,n=at,s=Object.keys(t);if(0!==s.length){var a=_e(t,r);s.forEach((function(e){o(t[e],n,a[e],e)}))}else r(Z(t)?[]:{})},st.RACE=function(e,t,r,i){var o=i.digestEffect,n=at,s=Object.keys(t),a=Z(t)?ge(s.length):{},c={},d=!1;s.forEach((function(e){var t=function(t,i){d||(i||be(t)?(r.cancel(),r(t,i)):(r.cancel(),d=!0,a[e]=t,r(a)))};t.cancel=se,c[e]=t})),r.cancel=function(){d||(d=!0,s.forEach((function(e){return c[e].cancel()})))},s.forEach((function(e){d||o(t[e],n,c[e],e)}))},st[Te]=function(e,t,r,i){var o=t.context,n=t.fn,s=t.args,a=i.task;try{var c=n.apply(o,s);if(ee(c))return void nt(c,r);if(te(c))return void _t(e,c,a.context,at,we(n),!1,r);r(c)}catch(e){r(e,!0)}},st.CPS=function(e,t,r){var i=t.context,o=t.fn,n=t.args;try{var s=function(e,t){J(e)?r(t):r(e,!0)};o.apply(i,n.concat(s)),s.cancel&&(r.cancel=s.cancel)}catch(e){r(e,!0)}},st[Ee]=function(e,t,r,i){var o=t.fn,n=t.detached,s=i.task,a=function(e){var t=e.context,r=e.fn,i=e.args;try{var o=r.apply(t,i);if(te(o))return o;var n=!1;return me((function(e){return n?{value:e,done:!0}:(n=!0,{value:o,done:!ee(o)})}))}catch(e){return me((function(){throw e}))}}({context:t.context,fn:o,args:t.args}),c=function(e,t){return e.isSagaIterator?{name:e.meta.name}:we(t)}(a,o);Be((function(){var t=_t(e,a,s.context,at,c,n,void 0);n?r(t):t.isRunning()?(s.queue.addTask(t),r(t)):t.isAborted()?s.queue.abort(t.error()):r(t)}))},st[Pe]=function(e,t,r,i){var o=i.task,n=function(e,t){if(e.isRunning()){var r={task:o,cb:t};t.cancel=function(){e.isRunning()&&de(e.joiners,r)},e.joiners.push(r)}else e.isAborted()?t(e.error(),!0):t(e.result())};if(Z(t)){if(0===t.length)return void r([]);var s=_e(t,r);t.forEach((function(e,t){n(e,s[t])}))}else n(t,r)},st.CANCEL=function(e,t,r,i){t===B?dt(i.task):Z(t)?t.forEach(dt):dt(t),r()},st[Me]=function(e,t,r){var i=t.selector,o=t.args;try{r(i.apply(void 0,[e.getState()].concat(o)))}catch(e){r(e,!0)}},st.ACTION_CHANNEL=function(e,t,r){var i=t.pattern,o=tt(t.buffer),n=Ye(i),s=function t(r){et(r)||e.channel.take(t,n),o.put(r)},a=o.close;o.close=function(){s.cancel(),a()},e.channel.take(s,n),r(o)},st[Re]=function(e,t,r,i){r(i.task.isCancelled())},st.FLUSH=function(e,t,r){t.flush(r)},st.GET_CONTEXT=function(e,t,r,i){r(i.task.context[t])},st.SET_CONTEXT=function(e,t,r,i){ce(i.task.context,t),r()},st);function ut(e,t){return e+"?"+t}function ht(e){var t=e.name,r=e.location;return r?t+" "+ut(r.fileName,r.lineNumber):t}function mt(e){var t,r=(t=[]).concat.apply(t,e.map((function(e){return e.cancelledTasks})));return r.length?["Tasks cancelled due to error:"].concat(r).join("\n"):""}var pt=null,gt=[],ft=function(e){e.crashedEffect=pt,gt.push(e)},vt=function(){pt=null,gt.length=0},yt=function(e){pt=e},bt=function(){var e,t=gt[0],r=gt.slice(1),i=t.crashedEffect?(e=ke(t.crashedEffect))?e.code+" "+ut(e.fileName,e.lineNumber):"":null;return["The above error occurred in task "+ht(t.meta)+(i?" \n when executing effect "+i:"")].concat(r.map((function(e){return" created by "+ht(e.meta)})),[mt(gt)]).join("\n")};function _t(e,t,r,i,o,n,s){var a=e.finalizeRunEffect((function(t,r,i){ee(t)?nt(t,i):te(t)?_t(e,t,d.context,r,o,!1,i):t&&t[N]?(0,lt[t.type])(e,t.payload,i,l):i(t)}));u.cancel=se;var c={meta:o,cancel:function(){0===c.status&&(c.status=1,u(H))},status:0},d=function(e,t,r,i,o,n,s){var a;void 0===s&&(s=se);var c,d,l=0,u=null,h=[],m=Object.create(r),p=function(e,t,r){var i,o=[],n=!1;function s(e){h.push.apply(h,p.getTasks().map((function(e){return e.meta.name}))),c(),r(e,!0)}function a(t){o.push(t),t.cont=function(a,c){n||(de(o,t),t.cont=se,c?s(a):(t===e&&(i=a),o.length||(n=!0,r(i))))}}function c(){n||(n=!0,o.forEach((function(e){e.cont=se,e.cancel()})),o=[])}return a(e),{addTask:a,cancelAll:c,abort:s,getTasks:function(){return o}}}(t,0,g);function g(t,r){if(r){if(l=2,ft({meta:o,cancelledTasks:h}),f.isRoot){var i=bt();vt(),e.onError(t,{sagaStack:i})}d=t,u&&u.reject(t)}else t===H?l=1:1!==l&&(l=3),c=t,u&&u.resolve(t);f.cont(t,r),f.joiners.forEach((function(e){e.cb(t,r)})),f.joiners=null}var f=((a={})[F]=!0,a.id=i,a.meta=o,a.isRoot=n,a.context=m,a.joiners=[],a.queue=p,a.cancel=function(){0===l&&(l=1,p.cancelAll(),g(H,!1))},a.cont=s,a.end=g,a.setContext=function(e){ce(m,e)},a.toPromise=function(){return u||((e={}).promise=new Promise((function(t,r){e.resolve=t,e.reject=r})),u=e,2===l?u.reject(d):0!==l&&u.resolve(c)),u.promise;var e},a.isRunning=function(){return 0===l},a.isCancelled=function(){return 1===l||0===l&&1===t.status},a.isAborted=function(){return 2===l},a.result=function(){return c},a.error=function(){return d},a);return f}(e,c,r,i,o,n,s),l={task:d,digestEffect:h};return s&&(s.cancel=d.cancel),u(),d;function u(e,r){try{var o;r?(o=t.throw(e),vt()):ye(e)?(c.status=1,u.cancel(),o=X(t.return)?t.return(H):{done:!0,value:H}):o=ve(e)?X(t.return)?t.return():{done:!0}:t.next(e),o.done?(1!==c.status&&(c.status=3),c.cont(o.value)):h(o.value,i,u)}catch(e){if(1===c.status)throw e;c.status=2,c.cont(e,!0)}}function h(t,r,i,o){void 0===o&&(o="");var n,s=ct();function c(r,o){n||(n=!0,i.cancel=se,e.sagaMonitor&&(o?e.sagaMonitor.effectRejected(s,r):e.sagaMonitor.effectResolved(s,r)),o&&yt(t),i(r,o))}e.sagaMonitor&&e.sagaMonitor.effectTriggered({effectId:s,parentEffectId:r,label:o,effect:t}),c.cancel=se,i.cancel=function(){n||(n=!0,c.cancel(),c.cancel=se,e.sagaMonitor&&e.sagaMonitor.effectCancelled(s))},a(t,s,c)}}function wt(e,t){for(var r=e.channel,i=void 0===r?ot():r,o=e.dispatch,n=e.getState,s=e.context,a=void 0===s?{}:s,c=e.sagaMonitor,d=e.effectMiddlewares,l=e.onError,u=void 0===l?pe:l,h=arguments.length,m=new Array(h>2?h-2:0),p=2;p<h;p++)m[p-2]=arguments[p];var g,f=t.apply(void 0,m),v=ct();if(c&&(c.rootSagaStarted=c.rootSagaStarted||se,c.effectTriggered=c.effectTriggered||se,c.effectResolved=c.effectResolved||se,c.effectRejected=c.effectRejected||se,c.effectCancelled=c.effectCancelled||se,c.actionDispatched=c.actionDispatched||se,c.rootSagaStarted({effectId:v,saga:t,args:m})),d){var y=Se.apply(void 0,d);g=function(e){return function(t,r,i){return y((function(t){return e(t,r,i)}))(t)}}}else g=ae;var b={channel:i,dispatch:fe(o),getState:n,sagaMonitor:c,onError:u,finalizeRunEffect:g};return Be((function(){var e=_t(b,f,a,v,we(t),!0,void 0);return c&&c.effectResolved(v,e),e}))}var kt={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function o(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,i,o=[];if(0===this._eventsCount)return o;for(i in e=this._events)t.call(e,i)&&o.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[r?r+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var i=0,o=t.length,n=new Array(o);i<o;i++)n[i]=t[i].fn;return n},a.prototype.listenerCount=function(e){var t=this._events[r?r+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,i,o,n,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,d,l=this._events[a],u=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,i),!0;case 4:return l.fn.call(l.context,t,i,o),!0;case 5:return l.fn.call(l.context,t,i,o,n),!0;case 6:return l.fn.call(l.context,t,i,o,n,s),!0}for(d=1,c=new Array(u-1);d<u;d++)c[d-1]=arguments[d];l.fn.apply(l.context,c)}else{var h,m=l.length;for(d=0;d<m;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),u){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,t);break;case 3:l[d].fn.call(l[d].context,t,i);break;case 4:l[d].fn.call(l[d].context,t,i,o);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];l[d].fn.apply(l[d].context,c)}}return!0},a.prototype.on=function(e,t,r){return n(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,i,o){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return s(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||o&&!a.once||i&&a.context!==i||s(this,n);else{for(var c=0,d=[],l=a.length;c<l;c++)(a[c].fn!==t||o&&!a[c].once||i&&a[c].context!==i)&&d.push(a[c]);d.length?this._events[n]=1===d.length?d[0]:d:s(this,n)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=r?r+e:e]&&s(this,t):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(kt);var St=kt.exports,Ct=Object.defineProperty,It=Object.defineProperties,Tt=Object.getOwnPropertyDescriptor,Et=Object.getOwnPropertyDescriptors,Pt=Object.getOwnPropertyNames,Mt=Object.getOwnPropertySymbols,Rt=Object.prototype.hasOwnProperty,At=Object.prototype.propertyIsEnumerable,xt=(e,t,r)=>t in e?Ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Ot=(e,t)=>{for(var r in t||(t={}))Rt.call(t,r)&&xt(e,r,t[r]);if(Mt)for(var r of Mt(t))At.call(t,r)&&xt(e,r,t[r]);return e},Lt=(e,t)=>It(e,Et(t)),jt=(e,t)=>{var r={};for(var i in e)Rt.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&Mt)for(var i of Mt(e))t.indexOf(i)<0&&At.call(e,i)&&(r[i]=e[i]);return r},Dt=(e,t)=>{for(var r in t)Ct(e,r,{get:t[r],enumerable:!0})},Wt=(e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of Pt(t))Rt.call(e,o)||o===r||Ct(e,o,{get:()=>t[o],enumerable:!(i=Tt(t,o))||i.enumerable});return e},Vt=(e,t,r)=>(Wt(e,t,"default"),r&&Wt(r,t,"default")),Nt=(e,t,r)=>xt(e,"symbol"!=typeof t?t+"":t,r),$t="__local__",Ut="__synthetic__",zt="chat",Bt=Symbol.for("sw-execute-connection-closed"),Ft=Symbol.for("sw-execute-timeout"),Ht=Symbol.for("sw-connect-error"),qt=i.getLogger("signalwire"),Kt=qt.methodFactory;qt.methodFactory=(e,t,r)=>{const i=Kt(e,t,r);return function(...e){e.unshift(/* @__PURE__ */(new Date).toISOString(),"-"),i.apply(void 0,e)}};var Gt,Jt=qt.getLevel();qt.setLevel(Jt);var Qt={},Xt=()=>null!=Gt?Gt:qt,Yt=({type:e,payload:t})=>{const r=Xt(),{logWsTraffic:i}=Qt||{};if(!i)return;const o=(e=>!("method"in e)||"signalwire.ping"!==e.method)(t)?JSON.stringify(t,null,2):t;return r.info(`${e.toUpperCase()}: \n`,o,"\n")},Zt=()=>{const e=Xt();return new Proxy(e,{get:(e,t,r)=>"wsTraffic"===t?Yt:Reflect.get(e,t,r)})},er=/[A-Z]/g,tr=e=>e.replace(er,(e=>`_${e.toLowerCase()}`)),rr=["webrtc.message"],ir=e=>rr.includes(e),or=/^2[0-9][0-9]$/,nr=(e,t)=>{const{result:r={},error:i}=e;if(i)return{error:i};const{code:o,node_id:n,result:s=null}=r;return o&&!or.test(o)?{error:r}:null===s?(t&&(r.node_id=t),{result:r}):s?s.jsonrpc?nr(s,n):{result:s}:{result:r}},sr={propsToUpdateValue:["updated","layers","members","recordings","playbacks"]},ar=(e,t=sr)=>(null==e?void 0:e.__sw_symbol)||(null==e?void 0:e.__sw_proxy)?e:Object.entries(e).reduce(((e,[r,i])=>{const o=cr(r);return e[o]="object"==typeof i&&i?Array.isArray(i)?t.propsToUpdateValue.includes(r)?i.map((e=>"string"==typeof e?cr(e):ar(e))):i:ar(i):(e=>e.endsWith("At"))(o)?(e=>{if(void 0===e)return e;const t=new Date(1e3*e);return isNaN(t.getTime())?e:t})(i):i,e}),{}),cr=e=>e.includes("_")?e.split("_").reduce(((e,t,r)=>{const i=t.trim().charAt(0),o=t.substr(1).toLowerCase();return`${e}${0===r?i.toLowerCase():i.toUpperCase()}${o}`}),""):e,dr=(e,t=e=>e,r={})=>(Array.isArray(e)?r=e.map(((e,i)=>"object"==typeof e?dr(e,t,r[i]):e)):Object.keys(e).forEach((i=>{const o=tr(i);r[o]=e[i]&&"object"==typeof e[i]?dr(e[i],t,r[o]):t(e[i])})),r),lr=(e,t)=>(Object.keys(t).forEach((t=>{if(e.prototype.hasOwnProperty(t))throw new Error(`[extendComponent] Duplicated method name: ${t}`)})),Object.defineProperties(e.prototype,t),e),ur=(e,t)=>{if(t&&"string"==typeof t){const r=new RegExp(`^${t}.`);return e.replace(r,"")}const r=e.split(".");return r.length>1?(r.shift(),r.join(".")):e},hr=({delayLimit:e=Number.MAX_SAFE_INTEGER,initialDelay:t=100,variation:r=1})=>{if(t<0||e<0||r<0)throw new Error("No Negative Numbers");if(t>e)throw new Error("initialDelay must be lte delayLimit");let i=Math.min(t,e);return()=>{if(i===e)return e;const t=i;return i=Math.min(i+r,e),t}},mr=({initialDelay:e=100})=>{if(e<0)throw new Error("No Negative Numbers");return()=>e},pr=async({asyncCallable:e,maxRetries:t=10,delayFn:r,validator:i,expectedErrorHandler:o})=>{let n=t-1,s=0;const a=async()=>{var c;try{let t;return t=s<=0?await e():await new Promise(((t,r)=>setTimeout((()=>{e().then(t).catch(r)}),s))),n&&(null==i||i(t)),t}catch(e){if(n-- >0&&!(null==o?void 0:o(e)))return s=null!=(c=null==r?void 0:r())?c:0,Zt().debug(`Retrying request: ${t-n} of ${t}`),a();throw e}};return a()},gr=/^(ws|wss):\/\//,fr=(e,t,r)=>{let i=null;return Promise.race([e,new Promise(((e,o)=>i=setTimeout(o,t,r)))]).finally((()=>clearTimeout(i)))},vr=["video.member.updated","video.member.talking"],yr=["video.room.joined","video.track","video.active","video.answering","video.destroy","video.early","video.hangup","video.held","video.new","video.purge","video.recovering","video.requesting","video.ringing","video.trying","video.media.connected","video.media.reconnecting","video.media.disconnected","video.microphone.updated","video.camera.updated","video.speaker.updated","video.microphone.disconnected","video.camera.disconnected","video.speaker.disconnected"],br=e=>{const t=e.map((e=>{if("string"==typeof e){const t=(e=>{const t=e.split(":");return t[t.length-1]})(e);return yr.includes(t)||(e=>e.includes(Ut))(t)||_r(t)||(e=>e.includes("session."))(t)?null:vr.find((e=>t.startsWith(e)))||t}return e}));return Array.from(new Set(t)).filter(Boolean)},_r=e=>e.includes($t),wr=e=>Boolean(e.method),kr=e=>void 0!==e&&"jti"in e,Sr=e=>wr(e)&&"signalwire.connect"==e.method,Cr=e=>{var t;return Ot({jsonrpc:"2.0",id:null!=(t=e.id)?t:b()},e)},Ir=e=>Ot({jsonrpc:"2.0"},e),Tr={major:3,minor:0,revision:0},Er={major:4,minor:0,revision:0},Pr=e=>Cr({method:"signalwire.connect",params:Ot({version:Tr,event_acks:!0},e)}),Mr=e=>Cr({method:"signalwire.reauthenticate",params:{authentication:e}}),Rr={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",fromFabricAddressId:"from_fabric_address_id"},Ar=e=>{if(e.hasOwnProperty("dialogParams")){const t=jt(e.dialogParams,["remoteSdp","localStream","remoteStream"]);for(const e in Rr)e&&t.hasOwnProperty(e)&&(t[Rr[e]]=t[e],delete t[e]);e.dialogParams=t}return e},xr=e=>(t={})=>Cr({method:e,params:Ar(t)}),Or=xr("verto.invite"),Lr=xr("verto.bye"),jr=xr("verto.modify"),Dr=xr("verto.info"),Wr=xr("verto.answer"),Vr=xr("verto.subscribe"),Nr=xr("verto.pong"),$r=(e,t)=>Ir({id:e,result:{method:t}}),Ur={};Dt(Ur,{authErrorAction:()=>Qr,authExpiringAction:()=>Yr,authSuccessAction:()=>Xr,createAction:()=>Br,destroyAction:()=>Gr,getCustomSagaActionType:()=>ni,initAction:()=>Kr,makeCustomSagaAction:()=>oi,reauthAction:()=>Jr,sessionDisconnectedAction:()=>ei,sessionForceCloseAction:()=>ri,sessionReconnectingAction:()=>ti,socketMessageAction:()=>Zr});var zr={};function Br(e,t){function r(...r){if(t){let i=t(...r);if(!i)throw new Error("prepareAction did not return an object");return Ot(Ot({type:e,payload:i.payload},"meta"in i&&{meta:i.meta}),"error"in i&&{error:i.error})}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>t.type===e,r}Dt(zr,{configureStore:()=>qr,createAction:()=>Br}),Vt(zr,j);var Fr="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?O:O.apply(null,arguments)},Hr=!0;function qr(e){const t=function(){return[]},{reducer:r,middleware:i=t(),devTools:o=!0,preloadedState:n,enhancers:s}=e||{};let a;if("function"==typeof r)a=r;else{if(!function(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let r=t;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return t===r}(r))throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');a=A(r)}let c=i;"function"==typeof c&&(c=c(t));const d=L(...c);let l=O;o&&(l=Fr(Ot({trace:!Hr},"object"==typeof o&&o)));let u=[d];return Array.isArray(s)?u=[d,...s]:"function"==typeof s&&(u=s(u)),R(a,n,l(...u))}var Kr=Br("swSdk/init"),Gr=Br("swSdk/destroy"),Jr=Br("swSdk/reauth"),Qr=Br("auth/error"),Xr=Br("auth/success"),Yr=Br("auth/expiring"),Zr=Br("socket/message"),ei=Br("session.disconnected"),ti=Br("session.reconnecting"),ri=Br("session.forceClose"),ii=(e,t)=>`${t.type}/${e}`,oi=(e,t)=>Lt(Ot({},t),{type:ii(e,t)}),ni=(e,t)=>ii(e,t);function si(e){const t={},r=[];let i;const o={addCase(e,r){const i="string"==typeof e?e:e.type;if(i in t)throw new Error("addCase cannot be called with two reducers for the same action type");return t[i]=r,o},addMatcher:(e,t)=>(r.push({matcher:e,reducer:t}),o),addDefaultCase:e=>(i=e,o)};return e(o),[t,r,i]}var ai=({name:e="",initialState:t,reducers:r,extraReducers:i})=>function(e){const{name:t}=e;if(!t)throw new Error("`name` is a required option for createSlice");const r=e.initialState,i=e.reducers||{},o=Object.keys(i),n={},s={},a={};function c(){const[t={},i=[],o]="function"==typeof e.extraReducers?si(e.extraReducers):[e.extraReducers],n=Ot(Ot({},t),s);return function(e,t,r=[],i){let o,[n,s,a]="function"==typeof t?si(t):[t,r,i];function c(e=o(),t){let r=[n[t.type],...s.filter((({matcher:e})=>e(t))).map((({reducer:e})=>e))];return 0===r.filter((e=>!!e)).length&&(r=[a]),r.reduce(((e,r)=>r?r(e,t):e),e)}return o="function"==typeof e?()=>e():()=>e,c.getInitialState=o,c}(r,n,i,o)}let d;return o.forEach((e=>{const r=i[e],o=`${t}/${e}`;let c,d;"reducer"in r?(c=r.reducer,d=r.prepare):c=r,n[e]=c,s[o]=c,a[e]=d?Br(o,d):Br(o)})),{name:t,reducer:(e,t)=>(d||(d=c()),d(e,t)),actions:a,caseReducers:n,getInitialState:()=>(d||(d=c()),d.getInitialState())}}({name:e,initialState:t,reducers:r,extraReducers:e=>{e.addCase(Gr.type,(()=>t)),"function"==typeof i&&i(e)}});function ci(e){return[Kr.type,Jr.type].includes(e.type)}var di=ai({name:"session",initialState:{protocol:"",iceServers:[],authStatus:"unknown",authorization:void 0,authorizationState:void 0,authError:void 0,authCount:0},reducers:{connected:(e,{payload:t})=>{var r,i;return Lt(Ot({},e),{authStatus:"authorized",authorization:null==t?void 0:t.authorization,authCount:e.authCount+1,protocol:null!=(r=null==t?void 0:t.protocol)?r:"",iceServers:null!=(i=null==t?void 0:t.ice_servers)?i:[]})},authStatus:(e,{payload:t})=>Lt(Ot({},e),{authStatus:t}),updateAuthorization:(e,{payload:t})=>Lt(Ot({},e),{authorization:t}),updateAuthorizationState:(e,{payload:t})=>Lt(Ot({},e),{authorizationState:t})},extraReducers:e=>{e.addCase(Qr.type,((e,{payload:t})=>Lt(Ot({},e),{authStatus:"unauthorized",authError:t.error}))),e.addMatcher(ci,(e=>Lt(Ot({},e),{authStatus:"authorizing"})))}}),{actions:li,reducer:ui}=di,hi=Symbol("BaseSession"),mi=class{constructor(e){var t,r;this.options=e,Nt(this,"__sw_symbol",hi),Nt(this,"uuid",b()),Nt(this,"WebSocketConstructor"),Nt(this,"CloseEventConstructor"),Nt(this,"agent"),Nt(this,"connectVersion",Tr),Nt(this,"_rpcConnectResult"),Nt(this,"_requests",/* @__PURE__ */new Map),Nt(this,"_socket",null),Nt(this,"_host","wss://relay.signalwire.com"),Nt(this,"_executeTimeoutMs",1e4),Nt(this,"_executeTimeoutError",Ft),Nt(this,"_executeQueue",/* @__PURE__ */new Set),Nt(this,"_swConnectError",Ht),Nt(this,"_executeConnectionClosed",Bt),Nt(this,"_checkPingDelay",15e3),Nt(this,"_checkPingTimer",null),Nt(this,"_reconnectTimer"),Nt(this,"_status","unknown"),Nt(this,"_resolveWaitConnected",null),Nt(this,"_sessionChannel"),Nt(this,"wsOpenHandler"),Nt(this,"wsCloseHandler"),Nt(this,"wsErrorHandler");const{host:i,logLevel:o="info",sessionChannel:n}=e;i&&(this._host=(e=>`${gr.test(e)?"":"wss://"}${e}`)(i)),n&&(this._sessionChannel=n),o&&(null==(r=(t=this.logger).setLevel)||r.call(t,o)),this._onSocketOpen=this._onSocketOpen.bind(this),this._onSocketError=this._onSocketError.bind(this),this._onSocketClose=this._onSocketClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this.execute=this.execute.bind(this),this.connect=this.connect.bind(this),this.wsOpenHandler=e=>{var t;null==(t=this._socket)||t.removeEventListener("open",this.wsOpenHandler),this._onSocketOpen(e)},this.wsCloseHandler=e=>{var t;null==(t=this._socket)||t.removeEventListener("close",this.wsCloseHandler),this._onSocketClose(e)},this.wsErrorHandler=e=>{var t;null==(t=this._socket)||t.removeEventListener("error",this.wsErrorHandler),this._onSocketError(e)}}get host(){return this._host}get rpcConnectResult(){return this._rpcConnectResult}get relayProtocol(){var e,t;return null!=(t=null==(e=this._rpcConnectResult)?void 0:e.protocol)?t:""}get signature(){if(this._rpcConnectResult){const{authorization:e}=this._rpcConnectResult;return e.signature}}get logger(){return Zt()}get connecting(){var e;return 0===(null==(e=this._socket)?void 0:e.readyState)}get connected(){var e;return 1===(null==(e=this._socket)?void 0:e.readyState)}get closing(){var e;return 2===(null==(e=this._socket)?void 0:e.readyState)}get closed(){return!this._socket||3===this._socket.readyState}get status(){return this._status}get idle(){return"idle"===this._status}get ready(){return!Boolean(this.idle||!this.connected)}async _waitConnected(){return new Promise((e=>{this.connected?e():this._resolveWaitConnected=e}))}set token(e){this.options.token=e}connect(){if(!(null==this?void 0:this.WebSocketConstructor))throw new Error("Missing WebSocketConstructor");if(!(null==this?void 0:this.CloseEventConstructor))throw new Error("Missing CloseEventConstructor");this._clearTimers(),this.connecting||this.connected?this.logger.warn("Session already connected."):(this._removeSocketListeners(),this.destroySocket(),this._clearCheckPingTimer(),this._socket=this._createSocket(),this._addSocketListeners())}_createSocket(){return new this.WebSocketConstructor(this._host)}destroySocket(){this._socket&&(this._socket.close(),this.wsCloseHandler(new this.CloseEventConstructor("close",{reason:"Client-side closed"})),this._socket=null)}_addSocketListeners(){if(!this._socket)return this.logger.debug("Invalid socket instance to add listeners");this._removeSocketListeners(),this._socket.addEventListener("open",this.wsOpenHandler),this._socket.addEventListener("close",this.wsCloseHandler),this._socket.addEventListener("error",this.wsErrorHandler),this._socket.addEventListener("message",this._onSocketMessage)}_removeSocketListeners(){if(!this._socket)return this.logger.debug("Invalid socket instance to remove listeners");this._socket.removeEventListener("open",this.wsOpenHandler),this._socket.removeEventListener("close",this.wsCloseHandler),this._socket.removeEventListener("error",this.wsErrorHandler),this._socket.removeEventListener("message",this._onSocketMessage)}disconnect(){this._socket&&!this.closing?(this._status="disconnecting",this._checkCurrentStatus()):this.logger.debug("Session not connected or already in closing state.")}execute(e){if("disconnecting"===this._status)return this.logger.warn("Reject request because the session is disconnecting",e),Promise.reject({code:"400",message:"The SDK session is disconnecting"});if("disconnected"===this._status)return Promise.reject({code:"400",message:"The SDK is disconnected"});let t=Promise.resolve();return"params"in e&&(t=new Promise(((t,r)=>{this._requests.set(e.id,{rpcRequest:e,resolve:t,reject:r})}))),this.ready?(this._send(e),fr(t,this._executeTimeoutMs,this._executeTimeoutError).catch((t=>{if(t===this._executeConnectionClosed)throw this._executeConnectionClosed;if(t!==this._executeTimeoutError)throw t;if(Sr(e))throw this._swConnectError;if(this._checkCurrentStatus(),this.logger.error("Request Timeout",e),"disconnected"===this.status)return this.logger.debug("Request failed because the session is disconnected",this.status,this._socket);this._closeConnection("reconnecting")}))):(this._addToExecuteQueue(e),this.connect(),t)}get _connectParams(){return{agent:this.agent,version:this.connectVersion,authentication:{project:this.options.project,token:this.options.token}}}async authenticate(){var e,t;const r=this._connectParams;this._relayProtocolIsValid()&&(r.protocol=this.relayProtocol),(null==(e=this.options.topics)?void 0:e.length)?r.contexts=this.options.topics:(null==(t=this.options.contexts)?void 0:t.length)&&(r.contexts=this.options.contexts),this._rpcConnectResult=await this.execute(Pr(r))}authError(e){this._removeSocketListeners(),this.dispatch(Qr({error:e}))}forceClose(){return this._removeSocketListeners(),this._closeConnection("reconnecting")}async _onSocketOpen(e){var t;this.logger.debug("_onSocketOpen",e.type);try{this._status="unknown",this._clearTimers(),await this.authenticate(),this._status="connected",null==(t=this._resolveWaitConnected)||t.call(this),this._flushExecuteQueue(),this.dispatch(Xr())}catch(e){if(e===this._swConnectError||e===this._executeConnectionClosed)return void this.logger.debug("Invalid connect or connection closed. Waiting for retry.");this.logger.error("Auth Error",e),this.authError(e)}}_onSocketError(e){this.logger.debug("_onSocketError",e)}_onSocketClose(e){this.logger.debug("_onSocketClose",e.type,e.code,e.reason),"disconnected"!==this._status&&(this._status="reconnecting",this.dispatch(ti()),this._clearTimers(),this._clearPendingRequests(),this._reconnectTimer=setTimeout((()=>{this.connect()}),1e3*Math.floor(4*Math.random()+1))),this._socket=null}_clearTimers(){clearTimeout(this._reconnectTimer)}_clearPendingRequests(){this.logger.debug("_clearPendingRequests",this._requests.size),this._requests.forEach((({reject:e})=>{e(this._executeConnectionClosed)})),this._requests.clear()}_onSocketMessage(e){const t=this.decode(e.data);if(this.logger.wsTraffic({type:"recv",payload:t}),(e=>!wr(e))(t)){const e=this._requests.get(t.id);if(e){const{rpcRequest:r,resolve:i,reject:o}=e;this._requests.delete(t.id);const{result:n,error:s}=(({response:e,request:t})=>{const{result:r={},error:i}=e;return i?{error:i}:"signalwire.connect"===t.method?{result:r}:nr(e)})({response:t,request:r});return this._checkCurrentStatus(),s?o(s):i(n)}return this.logger.warn("Unknown request for",t)}switch(t.method){case"signalwire.ping":return this._pingHandler(t);case"signalwire.disconnect":this.execute((r=t.id,Ir({id:r,result:{}}))).catch((e=>{this.logger.error("SwDisconnect Error",e)})).finally((()=>{this._status="idle"}));break;default:this._eventAcknowledgingHandler(t).catch((e=>this.logger.error("Event Acknowledging Error",e))),this.dispatch(Zr(t))}var r}dispatch(e){if(!this._sessionChannel)throw new Error("Session channel does not exist");this._sessionChannel.put(e)}_relayProtocolIsValid(){var e;return this.signature&&(null==(e=null==this?void 0:this.relayProtocol)?void 0:e.split("_")[1])===this.signature}encode(e){return JSON.stringify(e)}decode(e){return(e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}})(e)}async onSwAuthorizationState(e){this.persistSwAuthorizationState(e)}async retrieveSwAuthorizationState(){return""}async persistSwAuthorizationState(e){}_send(e){this.logger.wsTraffic({type:"send",payload:e}),this._socket.send(this.encode(e))}_addToExecuteQueue(e){this.logger.warn("Request queued waiting for session to reconnect",e),this._executeQueue.add(e)}_flushExecuteQueue(){if(this._executeQueue.size){if(!this.ready)return this.logger.warn("Session not ready to flush the queue."),void this._closeConnection("reconnecting");this.logger.debug(`${this._executeQueue.size} messages to flush`),this._executeQueue.forEach((e=>{this._send(e),this._executeQueue.delete(e)})),this._executeQueue.clear()}}_clearCheckPingTimer(){clearTimeout(this._checkPingTimer)}async _pingHandler(e){var t,r,i;this._clearCheckPingTimer(),this._checkPingTimer=setTimeout((()=>{this.logger.debug("Timeout waiting for ping"),this._closeConnection("reconnecting")}),this._checkPingDelay),await this.execute((r=e.id,i=null==(t=null==e?void 0:e.params)?void 0:t.timestamp,Ir({id:r,result:{timestamp:i||Date.now()/1e3}})))}async _eventAcknowledgingHandler(e){const{method:t,id:r}=e;return"signalwire.event"===t?this.execute((e=>Ir({id:e,result:{}}))(r)):Promise.resolve()}_checkCurrentStatus(){switch(this._status){case"disconnecting":if(this._requests.size>0)return;this._requests.clear(),this._closeConnection("disconnected");break;case"disconnected":this.dispatch(ei());break;case"reconnecting":this.wsCloseHandler(new this.CloseEventConstructor("close",{reason:"Client-side closed"}))}}_closeConnection(e){this._clearCheckPingTimer(),this.logger.debug("Close Connection:",e),this._status=e,this.dispatch(li.authStatus("disconnected"===e?"unauthorized":"unknown")),this._removeSocketListeners();const t=!!this._socket;this.destroySocket(),"disconnected"!==e&&t||this._checkCurrentStatus()}},pi=class extends mi{constructor(e){super(e),this.options=e,Nt(this,"_expiredDiffSeconds",0),Nt(this,"_refreshTokenNotificationDiff",120),Nt(this,"_checkTokenExpirationDelay",2e4),Nt(this,"_checkTokenExpirationTimer",null),this._checkTokenExpiration=this._checkTokenExpiration.bind(this),this.reauthenticate=this.reauthenticate.bind(this)}get expiresAt(){var e;if(!(null==this?void 0:this._rpcConnectResult))return 0;const{authorization:t}=this._rpcConnectResult,r=null!=(e=kr(t)?t.fabric_subscriber.expires_at:null==t?void 0:t.expires_at)?e:0;if("string"==typeof r){const e=Date.parse(r);if(!isNaN(e))return Math.floor(e/1e3)}return r}get expiresIn(){const e=Math.floor(Date.now()/1e3);return this.expiresAt-e}get expired(){return this.expiresAt>0&&this.expiresIn<=this._expiredDiffSeconds}async authenticate(){const e=Lt(Ot({},this._connectParams),{authentication:{jwt_token:this.options.token}});if(this._relayProtocolIsValid())e.protocol=this.relayProtocol;else{const t=await this.retrieveRelayProtocol();t&&(e.protocol=t)}if(e.protocol){const t=await this.retrieveSwAuthorizationState();t&&(e.authorization_state=t)}try{this._rpcConnectResult=await this.execute(Pr(e)),await this.persistRelayProtocol(),await this._checkTokenExpiration()}catch(e){if(this.logger.debug("BaseJWTSession authenticate error",e),"Requester validation failed"===e.message)return this.removeRelayProtocol(),this.removeSwAuthorizationState(),this.removePrevCallId(),void await this.authenticate();throw e}}async retrieveRelayProtocol(){return""}async persistRelayProtocol(){}removeRelayProtocol(){}removeSwAuthorizationState(){}removePrevCallId(){}async reauthenticate(){if(this.logger.debug("Session Reauthenticate",{ready:this.ready,expired:this.expired}),!this.ready||this.expired)return this.connect();const e={project:this._rpcConnectResult.authorization.project_id,jwt_token:this.options.token};try{this._rpcConnectResult=await this.execute(Mr(e))}catch(e){throw clearTimeout(this._checkTokenExpirationTimer),e}}_onSocketClose(e){clearTimeout(this._checkTokenExpirationTimer),super._onSocketClose(e)}async _checkTokenExpiration(){if(!this.expiresAt)return;const e=this.options.onRefreshToken;if(this.expiresIn<=this._refreshTokenNotificationDiff)if(this.dispatch(Yr()),"function"==typeof e)try{const t=await e();this.dispatch(Jr({token:t}))}catch(e){this.logger.error(e)}else this.logger.warn("The token is going to expire!");clearTimeout(this._checkTokenExpirationTimer),this.expired||(this._checkTokenExpirationTimer=setTimeout(this._checkTokenExpiration,this._checkTokenExpirationDelay))}},gi={};Dt(gi,{authErrorAction:()=>Qr,authExpiringAction:()=>Yr,authSuccessAction:()=>Xr,configureStore:()=>zi,connect:()=>$i,createAction:()=>Br,createCatchableSaga:()=>Si,createRestartableSaga:()=>wi,destroyAction:()=>Gr,eventChannel:()=>rt,getCustomSagaActionType:()=>ni,initAction:()=>Kr,makeCustomSagaAction:()=>oi,reauthAction:()=>Jr,sessionDisconnectedAction:()=>ei,sessionForceCloseAction:()=>ri,sessionReconnectingAction:()=>ti,socketMessageAction:()=>Zr});var fi=ai({name:"components",initialState:{byId:{}},reducers:{upsert:(e,{payload:t})=>Lt(Ot({},e),t.id in e.byId?{byId:Lt(Ot({},e.byId),{[t.id]:Ot(Ot({},e.byId[t.id]),t)})}:{byId:Lt(Ot({},e.byId),{[t.id]:t})}),cleanup:(e,{payload:t})=>Lt(Ot({},e),{byId:Object.entries(e.byId).reduce(((e,[r,i])=>(t.ids.includes(r)||(e[r]=i),e)),{})})}}),{actions:vi,reducer:yi}=fi,bi=(0,zr.combineReducers)({components:yi,session:ui}),_i={};Dt(_i,{createCatchableSaga:()=>Si,createRestartableSaga:()=>wi,eventChannel:()=>rt});var wi=e=>function*(){!function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return o=De.apply(void 0,[e].concat(r)),Ae(Ee,G({},o.payload,{detached:!0}));var o}((function*(){for(;;)try{Zt().debug("Run a restartable saga"),yield je(e),Zt().debug("One of the restartable saga has ended. Restarting..")}catch(e){Zt().error("Restartable Saga Error",e)}}))},ki=e=>Zt().error("Catchable Saga Error",e),Si=(e,t=ki)=>function*(...r){try{yield je(e,...r)}catch(e){t(e)}};function*Ci({sessionChannel:e,swEventChannel:t,session:r}){function*i(e){if(yield Oe(t,(e=>{const{event_type:t,params:r,node_id:i}=e;if("queuing.relay.tasks"===t)return{type:t,payload:e};if(ir(t)&&(null==r?void 0:r.jsonrpc)){const e=r;return e.params&&(e.params.nodeId=i),{type:t,payload:e}}return{type:t,payload:r}})(e)),!(e=>ir(null==e?void 0:e.event_type))(e)&&!(e=>{var t;return!!(null==(t=null==e?void 0:e.event_type)?void 0:t.startsWith("video."))})(e))return(e=>"signalwire.authorization.state"===(null==e?void 0:e.event_type))(e)?(r.onSwAuthorizationState(e.params.authorization_state),void(yield Oe(li.updateAuthorizationState(e.params.authorization_state)))):void(yield Oe({type:e.event_type,payload:e}))}Zt().debug("sessionChannelWatcher [started]");const o=Si((function*(e){if(e.type!==Zr.type)return void(yield Oe(e));const{method:t,params:r}=e.payload;if("signalwire.event"!==t)return Zt().debug(`Unknown message: ${t}`,e);yield De(i,r)}),(e=>{Zt().error("Channel Error",e)}));for(;;)try{for(;;){const t=yield xe(e);yield De(o,t)}}catch(e){Zt().error("sessionChannelWorker error:",e)}finally{Zt().debug("sessionChannelWorker [finally]")}}var Ii=class e extends Error{constructor(t,r){super(r),this.code=t,this.message=r,Nt(this,"name","AuthError"),Object.setPrototypeOf(this,e.prototype)}},Ti=class e extends Error{constructor(t,r,i){super(r),this.code=t,this.message=r,this.response=i,Nt(this,"name","HttpError"),Object.setPrototypeOf(this,e.prototype)}},Ei=class extends Error{constructor(e){super(e),this.name="CapabilityError"}};function*Pi({initSession:e,sessionEmitter:t,userOptions:r,channels:i}){var o;Zt().debug("sessionSaga [started]");const n=e(),s=i.swEventChannel,a=i.sessionChannel;let c=[];if(null==(o=r.workers)?void 0:o.length)try{const e=r.workers.map((e=>je(wi(e))));c=yield function(e){var t=Ae("ALL",e);return t.combinator=!0,t}(e)}catch(e){Zt().error("Error running custom workers",e)}const d=yield De(Ci,{session:n,sessionChannel:a,swEventChannel:s}),l=yield De(Ri,{session:n,sessionEmitter:t,sessionChannel:a,userOptions:r});n.connect(),yield xe(Gr.type),n.disconnect(),yield xe(ei.type),t.emit("session.disconnected"),l.cancel(),d.cancel(),c.forEach((e=>e.cancel())),s.close(),a.close(),Zt().debug("sessionSaga [ended]")}function*Mi({session:e,token:t,sessionEmitter:r}){try{e.reauthenticate&&(e.token=t,yield je(e.reauthenticate),yield Oe(li.connected(e.rpcConnectResult)),r.emit("session.connected"))}catch(t){Zt().error("Reauthenticate Error",t),e.authError(t)}}function*Ri(e){Zt().debug("sessionStatusWatcher [started]");const{session:t,sessionEmitter:r}=e;try{for(;;){const i=yield xe([Xr.type,Qr.type,Yr.type,Jr.type,ti.type,ri.type]);switch(Zt().debug("sessionStatusWatcher",i.type,i.payload),i.type){case Xr.type:yield Oe(li.connected(t.rpcConnectResult)),r.emit("session.connected");break;case Qr.type:yield De(Ai,Lt(Ot({},e),{action:i}));break;case Yr.type:r.emit("session.expiring");break;case Jr.type:yield De(Mi,{session:t,token:i.payload.token,sessionEmitter:r});break;case ti.type:r.emit("session.reconnecting");break;case ri.type:t.forceClose()}}}finally{(yield Ve())&&Zt().debug("sessionStatusWatcher [cancelled]")}}function*Ai(e){Zt().debug("sessionAuthErrorSaga [started]");try{const{action:t,sessionEmitter:r}=e,{error:i}=t.payload,o=i?new Ii(i.code,i.message):new Error("Unauthorized");r.emit("session.auth_error",o)}finally{(yield Ve())&&Zt().debug("sessionAuthErrorSaga [cancelled]")}}var xi={};Dt(xi,{getAuthError:()=>Di,getAuthStatus:()=>ji,getAuthorization:()=>Wi,getAuthorizationState:()=>Vi,getIceServers:()=>Oi,getProtocol:()=>Ni,getSession:()=>Li});var Oi=({session:e})=>{var t;return null!=(t=null==e?void 0:e.iceServers)?t:[]},Li=e=>e.session,ji=({session:e})=>e.authStatus,Di=({session:e})=>e.authError,Wi=({session:e})=>e.authorization,Vi=({session:e})=>e.authorizationState,Ni=({session:e})=>e.protocol,$i=e=>{const{sessionListeners:t={},store:r,Component:i,customSagas:o=[]}=e,n=Object.keys(t);return e=>{const s=new i(Lt(Ot({},e),{store:r})),a=/* @__PURE__ */new Map;let c=!0;const d=r.subscribe((()=>{const e=r.getState(),i=Li(e);for(const e of n){if(!1===c)return;const r=`session.${e}`,o=a.get(r),n=i[e];if(void 0!==n&&o!==n){a.set(r,n);const o=t[e];"string"==typeof o?s[o](i):"function"==typeof o&&o(i)}}})),l=null==o?void 0:o.map((e=>r.runSaga(e,{instance:s,runSaga:r.runSaga})));return s.destroyer=()=>{c=!1,d(),a.clear(),(null==l?void 0:l.length)&&l.forEach((e=>e.cancel()))},s}},Ui=()=>new St;Vt(gi,zr);var zi=e=>{var t;const{userOptions:r,SessionConstructor:i,preloadedState:o={},runRootSaga:n=!0}=e,s=function(e){var t,r=void 0===e?{}:e,i=r.context,o=void 0===i?{}:i,n=r.channel,s=void 0===n?ot():n,a=r.sagaMonitor,c=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(r,["context","channel","sagaMonitor"]);function d(e){return t=wt.bind(null,G({},c,{context:o,channel:s,dispatch:e.dispatch,getState:e.getState,sagaMonitor:a})),function(e){return function(t){a&&a.actionDispatched&&a.actionDispatched(t);var r=e(t);return s.put(t),r}}}return d.run=function(){return t.apply(void 0,arguments)},d.setContext=function(e){ce(o,e)},d}({sagaMonitor:r.sagaMonitor}),a=it(),c=tt(),d={swEventChannel:a,sessionChannel:c},l=qr({devTools:null==(t=null==r?void 0:r.devTools)||t,reducer:bi,preloadedState:o,middleware:e=>e().concat(s)}),u=(()=>{const e=/* @__PURE__ */new Map;return{get:t=>e.get(t),set:(t,r)=>(e.set(t,r),e),remove:t=>(e.delete(t),e),getAll:()=>Array.from(e.entries()),deleteAll:()=>(e.clear(),e)}})(),{initSession:h,getSession:m,sessionEmitter:p}=(e=>{const{SessionConstructor:t,userOptions:r,sessionChannel:i}=e,o=Ui();let n=null;return{session:n,initSession:()=>(n=new t(Lt(Ot({},r),{sessionChannel:i})),n),getSession:()=>(n||Zt().warn("Session does not exist!"),n),sessionEmitter:o}})({userOptions:r,sessionChannel:c,SessionConstructor:i});if(n){const e=(e=>function*({userOptions:t,channels:r}){for(Zt().debug("rootSaga [started]"),t.logger&&(Gt=t.logger),t.debug&&(e=>{null!=e?Object.assign(Qt,e):Qt={}})(t.debug);;){yield xe(Kr.type);try{yield je(Pi,Lt(Ot({},e),{userOptions:t,channels:r}));break}catch(e){Zt().error("RootSaga Error:",e)}finally{(yield Ve())&&Zt().debug("rootSaga [cancelled]"),Zt().debug("Reboot rootSaga")}}Zt().debug("rootSaga [finished]")})({initSession:h,sessionEmitter:p});s.run(e,{userOptions:r,channels:d})}return Lt(Ot({},l),{runSaga:(e,t)=>s.run(e,Lt(Ot({},t),{channels:d,getSession:m,instanceMap:u})),channels:d,instanceMap:u,sessionEmitter:p})},Bi=function*(e){const{initialState:t,onDone:r,onFail:i,getSession:o}=e,{requestId:n,method:s,params:a}=t,c=o();if(!c){const e=new Error("Session does not exist!");return Zt().error(e),void(null==i||i(e))}try{let e=(({method:e,params:t})=>Cr({method:e,params:t}))({id:n,method:s,params:a});const t=yield je(c.execute,e);null==r||r(t)}catch(e){Zt().warn("Execute error: ",e),null==i||i(e)}},Fi=e=>e,Hi=Symbol("BaseComponent"),qi=class{constructor(e){this.options=e,Nt(this,"__sw_symbol",Hi),Nt(this,"uuid",b()),Nt(this,"_customSagaTriggers",/* @__PURE__ */new Map),Nt(this,"_destroyer"),Nt(this,"eventEmitter"),Nt(this,"_runningWorkers",[]),Nt(this,"_workers",/* @__PURE__ */new Map),this.eventEmitter=new St}get __uuid(){return this.uuid}get logger(){return Zt()}set destroyer(e){this._destroyer=e}get store(){return this.options.store}get instanceMap(){return this.store.instanceMap}get emitter(){return this.eventEmitter}get sessionEmitter(){return this.store.sessionEmitter}get session(){return this.sessionEmitter}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){return this.emitter.off(e,t)}removeAllListeners(e){return e?this.off(e):(this.eventNames().forEach((e=>{this.off(e)})),this.emitter)}eventNames(){return this.emitter.eventNames()}sessionEventNames(){return this.sessionEmitter.eventNames()}getSubscriptions(){return br(this.eventNames())}emit(e,...t){return this.emitter.emit(e,...t)}listenerCount(e){return this.emitter.listenerCount(e)}destroy(){var e;null==(e=this._destroyer)||e.call(this),this.removeAllListeners(),this.detachWorkers()}execute({method:e,params:t},{transformParams:r=Fi,transformResolve:i=Fi,transformReject:o=Fi}={transformParams:Fi,transformResolve:Fi,transformReject:Fi}){return new Promise(((n,s)=>{const a=b();this.runWorker("executeActionWorker",{worker:Bi,onDone:e=>n(i(e)),onFail:e=>s(o(e)),initialState:{requestId:a,componentId:this.__uuid,method:e,params:r(t)}})}))}triggerCustomSaga(e){return new Promise(((t,r)=>{const i=b();this._customSagaTriggers.set(i,{resolve:t,reject:r}),this.store.dispatch(Ot({dispatchId:i},oi(this.__uuid,e)))}))}settleCustomSagaTrigger({dispatchId:e,payload:t,kind:r}){const i=this._customSagaTriggers.get(e);i&&(i[r](t),this._customSagaTriggers.delete(e))}select(e){return e(this.store.getState())}getStateProperty(e){return this[e]}get _sessionAuthStatus(){return this.select(ji)}get _sessionAuthorization(){return this.select(Wi)}_waitUntilSessionAuthorized(){switch(this._sessionAuthStatus){case"authorized":return Promise.resolve(this);case"unknown":case"authorizing":return new Promise(((e,t)=>{const r=this.store.subscribe((()=>{const i=this.select(ji),o=this.select(Di);if("authorized"===i)e(this),r();else if("unauthorized"===i){const e=o?new Ii(o.code,o.message):new Error("Unauthorized");t(e),r()}}))}));case"unauthorized":return Promise.reject(new Error("Unauthorized"))}}runWorker(e,t){return this._workers.has(e)?Zt().warn(`[runWorker] Worker with name ${e} has already been registerd.`):this._setWorker(e,t),this._attachWorker(e,t)}cancelWorker(e){const t=this._runningWorkers.findIndex((t=>t===e));t>-1&&(this._runningWorkers.splice(t,1),e.cancel())}_setWorker(e,t){this._workers.set(e,t)}_attachWorker(e,t){var r=t,{worker:i}=r,o=jt(r,["worker"]);const n=this.store.runSaga(i,Ot({instance:this,runSaga:this.store.runSaga},o));return this._runningWorkers.push(n),this._workers.delete(e),n}detachWorkers(){this._runningWorkers.forEach((e=>{e.cancel()})),this._runningWorkers=[]}},Ki=class extends qi{constructor(e){super(e),this.options=e}connect(){const e=ji(this.store.getState());return"unknown"!==e&&"unauthorized"!==e||this.store.dispatch(Kr()),this._waitUntilSessionAuthorized()}disconnect(){this.store.dispatch(Gr())}removeAllListeners(e){return this.sessionEventNames().forEach((e=>{this.sessionEmitter.off(e)})),super.removeAllListeners(e)}},Gi=class extends qi{constructor(e){super(e),this.options=e,Nt(this,"subscribeMethod","signalwire.subscribe"),Nt(this,"subscribeParams",{}),Nt(this,"_latestExecuteParams");const t=()=>{this._latestExecuteParams=void 0};super.session.on("session.connected",t),super.session.on("session.disconnected",t),super.session.on("session.reconnecting",t)}shouldExecuteSubscribe(e){return!this._latestExecuteParams||JSON.stringify(e)!==JSON.stringify(this._latestExecuteParams)}async subscribe(){await this._waitUntilSessionAuthorized();const e=this.getSubscriptions();if(0===e.length)return void this.logger.debug("`subscribe()` was called without any listeners attached.");const t={method:this.subscribeMethod,params:Lt(Ot({},this.subscribeParams),{event_channel:this.getStateProperty("eventChannel"),events:e})};if(this.shouldExecuteSubscribe(t))return this._latestExecuteParams=t,new Promise((async(e,r)=>{try{return await this.execute(t),e(void 0)}catch(e){return r(e)}}));this.logger.debug("BaseConsumer.subscribe() - Skipped .execute() since the execParams are exactly the same as last time")}},Ji={audio_muted:!0,video_muted:!0,deaf:!0,visible:!0,input_volume:1,output_volume:1,input_sensitivity:1};Object.keys(Ji).map((e=>`video.member.updated.${e}`));var Qi=ar(Ji);Object.keys(Qi).map((e=>`member.updated.${e}`));var Xi={};Dt(Xi,{getComponent:()=>Yi,getComponentsById:()=>Zi,getComponentsToCleanup:()=>eo});var Yi=({components:e},t)=>{var r;return null==(r=e.byId)?void 0:r[t]},Zi=({components:e})=>e.byId,eo=e=>{const t=Zi(e);let r=[];return Object.keys(t).forEach((e=>{(t[e].responses||t[e].errors)&&r.push(e)})),r},to={audio_muted:!0,video_muted:!0,deaf:!0,visible:!0,input_volume:1,output_volume:1,input_sensitivity:1,handraised:!0,echo_cancellation:!0,auto_gain:!0,noise_suppression:!0};Object.keys(to).map((e=>`member.updated.${e}`));var ro=ar(to);Object.keys(ro).map((e=>`member.updated.${e}`));var io={};Dt(io,{RoomSessionPlaybackAPI:()=>Xo,RoomSessionRecordingAPI:()=>Jo,RoomSessionStreamAPI:()=>Zo,audioMuteMember:()=>Mo,audioUnmuteMember:()=>Ro,createRoomSessionPlaybackObject:()=>Yo,createRoomSessionRecordingObject:()=>Qo,createRoomSessionStreamObject:()=>en,deafMember:()=>Oo,deleteMemberMeta:()=>Ko,deleteMeta:()=>Io,demote:()=>$o,getLayouts:()=>ao,getMemberMeta:()=>Fo,getMembers:()=>co,getMeta:()=>ko,getPlaybacks:()=>bo,getRecordings:()=>vo,getStreams:()=>To,hideVideoMuted:()=>ho,lock:()=>po,play:()=>_o,promote:()=>No,removeAllMembers:()=>Bo,removeMember:()=>zo,setDeaf:()=>jo,setHideVideoMuted:()=>fo,setInputSensitivityMember:()=>Vo,setInputVolumeMember:()=>Do,setLayout:()=>lo,setMemberMeta:()=>Ho,setMemberPosition:()=>Uo,setMeta:()=>So,setOutputVolumeMember:()=>Wo,setPositions:()=>uo,setPrioritizeHandraise:()=>Po,setRaisedHand:()=>Go,showVideoMuted:()=>mo,startRecording:()=>yo,startStream:()=>Eo,undeafMember:()=>Lo,unlock:()=>go,updateMemberMeta:()=>qo,updateMeta:()=>Co,videoMuteMember:()=>Ao,videoUnmuteMember:()=>xo});var oo=()=>{},no=(e,t={})=>({value:function(r={}){return this.execute({method:e,params:Ot({room_session_id:this.roomSessionId},r)},t)}}),so=(e,t={})=>({value:function(r={}){var i=r,{memberId:o}=i,n=jt(i,["memberId"]);return this.execute({method:e,params:Ot({room_session_id:this.roomSessionId,member_id:o||this.memberId},n)},t)}}),ao=no("video.list_available_layouts",{transformResolve:e=>({layouts:e.layouts})}),co=no("video.members.get",{transformResolve:e=>({members:e.members})}),lo=no("video.set_layout",{transformResolve:oo}),uo=no("video.set_position",{transformResolve:oo}),ho=no("video.hide_video_muted",{transformResolve:oo}),mo=no("video.show_video_muted",{transformResolve:oo}),po=no("video.lock",{transformResolve:oo}),go=no("video.unlock",{transformResolve:oo}),fo={value:function(e){return this.execute({method:e?"video.hide_video_muted":"video.show_video_muted",params:{room_session_id:this.roomSessionId}},{transformResolve:oo})}},vo={value:function(){return new Promise((async(e,t)=>{try{const{recordings:t}=await this.execute({method:"video.recording.list",params:{room_session_id:this.roomSessionId}}),r=[];t.forEach((e=>{let t=this.instanceMap.get(e.id);t?t.setPayload({room_id:this.roomId,room_session_id:this.roomSessionId,recording:e}):t=Qo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,recording:e}}),r.push(t),this.instanceMap.set(t.id,t)})),e({recordings:r})}catch(e){t(e)}}))}},yo={value:function(){return new Promise((async(e,t)=>{try{const{recording:t}=await this.execute({method:"video.recording.start",params:{room_session_id:this.roomSessionId}}),r=Qo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,recording:t}});this.instanceMap.set(r.id,r),e(r)}catch(e){t(e)}}))}},bo={value:function(){return new Promise((async(e,t)=>{try{const{playbacks:t}=await this.execute({method:"video.playback.list",params:{room_session_id:this.roomSessionId}}),r=[];t.forEach((e=>{let t=this.instanceMap.get(e.id);t?t.setPayload({room_id:this.roomId,room_session_id:this.roomSessionId,playback:e}):t=Yo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,playback:e}}),r.push(t),this.instanceMap.set(t.id,t)})),e({playbacks:r})}catch(e){t(e)}}))}},_o={value:function(e){var t=e,{seekPosition:r,currentTimecode:i}=t,o=jt(t,["seekPosition","currentTimecode"]);return new Promise((async(e,t)=>{try{const t=r||i,{playback:n}=await this.execute({method:"video.playback.start",params:Ot({room_session_id:this.roomSessionId,seek_position:t},o)}),s=Yo({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,playback:n}});this.instanceMap.set(s.id,s),e(s)}catch(e){t(e)}}))}},wo=e=>no(e,{transformResolve:oo,transformParams:e=>{const t=e,{room_session_id:r}=t;return{room_session_id:r,meta:jt(t,["room_session_id"])}}}),ko=no("video.get_meta",{transformResolve:({meta:e})=>({meta:e})}),So=wo("video.set_meta"),Co=wo("video.update_meta"),Io={value:function(e){return this.execute({method:"video.delete_meta",params:{room_session_id:this.roomSessionId,keys:e}})}},To={value:function(){return new Promise((async(e,t)=>{try{const{streams:t}=await this.execute({method:"video.stream.list",params:{room_session_id:this.roomSessionId}}),r=[];t.forEach((e=>{let t=this.instanceMap.get(e.id);t?t.setPayload({room_id:this.roomId,room_session_id:this.roomSessionId,stream:e}):t=en({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,stream:e}}),r.push(t),this.instanceMap.set(t.id,t)})),e({streams:r})}catch(e){t(e)}}))}},Eo={value:function(e){return new Promise((async(t,r)=>{try{const{stream:r}=await this.execute({method:"video.stream.start",params:Ot({room_session_id:this.roomSessionId},e)}),i=en({store:this.store,payload:{room_id:this.roomId,room_session_id:this.roomSessionId,stream:r}});this.instanceMap.set(i.id,i),t({stream:i})}catch(e){r(e)}}))}},Po={value:function(e){return this.execute({method:"video.prioritize_handraise",params:{room_session_id:this.roomSessionId,enable:e}})}},Mo=so("video.member.audio_mute",{transformResolve:oo}),Ro=so("video.member.audio_unmute",{transformResolve:oo}),Ao=so("video.member.video_mute",{transformResolve:oo}),xo=so("video.member.video_unmute",{transformResolve:oo}),Oo=so("video.member.deaf",{transformResolve:oo}),Lo=so("video.member.undeaf",{transformResolve:oo}),jo={value:function(e){return this.execute({method:e?"video.member.deaf":"video.member.undeaf",params:{room_session_id:this.roomSessionId,member_id:this.memberId}},{transformResolve:oo})}},Do=so("video.member.set_input_volume",{transformResolve:oo}),Wo=so("video.member.set_output_volume",{transformResolve:oo}),Vo=so("video.member.set_input_sensitivity",{transformResolve:oo}),No={value:function(e){var t=e,{memberId:r,mediaAllowed:i,joinAudioMuted:o,joinVideoMuted:n}=t,s=jt(t,["memberId","mediaAllowed","joinAudioMuted","joinVideoMuted"]);return this.execute({method:"video.member.promote",params:Ot({room_session_id:this.roomSessionId,member_id:r,media_allowed:i,join_audio_muted:o,join_video_muted:n},s)},{transformResolve:oo})}},$o={value:function({memberId:e,mediaAllowed:t}){return this.execute({method:"video.member.demote",params:{room_session_id:this.roomSessionId,member_id:e,media_allowed:t}},{transformResolve:oo})}},Uo=so("video.member.set_position",{transformResolve:oo}),zo={value:function(e){var t=e,{memberId:r}=t,i=jt(t,["memberId"]);if(!r)throw new TypeError('Invalid or missing "memberId" argument');return this.execute({method:"video.member.remove",params:Ot({room_session_id:this.roomSessionId,member_id:r},i)},{transformResolve:oo})}},Bo={value:function(){return this.execute({method:"video.member.remove",params:{room_session_id:this.roomSessionId,member_id:"all"}},{transformResolve:oo})}},Fo=so("video.member.get_meta",{transformResolve:({meta:e})=>({meta:e})}),Ho=so("video.member.set_meta",{transformResolve:oo}),qo=so("video.member.update_meta",{transformResolve:oo}),Ko=so("video.member.delete_meta",{transformResolve:oo}),Go={value:function(e){const{raised:t=!0,memberId:r=this.memberId}=e||{};if(!r)throw new TypeError('Invalid or missing "memberId" argument');return this.execute({method:t?"video.member.raisehand":"video.member.lowerhand",params:{room_session_id:this.roomSessionId,member_id:r}},{transformResolve:oo})}},Jo=class extends qi{constructor(e){super(e),Nt(this,"_payload"),this._payload=e.payload}get id(){return this._payload.recording.id}get roomId(){return this._payload.room_id}get roomSessionId(){return this._payload.room_session_id}get state(){return this._payload.recording.state}get duration(){return this._payload.recording.duration}get startedAt(){if(this._payload.recording.started_at)return new Date(1e3*this._payload.recording.started_at)}get endedAt(){if(this._payload.recording.ended_at)return new Date(1e3*this._payload.recording.ended_at)}setPayload(e){this._payload=e}async pause(){await this.execute({method:"video.recording.pause",params:{room_session_id:this.getStateProperty("roomSessionId"),recording_id:this.getStateProperty("id")}})}async resume(){await this.execute({method:"video.recording.resume",params:{room_session_id:this.getStateProperty("roomSessionId"),recording_id:this.getStateProperty("id")}})}async stop(){await this.execute({method:"video.recording.stop",params:{room_session_id:this.getStateProperty("roomSessionId"),recording_id:this.getStateProperty("id")}})}},Qo=e=>$i({store:e.store,Component:Jo})(e),Xo=class extends qi{constructor(e){super(e),Nt(this,"_payload"),this._payload=e.payload}get id(){return this._payload.playback.id}get roomId(){return this._payload.room_id}get roomSessionId(){return this._payload.room_session_id}get url(){return this._payload.playback.url}get state(){return this._payload.playback.state}get volume(){return this._payload.playback.volume}get startedAt(){if(this._payload.playback.started_at)return new Date(1e3*this._payload.playback.started_at)}get endedAt(){if(this._payload.playback.ended_at)return new Date(1e3*this._payload.playback.ended_at)}get position(){return this._payload.playback.position}get seekable(){return this._payload.playback.seekable}setPayload(e){this._payload=e}async pause(){await this.execute({method:"video.playback.pause",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id")}})}async resume(){await this.execute({method:"video.playback.resume",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id")}})}async stop(){await this.execute({method:"video.playback.stop",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id")}})}async setVolume(e){await this.execute({method:"video.playback.set_volume",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),volume:e}})}async seek(e){await this.execute({method:"video.playback.seek_absolute",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),position:Math.abs(e)}})}async forward(e=5e3){await this.execute({method:"video.playback.seek_relative",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),position:Math.abs(e)}})}async rewind(e=5e3){await this.execute({method:"video.playback.seek_relative",params:{room_session_id:this.getStateProperty("roomSessionId"),playback_id:this.getStateProperty("id"),position:-Math.abs(e)}})}},Yo=e=>$i({store:e.store,Component:Xo})(e),Zo=class extends qi{constructor(e){super(e),Nt(this,"_payload"),this._payload=e.payload}get id(){return this._payload.stream.id}get roomId(){return this._payload.room_id}get roomSessionId(){return this._payload.room_session_id}get state(){return this._payload.stream.state}get duration(){return this._payload.stream.duration}get url(){return this._payload.stream.url}get startedAt(){if(this._payload.stream.started_at)return new Date(1e3*this._payload.stream.started_at)}get endedAt(){if(this._payload.stream.ended_at)return new Date(1e3*this._payload.stream.ended_at)}setPayload(e){this._payload=e}async stop(){await this.execute({method:"video.stream.stop",params:{room_session_id:this.getStateProperty("roomSessionId"),stream_id:this.getStateProperty("id")}})}},en=e=>$i({store:e.store,Component:Zo})(e),tn={};Dt(tn,{BaseChatAPI:()=>kn,BaseChatConsumer:()=>wn,ChatMember:()=>In,ChatMessage:()=>Cn,applyCommonMethods:()=>Pn,createBaseChatObject:()=>Sn,getMemberState:()=>mn,getMembers:()=>ln,getMessages:()=>dn,publish:()=>cn,setMemberState:()=>hn});var rn=e=>{const t=!e||Array.isArray(e)?e:[e];return Array.isArray(t)?t.map((e=>({name:e}))):[]},on=e=>Array.isArray(e)||"string"==typeof e,nn=()=>{},sn=(e,t={})=>({value:function(r={}){return this.execute({method:e,params:r},t)}}),an=(e,t={})=>({value:function(r={}){var i=r,{memberId:o}=i,n=jt(i,["memberId"]);return this.execute({method:e,params:Ot({member_id:o},n)},t)}}),cn=sn("chat.publish",{transformResolve:nn}),dn=sn("chat.messages.get",{transformResolve:e=>({messages:e.messages.map((e=>ar(e))),cursor:e.cursor})}),ln=sn("chat.members.get",{transformResolve:e=>({members:e.members.map((e=>ar(e)))})}),un=e=>{const t=on(null==e?void 0:e.channels)?rn(e.channels):void 0;return Lt(Ot({},e),{channels:t})},hn=an("chat.member.set_state",{transformResolve:nn,transformParams:un}),mn=an("chat.member.get_state",{transformResolve:e=>({channels:e.channels}),transformParams:un}),pn={};Dt(pn,{BasePubSubConsumer:()=>vn,PubSubMessage:()=>bn,createBasePubSubObject:()=>yn});var gn=function*(e){Zt().trace("pubSubWorker started");const{instance:t,channels:{swEventChannel:r}}=e;function*i(e){const{type:r,payload:i}=e;switch(r){case`${zt}.channel.message`:{const{channel:e,message:r}=i,o=jt(r,["member"]),n=ar(Lt(Ot({},o),{channel:e})),s=new bn(n);t.emit("message",s);break}default:Zt().warn(`Unknown pubsub event: "${r}"`)}}const o=e=>e.type.startsWith(`${zt}.`);for(;;){const e=yield xe(r,o);yield De(i,e)}Zt().trace("pubSubWorker ended")},fn=e=>e.map((e=>({name:e}))),vn=class extends Gi{constructor(e){super(e),Nt(this,"subscribeMethod",`${zt}.subscribe`),this.initWorker()}initWorker(){this.runWorker("pubSub",{worker:gn})}_getChannelsParam(e,t){const r=!e||Array.isArray(e)?e:[e];if(!Array.isArray(r)||0===r.length)throw new Error(`Please specify one or more channels when calling .${t}()`);return{channels:fn(r)}}_setSubscribeParams(e){this.subscribeParams=Ot(Ot({},this.subscribeParams),e)}_getSubscribeParams({channels:e}){return Ot({},this._getChannelsParam(e,"subscribe"))}_getUnsubscribeParams({channels:e}){const t=this._getChannelsParam(e,"unsubscribe");return Ot({},t)}_checkMissingSubscriptions(){0===this.getSubscriptions().length&&(this.logger.info("Subscribe was called before any listeners were attached. Move `.subscribe()` right after your event listeners to suppress this message."),this.once("message",(()=>{})))}getSubscriptions(){const e=this.eventNames().map((e=>`${zt}.${String(e)}`));return br(e)}async subscribe(e){this._checkMissingSubscriptions();const t=this._getSubscribeParams({channels:e});return this._setSubscribeParams(t),super.subscribe()}async unsubscribe(e){if("unknown"===this._sessionAuthStatus||"unauthorized"===this._sessionAuthStatus)throw new Error("You must be authenticated to unsubscribe from a channel");const t=this._getUnsubscribeParams({channels:e});return new Promise((async(e,r)=>{const i=this.getSubscriptions();if(i.length>0){const e={method:`${zt}.unsubscribe`,params:Lt(Ot({},t),{events:i})};try{await this.execute(e)}catch(e){return r(e)}}else this.logger.warn("`unsubscribe()` was called without any listeners attached.");return e()}))}updateToken(e){return new Promise(((t,r)=>{this.session.once("session.auth_error",(e=>{r(e)})),this.session.once("session.connected",(()=>{t()})),this.store.dispatch(Ur.reauthAction({token:e}))}))}publish(e){return this.execute({method:`${zt}.publish`,params:e})}async getAllowedChannels(){await this._waitUntilSessionAuthorized();const e=this.select(Wi);return e&&"channels"in e&&e.channels?e.channels:{}}},yn=e=>$i({store:e.store,Component:vn})(e),bn=class{constructor(e){this.payload=e}get id(){return this.payload.id}get channel(){return this.payload.channel}get content(){return this.payload.content}get meta(){return this.payload.meta}get publishedAt(){return this.payload.publishedAt}},_n=function*(e){Zt().trace("chatWorker started");const{instance:t,channels:{swEventChannel:r}}=e;function*i(e){const{type:r,payload:i}=e;switch(r){case"chat.channel.message":{const{channel:e,message:r}=i,o=ar(Lt(Ot({},r),{channel:e})),n=new Cn(o);t.emit("message",n);break}case"chat.member.joined":case"chat.member.updated":case"chat.member.left":{const{member:e}=i,o=ar(e),n=new In(o),s=ur(r);t.emit(s,n);break}default:Zt().warn(`Unknown chat event: "${r}"`)}}const o=e=>e.type.startsWith("chat.");for(;;){const e=yield xe(r,o);yield De(i,e)}Zt().trace("chatWorker ended")},wn=class extends vn{constructor(e){super(e),Nt(this,"subscribeMethod","chat.subscribe")}initWorker(){this.runWorker("chat",{worker:_n})}},kn=lr(wn,{publish:cn,getMembers:ln,getMessages:dn,setMemberState:hn,getMemberState:mn}),Sn=e=>$i({store:e.store,Component:kn})(e),Cn=class extends bn{get member(){return this.payload.member}},In=class{constructor(e){this.payload=e}get id(){return this.payload.id}get channel(){return this.payload.channel}get state(){var e;return null!=(e=this.payload.state)?e:{}}},Tn=e=>{const t=on(null==e?void 0:e.channels)?rn(e.channels):void 0;return Lt(Ot({},e),{channels:t})},En=()=>{};function Pn(e){return class extends e{getMembers(e){return this._client.execute({method:"chat.members.get",params:e},{transformResolve:e=>({members:e.members.map((e=>ar(e)))})})}getMessages(e){return this._client.execute({method:"chat.messages.get",params:e},{transformResolve:e=>({messages:e.messages.map((e=>ar(e))),cursor:e.cursor})})}setMemberState(e={}){var t=e,{memberId:r}=t,i=jt(t,["memberId"]);return this._client.execute({method:"chat.member.set_state",params:Ot({member_id:r},i)},{transformResolve:En,transformParams:Tn})}getMemberState(e={}){var t=e,{memberId:r}=t,i=jt(t,["memberId"]);return this._client.execute({method:"chat.member.get_state",params:Ot({member_id:r},i)},{transformResolve:e=>({channels:e.channels}),transformParams:Tn})}}}var Mn={};Dt(Mn,{memberPositionWorker:()=>On,memberUpdatedWorker:()=>xn});var Rn=function*(e,t,r){const i=ur(e);r.emit(i,t)};function*An(e){const{action:t,memberList:r,instance:i,dispatcher:o=Rn}=e,n={};t.payload.layout.layers.forEach((e=>{var t;const i=e.member_id;if(!i)return;const o=r.get(i);o&&e.position!==(null==(t=o.member)?void 0:t.current_position)?(Ln({memberList:r,memberId:i,currentPosition:e.position}),n[i]=!0):n[i]=!1}));for(const[e,t]of r)if(n[e])yield null==o?void 0:o("video.member.updated",t,i);else if(void 0===n[e]){const t=Ln({memberList:r,memberId:e,currentPosition:"off-canvas"});if(!t)return;yield null==o?void 0:o("video.member.updated",t,i)}}function*xn({action:e,memberList:t,instance:r,dispatcher:i=Rn}){var o,n;const s=e.payload.member.id,a=Ln({memberList:t,memberId:s,currentPosition:null==(n=null==(o=t.get(s))?void 0:o.member)?void 0:n.current_position});if(!a)return;const{member:{updated:c=[]}}=e.payload,d=Lt(Ot({},a),{member:Ot(Ot({},a.member),e.payload.member)});t.set(s,d);for(const t of c){const o=`${e.type}.${t}`;yield null==i?void 0:i(o,d,r)}yield null==i?void 0:i(e.type,d,r)}var On=function*({instance:e,channels:t,initialState:r,getSession:i,instanceMap:o,dispatcher:n=Rn}){if(!r)return;const{swEventChannel:s}=t;let a=jn(r);const c=e=>{a.has(e.member.id)||a.set(e.member.id,e)};for(;;){const r=yield xe(s,(e=>"video.member.joined"===e.type||"video.member.updated"===e.type||"video.member.left"===e.type||"video.layout.changed"===e.type));switch(r.type){case"video.member.joined":c(r.payload);break;case"video.member.updated":c(r.payload),yield De(xn,{action:r,channels:t,memberList:a,instance:e,getSession:i,instanceMap:o,dispatcher:n});break;case"video.member.left":a.delete(r.payload.member.id);break;case"video.layout.changed":yield De(An,{action:r,channels:t,memberList:a,instance:e,dispatcher:n})}}},Ln=({memberList:e,memberId:t,currentPosition:r})=>{const i=e.get(t);if(!i)return;if(!r)return i;const o=Lt(Ot({},i),{member:Lt(Ot({},null==i?void 0:i.member),{current_position:r})});return e.set(t,o),o},jn=e=>{const t=e.room_session.members,r=/* @__PURE__ */new Map;return t.forEach((t=>{r.set(t.id,{room_id:e.room_session.room_id,room_session_id:e.room_session.id||e.room_session.room_session_id,member:t})})),r};Dt({},{configureFullStack:()=>$n,configureJestStore:()=>Nn,createMockedLogger:()=>Vn,createSessionChannel:()=>Fn,createSwEventChannel:()=>Bn,rpcConnectResultVRT:()=>zn,wait:()=>Un});var Dn="8f0a119a-cda7-4497-a47d-c81493b824d4",Wn="<VRT>",Vn=()=>({fatal:jest.fn(),error:jest.fn(),warn:jest.fn(),info:jest.fn(),debug:jest.fn(),trace:jest.fn(),wsTraffic:jest.fn()}),Nn=e=>zi(Ot({userOptions:{project:Dn,token:Wn,devTools:!1},SessionConstructor:mi,runRootSaga:!1},e)),$n=()=>{const e={dispatch:console.log,connect:jest.fn(),disconnect:jest.fn(),execute:jest.fn()},t=new St,r=zi({userOptions:{project:Dn,token:Wn,devTools:!1},SessionConstructor:jest.fn().mockImplementation((()=>e))});return r.dispatch(Ur.initAction()),r.dispatch(Ur.authSuccessAction()),{store:r,session:e,emitter:t,destroy:()=>r.dispatch(Ur.destroyAction())}},Un=e=>new Promise((t=>{setTimeout(t,e)})),zn={identity:"f3bc99df-2c3d-4fa4-b1dc-e8a8ffc579e6@e3fefa44-1bad-4be9-ad9b-1cbb9abd60c7.west-us",authorization:{type:"video",project_id:"8f0a119a-cda7-4497-a47d-c81493b824d4",project:"8f0a119a-cda7-4497-a47d-c81493b824d4",scopes:["video"],scope_id:"26675883-8499-4ee9-85eb-691c4aa209f8",resource:"9c80f1e8-9430-4070-a043-937eb3a96b38",join_as:"member",user_name:"Joe",room:{name:"lobby",display_name:"Lobby",scopes:["room.self.audio_mute","room.self.audio_unmute"],meta:{}},signature:"SGZtkRD9fvuBAOUp1UF56zESxdEvGT6qSGZtkRD9fvuBAOUp1UF56zESxdEvGT6q",media_allowed:"all",audio_allowed:"both",video_allowed:"both",meta:{}},protocol:"signalwire_SGZtkRD9fvuBAOUp1UF56zESxdEvGT6qSGZtkRD9fvuBAOUp1UF56zESxdEvGT6q_03e8c927-8ea3-4661-86d5-778c3e03296a_8f0a119a-cda7-4497-a47d-c81493b824d4",ice_servers:[{urls:"turn.swire.io:443",credential:"sFTwvi8ShXcYNOcyYjFy3ATIUpQ=",credentialType:"password",username:"1619521908:8f0a119a-cda7-4497-a47d-c81493b824d4"}]},Bn=()=>it(),Fn=()=>tt(),Hn=Ot({},xi);const qn=e=>new window.RTCPeerConnection(e),Kn=()=>"undefined"!=typeof navigator&&!!navigator.mediaDevices,Gn=()=>{if(!Kn())throw new Error("The media devices API isn't supported in this environment");return navigator.mediaDevices},Jn=()=>Gn().getSupportedConstraints(),Qn=e=>e&&e instanceof MediaStream,Xn=()=>"sinkId"in HTMLMediaElement.prototype,Yn=async(e,t)=>{if(null!==e)if("string"==typeof t)if(Xn())try{return await e.setSinkId(t)}catch(e){throw"SecurityError"===e.name?Zt().error(`You need to use HTTPS for selecting audio output device: ${e}`):Zt().error(`Error: ${e}`),e}else Zt().warn("Browser does not support output device selection.");else Zt().warn(`Invalid speaker deviceId: '${t}'`);else Zt().warn("No HTMLMediaElement to attach the speakerId")},Zn=e=>{var t;Qn(e)&&(null===(t=null==e?void 0:e.getTracks())||void 0===t||t.forEach(es))},es=e=>{e&&"live"===e.readyState&&(e.stop(),e.dispatchEvent(new Event("ended")))},ts={camera:"videoinput",microphone:"audioinput",speaker:"audiooutput"},rs=e=>{if(e)return ts[e]},is=()=>Gn().enumerateDevices(),os=async e=>{let t=await is().catch((e=>[]));return e&&(t=t.filter((({kind:t})=>t===e))),t},ns=async e=>{if("permissions"in navigator&&"function"==typeof navigator.permissions.query&&e)try{return"granted"===(await navigator.permissions.query({name:e})).state}catch(e){}return(async e=>{const t=await os(e);return t.length?t.every((({deviceId:e,label:t})=>Boolean(e&&t))):(Zt().warn(`No ${e} devices to check for permissions!`),null)})(rs(e))},ss=()=>ns("camera"),as=()=>ns("microphone"),cs=()=>ns("speaker"),ds=async(e={audio:!0,video:!0})=>{var t;try{const t=Gn().getUserMedia(e),r=await(async e=>{const t=[];return(null==e?void 0:e.audio)&&t.push(as()),(null==e?void 0:e.video)&&t.push(ss()),!!t.length&&(await Promise.all(t)).every(Boolean)})(e);if(r){const e=new Error("Timeout reading from your devices");return await fr(t,5e3,e)}return await t}catch(r){switch(r.name){case"Error":Zt().error(null!==(t=null==r?void 0:r.message)&&void 0!==t?t:"navigator.mediaDevices.getUserMedia doesn't seem to be supported.");break;case"NotFoundError":Zt().error("No media tracks of the type specified were found that satisfy the given constraints.");break;case"NotReadableError":Zt().error("Hardware error occurred at the operating system, browser, or Web page level which prevented access to the device. This could have been caused by having the Camera or Mic being user by another application.");break;case"OverconstrainedError":Zt().error(`The constraint: ${r.constraint} cannot be met by the selected device.`),Zt().info("List of available constraints:",Jn());break;case"NotAllowedError":Zt().error("The user has mostly likely denied access to the device. This could also happen if the browsing context is insecure (using HTTP rather than HTTPS)");break;case"TypeError":0===Object.keys(e).length?Zt().error('Constraints can\'t be empty nor have "video" and "audio" set to false.'):Zt().error("Please check that you are calling this method from a secure context (using HTTPS rather than HTTP).");break;case"SecurityError":Zt().error("User media support is disabled on the Document on which getUserMedia() was called. The mechanism by which user media support is enabled and disabled is left up to the individual user agent.")}throw r}},ls=e=>Gn().getDisplayMedia(e);var us={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;t.push("rtp"===r?1:"rtcp"===r?2:r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)r=i[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{i.push(void 0!==e.parameters[t]?t+"="+e.parameters[t]:t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],o=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&o?{usernameFragment:i.substring(12),password:o.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let o=3;o<i.length;o++){const n=i[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const i=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(i.parameters=o.length?t.parseFmtp(o[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),r.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const o=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{o.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let o=0;return r.codecs.forEach((e=>{e.maxptime>o&&(o=e.maxptime)})),o>0&&(i+="a=maxptime:"+o+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),o=-1!==i.fecMechanisms.indexOf("RED"),n=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),o&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:n?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach((e=>{e.maxBitrate=l}))),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const o=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=o.length>0,r.compound=0===o.length;const n=t.matchPrefix(e,"a=rtcp-mux");return r.mux=n.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return o.length>0?(r=o[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let o;i.length>0&&(o=parseInt(i[0].substring(19),10)),isNaN(o)&&(o=65536);const n=t.matchPrefix(e,"a=sctp-port:");if(n.length>0)return{port:parseInt(n[0].substring(12),10),protocol:r.fmt,maxMessageSize:o};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:o}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let o;const n=void 0!==r?r:2;return o=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+o+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(us);var hs=us.exports;const ms=e=>/^m=audio/.test(e),ps=e=>/^m=video/.test(e),gs=e=>{const t="\r\n",r=e.split(t),i=r.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const o=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),r=e.match(t);return r&&2==r.length?r[1]:null})(r[i]),n=new RegExp(`a=fmtp:${o}`),s=r.findIndex((e=>n.test(e)));return s>=0?/stereo=1;/.test(r[s])||(r[s]+="; stereo=1; sprop-stereo=1"):r[i]+=`${t}a=fmtp:${o} stereo=1; sprop-stereo=1`,r.join(t)},fs=e=>{try{const t=hs.getMediaSections(e);for(const e of t)if(!hs.splitLines(e).some((e=>0===e.indexOf("a=candidate")&&(e.includes("typ srflx")||e.includes("typ prflx")||e.includes("typ relay")))))return!1;return!0}catch(e){return Zt().error("Error checking SDP",e),!1}},vs=(e,t)=>{const r=(e=>e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"))(e).split("\n");let i=!1;const o=["inactive","recvonly","sendonly","sendrecv","stopped"];for(let e of r)if(e.startsWith("m="))i=e.startsWith(`m=${t}`);else if(i&&e.startsWith("a=")){const t=e.substring(2);if(o.includes(t))return t}return i?"sendrecv":"stopped"},ys=({localSdp:e,remoteSdp:t,media:r})=>{const i=(e=>{switch(e){case"sendrecv":return"sendrecv";case"sendonly":return"recvonly";case"recvonly":return"sendonly";default:return"inactive"}})(vs(e,r));return vs(t,r)===i},bs=async(e,t=!1)=>ws(e,t),_s=(e,t={})=>{const r=[];return e.filter((({deviceId:e,kind:i,groupId:o})=>{var n;if(!e||t.targets&&!(null===(n=t.targets)||void 0===n?void 0:n.includes(i)))return!1;if(!o)return!0;const s=`${i}-${o}`,a=!(null==t?void 0:t.excludeDefault)||"default"!==e;return!(r.includes(s)||!a||(r.push(s),0))}))},ws=async(e,t=!1)=>{let r;if(!1===await ns(e)){const t={audio:!(i=e)||"all"===i||"microphone"===i||"speaker"===i,video:!i||"all"===i||"camera"===i};r=await ds(t)}var i;const o=await os(rs(e));return r&&Zn(r),!0===t?o:_s(o)},ks=()=>ws("speaker"),Ss=async(e,t,r)=>{const i=await ws(r,!0);for(let r=0;r<i.length;r++){const{deviceId:o,label:n}=i[r];if(e===o||t===n)return o}return null},Cs=e=>{const t=new Map;return e.forEach((e=>{e.deviceId&&t.set(e.deviceId,e)})),t},Is={camera:ss,microphone:as,speaker:cs},Ts=["camera","microphone","speaker"],Es=`Allowed targets are: '${Ts.join("', '")}'`,Ps={speaker:Xn},Ms=async(e={})=>{const t=await(async e=>{var t;const r=(null!==(t=e.targets)&&void 0!==t?t:Ts).filter((e=>!!Ts.includes(e)||(Zt().warn(`We'll ignore the "${e}" target as it is not allowed. ${Es}.`),!1)));if(!r.length)throw new Error(`At least one "target" is required for createDeviceWatcher(). ${Es}.`);const i=await(async e=>{const t=e.targets;return(await Promise.all(t.map((e=>Is[e]())))).reduce(((e,r,i)=>{var o;const n=t[i];return e[!(n in Ps)||(null===(o=Ps[n])||void 0===o?void 0:o.call(Ps))?"supported":"unsupported"].push([n,!!r]),e}),{supported:[],unsupported:[]})})({targets:r});if(i.unsupported.length>0&&r.length===i.unsupported.length)throw new Error(`The platform doesn't support "${r.join(", ")}" as target/s, which means it's not possible to watch for changes on those devices.`);if(i.supported.every((([e,t])=>!t)))throw new Error("You must ask the user for permissions before being able to listen for device changes. Try calling getUserMedia() before calling `createDeviceWatcher()`.");let o=[];const n=i.supported.reduce(((e,[t,r])=>(r?e.push(t):o.push(t),e)),[]);if(n.length!==r.length){const e=i.unsupported.length>0?`The platform doesn't support "${i.unsupported.map((([e])=>e)).join(", ")}" as target/s, which means it's not possible to watch for changes on those devices. `:"",t=o.length>0?`The user hasn't granted permissions for the following targets: ${o.join(", ")}. `:"";Zt().warn(`${e}${t}We'll be watching for the following targets instead: "${n.join(", ")}"`)}return Zt().debug(`Watching these targets: "${n.join(", ")}"`),n})({targets:e.targets}),r=new St,i=await is(),o=null==t?void 0:t.reduce(((e,t)=>{const r=rs(t);return r&&e.push(r),e}),[]);let n=_s(i,{excludeDefault:!0,targets:o});return Gn().addEventListener("devicechange",(async()=>{const e=await is(),t=n,i=_s(e,{excludeDefault:!0,targets:o});n=i;const s=((e,t)=>{const r=Cs(e),i=Cs(e),o=[];Zt().debug("[_getDeviceListDiff] <- oldDevices",e),Zt().debug("[_getDeviceListDiff] -> newDevices",t);const n=t.filter((e=>{const t=e.deviceId,n=r.get(t);return n&&(i.delete(t),e.label!==n.label&&o.push(e)),void 0===n}));return{updated:o.map((e=>({type:"updated",payload:e}))),removed:Array.from(i,(([e,t])=>t)).map((e=>({type:"removed",payload:e}))),added:n.map((e=>({type:"added",payload:e})))}})(t,i),a=s.added.length>0,c=s.removed.length>0,d=s.updated.length>0;(a||c||d)&&r.emit("changed",{changes:s,devices:i}),a&&r.emit("added",{changes:s.added,devices:i}),c&&r.emit("removed",{changes:s.removed,devices:i}),d&&r.emit("updated",{changes:s.updated,devices:i})})),r},Rs=()=>Ms({targets:["speaker"]}),As=e=>"function"==typeof(null==e?void 0:e.getTracks),xs=async e=>(await ks()).find((t=>t.deviceId===e||"default"===t.deviceId&&""===e||""===t.deviceId&&"default"===e)),Os=e=>{Zt().info("RTCService.getUserMedia",e);const{audio:t,video:r}=e;if(t||r)return ds(e)},Ls=async e=>{var t,r;const{micLabel:i="",micId:o}=e;let n=null===(t=e.audio)||void 0===t||t;if(o&&n){const e=await Ss(o,i,"microphone").catch((e=>null));e&&("boolean"==typeof n&&(n={}),n.deviceId={exact:e})}const{camLabel:s="",camId:a}=e;let c=null===(r=e.video)||void 0===r||r;if(a&&c){const e=await Ss(a,s,"camera").catch((e=>null));e&&("boolean"==typeof c&&(c={}),c.deviceId={exact:e})}return{audio:n,video:c}},js=(e,t)=>{const{disableUdpIceServers:r=!1}=t,i=e=>{const t="transport=udp";return Array.isArray(e)?e.filter((e=>!e.includes(t))):e.includes(t)?"":e};return e.map((e=>Object.assign(Object.assign({},e),{urls:r?i(e.urls):e.urls})))};function Ds(e){"live"===e.readyState&&e.stop(),e._mockOscillator&&(e._mockOscillator.stop(),e._mockOscillator.disconnect(),delete e._mockOscillator),e._mockContext&&(e._mockContext.close(),delete e._mockContext)}function Ws(e){e&&("live"===e.readyState&&e.stop(),e._mockCanvas&&(e._mockCanvas.remove(),delete e._mockCanvas))}class Vs{constructor(e,t=3,r=!1){this.pool=new Map,this.turnRefreshInterval=24e4,this.logger=Zt();const i=e.iceCandidatePoolSize||10;this.config=Object.assign(Object.assign({},e),{iceCandidatePoolSize:i>20?20:i}),this.poolSize=t>4?4:t,this.forceRefresh=r}async initializePool(){this.logger.info(`Initializing RTCPeerConnection pool with size ${this.poolSize}`);const e=[];for(let t=0;t<this.poolSize;t++)e.push(this.createPooledConnection());(await Promise.all(e)).forEach((e=>{e&&this.pool.set(e.id,e)})),this.logger.info(`Pool initialized with ${this.pool.size} connections`),this.forceRefresh&&(this.logger.info("Manual force refresh mode enabled, TURN allocations will not be refreshed by this manager."),this.startMaintenanceWorker())}getConnection(){for(const[e,t]of this.pool.entries())if(this.logger.debug(`Checking pooled connection ${e}`),this.logger.debug(`Connection state: ${t.pc.connectionState}`),this.logger.debug(`Signaling state: ${t.pc.signalingState}`),this.logger.debug(`ICE connection state: ${t.pc.iceConnectionState}`),this.isConnectionValid(t))return this.logger.info(`Providing pooled connection ${e}`),this.pool.delete(e),this.cleanupMockTracks(t),this.replenishPool().catch((e=>{this.logger.error("Failed to replenish pool:",e)})),t.pc;return this.logger.warn("No valid pooled connections available"),null}cleanup(){this.logger.info("Cleaning up RTCPeerConnectionManager"),this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0);for(const[,e]of this.pool.entries())this.closeConnection(e);this.pool.clear()}async createPooledConnection(){var e;try{const t=qn(this.config),r=`conn_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;this.logger.debug(`Creating pooled connection ${r}`);const i=function(){const e=new(window.AudioContext||window.webkitAudioContext),t=e.createOscillator(),r=e.createMediaStreamDestination();t.frequency.value=0,t.connect(r),t.start();const i=r.stream.getAudioTracks()[0];return i._mockContext=e,i._mockOscillator=t,i}(),o=function(){const e=document.createElement("canvas");if(!e.captureStream)return console.warn("canvas.captureStream not supported, using audio-only mock"),null;e.width=320,e.height=240;const t=e.getContext("2d");t&&(t.fillStyle="#000000",t.fillRect(0,0,e.width,e.height));const r=e.captureStream(1).getVideoTracks()[0];return r._mockCanvas=e,r}(),n=[],s=t.addTrack(i);n.push(s);let a=null;o&&(a=t.addTrack(o),n.push(a));const c=await t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});await t.setLocalDescription(c),await this.waitForIceGathering(t);const d={id:r,pc:t,createdAt:Date.now(),lastRefreshed:Date.now(),iceGatheringComplete:!0,mockTracks:{audio:i,video:o||void 0},senders:n};return this.logger.debug(`Pooled connection ${r} created successfully`),this.logger.debug(`ICE candidates gathered for connection ${r}:`,null===(e=t.localDescription)||void 0===e?void 0:e.sdp),d}catch(e){return this.logger.error("Failed to create pooled connection:",e),null}}waitForIceGathering(e){return new Promise((t=>{if("complete"===e.iceGatheringState)return void t();const r=()=>{"complete"===e.iceGatheringState&&(i(),t())},i=()=>{e.removeEventListener("icegatheringstatechange",r),clearTimeout(o)};e.addEventListener("icegatheringstatechange",r);const o=setTimeout((()=>{this.logger.warn("ICE gathering timeout, proceeding anyway"),i(),t()}),1e4)}))}cleanupMockTracks(e){this.logger.debug(`Cleaning up mock tracks for connection ${e.id}`),e.mockTracks.audio&&Ds(e.mockTracks.audio),e.mockTracks.video&&Ws(e.mockTracks.video),e.senders.forEach((t=>{try{e.pc.removeTrack(t)}catch(e){this.logger.warn("Error removing track:",e)}})),this.cleanupEventListeners(e.pc),e.mockTracks={},e.senders=[]}cleanupEventListeners(e){["icecandidate","icegatheringstatechange","iceconnectionstatechange","connectionstatechange","signalingstatechange","negotiationneeded","track","datachannel","addstream","removestream"].forEach((t=>{e[`on${t}`]=null}))}isConnectionValid(e){if("closed"===e.pc.connectionState||"failed"===e.pc.connectionState)return this.logger.debug(`Pooled connection ${e.id} is not valid: ${e.pc.connectionState}`),!1;if("closed"===e.pc.signalingState)return this.logger.debug(`Pooled connection ${e.id} signalingState is not valid: ${e.pc.signalingState}`),!1;if("failed"===e.pc.iceConnectionState||"disconnected"===e.pc.iceConnectionState)return this.logger.debug(`Pooled connection ${e.id} iceConnectionState is not valid: ${e.pc.iceConnectionState}`),!1;const t=Date.now()-e.lastRefreshed;return!(this.forceRefresh&&t>this.turnRefreshInterval&&(this.logger.debug(`Pooled connection ${e.id} is not valid: TURN allocation age ${t}`),1))}async replenishPool(){const e=this.poolSize-this.pool.size;if(!(e<=0)){this.logger.debug(`Replenishing pool with ${e} connections`);for(let t=0;t<e;t++){const e=await this.createPooledConnection();e&&this.pool.set(e.id,e)}}}startMaintenanceWorker(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval((()=>{this.refreshTurnAllocations().catch((e=>{this.logger.error("TURN refresh error:",e)}))}),this.turnRefreshInterval)}async refreshTurnAllocations(){const e=Date.now();for(const[t,r]of this.pool.entries())if(e-r.lastRefreshed>this.turnRefreshInterval)try{await this.refreshConnection(r)}catch(e){this.logger.error(`Failed to refresh connection ${t}:`,e),this.pool.delete(t),this.closeConnection(r)}this.replenishPool().catch((e=>{this.logger.error("Failed to replenish after refresh:",e)}))}async refreshConnection(e){var t;this.logger.debug(`Refreshing TURN allocation for connection ${e.id}`),e.pc.restartIce();const r=await e.pc.createOffer({iceRestart:!0});await e.pc.setLocalDescription(r),await this.waitForIceGathering(e.pc),e.lastRefreshed=Date.now(),this.logger.debug(`TURN allocation refreshed for connection ${e.id}`),this.logger.debug(`New ICE candidates for connection ${e.id}:`,null===(t=e.pc.localDescription)||void 0===t?void 0:t.sdp)}closeConnection(e){try{e.mockTracks.audio&&Ds(e.mockTracks.audio),e.mockTracks.video&&Ws(e.mockTracks.video),"closed"!==e.pc.connectionState&&e.pc.close()}catch(t){this.logger.error(`Error closing connection ${e.id}:`,t)}}}const Ns=new class{constructor(){this.logger=Zt()}async initializePool(e,t={}){var r,i;if(this.manager)return void this.logger.warn("Connection pool already initialized");this.logger.info("Initializing connection pool");const o={iceServers:e,iceCandidatePoolSize:null!==(r=t.iceCandidatePoolSize)&&void 0!==r?r:10};this.manager=new Vs(o,null!==(i=t.poolSize)&&void 0!==i?i:2),await this.manager.initializePool()}getConnection(){return this.manager?this.manager.getConnection():(this.logger.warn("Connection pool not initialized"),null)}cleanup(){this.manager&&(this.logger.info("Cleaning up connection pool"),this.manager.cleanup(),this.manager=void 0)}get isInitialized(){return!!this.manager}};class $s{get logger(){return Zt()}constructor(e,t){this.call=e,this.type=t,this.uuid=b(),this._negotiating=!1,this._processingRemoteSDP=!1,this._restartingIce=!1,this._candidatesSnapshot=[],this._allCandidates=[],this._processingLocalSDP=!1,this._waitNegotiation=Promise.resolve(),this.logger.debug("New Peer with type:",this.type,"Options:",this.options),this._onIce=this._onIce.bind(this),this._onEndedTrackHandler=this._onEndedTrackHandler.bind(this),this.options.prevCallId&&(this.uuid=this.options.prevCallId),this.options.prevCallId=void 0,this.options.localStream&&Qn(this.options.localStream)&&(this._localStream=this.options.localStream),this.rtcConfigPolyfill=this.config}get options(){return this.call.options}get watchMediaPacketsTimeout(){var e;return null!==(e=this.options.watchMediaPacketsTimeout)&&void 0!==e?e:2e3}get isNegotiating(){return this._negotiating}get localStream(){return this._localStream}set localStream(e){this._localStream=e}get remoteStream(){return this._remoteStream}get isOffer(){return"offer"===this.type}get isAnswer(){return"answer"===this.type}get isSimulcast(){return!0===this.options.simulcast}get isSfu(){return!0===this.options.sfu}get localVideoTrack(){const e=this._getSenderByKind("video");return(null==e?void 0:e.track)||null}get localAudioTrack(){const e=this._getSenderByKind("audio");return(null==e?void 0:e.track)||null}get remoteVideoTrack(){const e=this._getReceiverByKind("video");return(null==e?void 0:e.track)||null}get remoteAudioTrack(){const e=this._getReceiverByKind("audio");return(null==e?void 0:e.track)||null}get hasAudioSender(){return!!this._getSenderByKind("audio")}get hasVideoSender(){return!!this._getSenderByKind("video")}get hasAudioReceiver(){return!!this._getReceiverByKind("audio")}get hasVideoReceiver(){return!!this._getReceiverByKind("video")}get config(){const{rtcPeerConfig:e={}}=this.options,t=Object.assign({bundlePolicy:"max-compat",iceServers:js(this.call.iceServers,{disableUdpIceServers:this.options.disableUdpIceServers}),sdpSemantics:"unified-plan"},e);return this.logger.debug("RTC config",t),t}get localSdp(){var e,t;return null===(t=null===(e=this.instance)||void 0===e?void 0:e.localDescription)||void 0===t?void 0:t.sdp}get remoteSdp(){var e,t;return null===(t=null===(e=this.instance)||void 0===e?void 0:e.remoteDescription)||void 0===t?void 0:t.sdp}get hasIceServers(){if(this.instance){const{iceServers:e=[]}=this.getConfiguration();return Boolean(null==e?void 0:e.length)}return!1}_negotiationCompleted(e){var t,r,i,o;e?(this._rejectStartMethod(e),null===(i=this._waitNegotiationCompleter)||void 0===i||i.call(this),null===(o=this._pendingNegotiationPromise)||void 0===o||o.reject(e)):(this._resolveStartMethod(),null===(t=this._waitNegotiationCompleter)||void 0===t||t.call(this),null===(r=this._pendingNegotiationPromise)||void 0===r||r.resolve())}stopTrackSender(e){var t;try{const r=this._getSenderByKind(e);if(!r)return this.logger.info(`There is not a '${e}' sender to stop.`);r.track&&(es(r.track),null===(t=this._localStream)||void 0===t||t.removeTrack(r.track))}catch(t){this.logger.error("RTCPeer stopTrackSender error",e,t)}}stopTrackReceiver(e){var t;try{const r=this._getReceiverByKind(e);if(!r)return this.logger.info(`There is not a '${e}' receiver to stop.`);r.track&&(es(r.track),null===(t=this._remoteStream)||void 0===t||t.removeTrack(r.track))}catch(t){this.logger.error("RTCPeer stopTrackReceiver error",e,t)}}async restoreTrackSender(e){var t;try{const r=this._getSenderByKind(e);if(!r)return this.logger.info(`There is not a '${e}' sender to restore.`);if(r.track&&"ended"!==r.track.readyState)return this.logger.info(`There is already an active ${e} track.`);const i=await Ls(this.options),o=await Os({[e]:i[e]});if(o&&Qn(o)){const i=o.getTracks().find((t=>t.kind===e));i&&(await r.replaceTrack(i),null===(t=this._localStream)||void 0===t||t.addTrack(i))}}catch(t){this.logger.error("RTCPeer restoreTrackSender error",e,t)}}getDeviceId(e){try{const t=this._getSenderByKind(e);if(!t||!t.track)return null;const{deviceId:r=null}=t.track.getSettings();return r}catch(t){return this.logger.error("RTCPeer getDeviceId error",e,t),null}}getTrackSettings(e){try{const t=this._getSenderByKind(e);return t&&t.track?t.track.getSettings():null}catch(t){return this.logger.error("RTCPeer getTrackSettings error",e,t),null}}getTrackConstraints(e){try{const t=this._getSenderByKind(e);return t&&t.track?t.track.getConstraints():null}catch(t){return this.logger.error("RTCPeer getTrackConstraints error",e,t),null}}getDeviceLabel(e){try{const t=this._getSenderByKind(e);return t&&t.track?t.track.label:null}catch(t){return this.logger.error("RTCPeer getDeviceLabel error",e,t),null}}restartIceWithRelayOnly(){try{if(this.isAnswer)return this.logger.warn("Skip restartIceWithRelayOnly since we need to generate answer");const e=this.getConfiguration();if("relay"===e.iceTransportPolicy)return this.logger.warn("RTCPeer already with iceTransportPolicy relay only");const t=Object.assign(Object.assign({},e),{iceTransportPolicy:"relay"});this.setConfiguration(t),this.restartIce()}catch(e){this.logger.error("restartIceWithRelayOnly",e),this._negotiationCompleted(e)}}restartIce(){if(this._negotiating||this._restartingIce)return this.logger.warn("Skip restartIce");this._restartingIce=!0,this.logger.debug("Restart ICE"),this.type="offer",this.instance.restartIce()}triggerResume(){this.logger.info("Probably half-open so force close from client"),this._resumeTimer?this.logger.info('[skipped] Already in "resume" state'):(this.call.emit("media.disconnected"),this.call.emit("media.reconnecting"),this.clearTimers(),this._resumeTimer=setTimeout((()=>{this.logger.warn("Disconnecting due to RECONNECTION_ATTEMPT_TIMEOUT"),this.call.emit("media.disconnected"),this.call.leaveReason="RECONNECTION_ATTEMPT_TIMEOUT",this.call.setState("hangup")}),12e3),this.call._closeWSConnection())}resetNeedResume(){this.clearResumeTimer(),this.options.watchMediaPackets&&this.startWatchMediaPackets()}stopWatchMediaPackets(){this._mediaWatcher&&this._mediaWatcher.stop()}startWatchMediaPackets(){var e;this.stopWatchMediaPackets(),this._mediaWatcher=(e=>{if(!e.hasAudioReceiver&&!e.hasVideoReceiver)return void Zt().warn(`Missing receivers to inspect media for RTCPeer "${e.uuid}"`);Zt().debug(`Start watching media for RTCPeer "${e.uuid}"`);let t,r=0,i=0,o=!0;const n=()=>{clearTimeout(t)},s=async()=>{var a,c;let d=0,l=0;try{const t=await e.instance.getStats(null),r=null===(a=e.remoteAudioTrack)||void 0===a?void 0:a.id,i=null===(c=e.remoteVideoTrack)||void 0===c?void 0:c.id;t.forEach((e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&e.trackIdentifier===r&&(Zt().trace(`audio inbound-rtp: packetsReceived: ${e.packetsReceived} (at ${e.lastPacketReceivedTimestamp})`),d=e.packetsReceived),"inbound-rtp"===e.type&&"video"===e.kind&&e.trackIdentifier===i&&(Zt().trace(`video inbound-rtp: packetsReceived: ${e.packetsReceived} (at ${e.lastPacketReceivedTimestamp})`),l=e.packetsReceived)}))}catch(e){Zt().warn("getStats error",e)}finally{d&&d<=r&&l&&l<=i?(Zt().warn(`audioPacketsReceived: ${d} - previousAudioValue: ${r}`),Zt().warn(`videoPacketsReceived: ${l} - previousVideoValue: ${i}`),e.triggerResume()):(r=null!=d?d:r,i=null!=l?l:i,n(),o&&"closed"!==e.instance.connectionState&&(t=setTimeout((()=>s()),e.watchMediaPacketsTimeout)))}};return{start:()=>{n(),s()},stop:()=>{o=!1,n()}}})(this),null===(e=this._mediaWatcher)||void 0===e||e.start()}async applyMediaConstraints(e,t){try{const r=this._getSenderByKind(e);if(!r||!r.track)return this.logger.info("No sender to apply constraints",e,t);if("live"===r.track.readyState){const i=Object.assign(Object.assign({},r.track.getConstraints()),t),o=this.getDeviceId(e);o&&!this.options.screenShare&&(i.deviceId={exact:o}),this.logger.info(`Apply ${e} constraints`,this.call.id,i),await r.track.applyConstraints(i)}}catch(r){this.logger.error("Error applying constraints",e,t)}}_getSenderByKind(e){var t;return(null===(t=this.instance)||void 0===t?void 0:t.getSenders)?this.instance.getSenders().find((({track:t})=>t&&t.kind===e)):(this.logger.warn("RTCPeerConnection.getSenders() not available."),null)}_getReceiverByKind(e){var t;return(null===(t=this.instance)||void 0===t?void 0:t.getReceivers)?this.instance.getReceivers().find((({track:t})=>t&&t.kind===e)):(this.logger.warn("RTCPeerConnection.getReceivers() not available."),null)}async startNegotiation(e=!1){var t,r;if(this._negotiating)return this.logger.warn("Skip twice onnegotiationneeded!");this._negotiating=!0;try{if((this.options.additionalDevice||this.options.screenShare)&&(null===(r=null===(t=this.instance)||void 0===t?void 0:t.getTransceivers)||void 0===r||r.call(t).forEach((e=>{e.direction="sendonly"}))),this.instance.removeEventListener("icecandidate",this._onIce),this.instance.addEventListener("icecandidate",this._onIce),this.isOffer){this.logger.debug("Trying to generate offer");const e={voiceActivityDetection:!1};this._supportsAddTransceiver()||(e.offerToReceiveAudio=this.options.negotiateAudio,e.offerToReceiveVideo=this.options.negotiateVideo);const t=await this.instance.createOffer(e);await this._setLocalDescription(t)}if(this.isAnswer){this.logger.debug("Trying to generate answer"),await this._setRemoteDescription({sdp:this.options.remoteSdp,type:"offer"});const e=await this.instance.createAnswer({voiceActivityDetection:!1});await this._setLocalDescription(e)}e&&"have-local-offer"===this.instance.signalingState&&this._sdpReady(),this.logger.info("iceGatheringState",this.instance.iceGatheringState),"gathering"===this.instance.iceGatheringState&&(this._iceTimeout=setTimeout((()=>{this._onIceTimeout()}),this.options.maxIceGatheringTimeout))}catch(e){this.logger.error(`Error creating ${this.type}:`,e),this._negotiationCompleted(e)}}onRemoteBye({code:e,message:t}){this._negotiationCompleted({code:e,message:t}),this.stop()}async onRemoteSdp(e){if(this._processingRemoteSDP||this.remoteSdp&&this.remoteSdp===e)this.logger.warn("Ignore same remote SDP",e);else try{const t=this.isOffer?"answer":"offer";if("answer"===t&&"have-local-offer"!==this.instance.signalingState)return void this.logger.warn("Ignoring offer SDP as signaling state is not have-local-offer");this._processingRemoteSDP=!0,await this._setRemoteDescription({sdp:e,type:t}),this._processingRemoteSDP=!1,this.isOffer&&this._negotiationCompleted(),this.resetNeedResume()}catch(e){this._processingRemoteSDP=!1,this.logger.error(`Error handling remote SDP on call ${this.call.id}:`,e),this.call.hangup(),this._negotiationCompleted(e)}}_setupRTCPeerConnection(){if(!this.instance){let e=null;try{e=Ns.getConnection()}catch(e){this.logger.debug("Could not access session connection pool",e)}e?(this.logger.info("Using pre-warmed connection from session pool with ICE candidates ready"),this.instance=e):(this.logger.debug("Creating new RTCPeerConnection (no pooled connection available)"),this.instance=qn(this.config)),this._attachListeners()}}async start(){return new Promise((async(e,t)=>{var r,i;this._resolveStartMethod=e,this._rejectStartMethod=t;try{this._localStream=await this._retrieveLocalStream()}catch(e){return this._negotiationCompleted(e),this.call.setState("hangup")}this._setupRTCPeerConnection();let o=!1;if(this._localStream&&Qn(this._localStream)){const e=this._localStream.getAudioTracks();this.logger.debug("Local audio tracks: ",e);const t=this._localStream.getVideoTracks();if(this.logger.debug("Local video tracks: ",t),o=Boolean(e.length||t.length),this.isOffer&&this._supportsAddTransceiver()){const r={direction:this.options.negotiateAudio?"sendrecv":"sendonly",streams:[this._localStream]};this.logger.debug("Applying audioTransceiverParams",r);const i=this.instance.getTransceivers().filter((e=>{var t,r;return"audio"===(null===(t=e.receiver.track)||void 0===t?void 0:t.kind)||!e.sender.track&&!e.receiver.track&&(null===(r=e.mid)||void 0===r?void 0:r.includes("audio"))}));e.forEach(((e,t)=>{var o;if(t<i.length){const n=i[t];this.logger.debug("Reusing existing audio transceiver",n.mid),n.sender.replaceTrack(e),n.direction=r.direction||"sendrecv",(null===(o=r.streams)||void 0===o?void 0:o[0])&&(n.sender.streams=r.streams)}else this.logger.debug("Creating new audio transceiver"),this.instance.addTransceiver(e,r)}));const o={direction:this.options.negotiateVideo?"sendrecv":"sendonly",streams:[this._localStream]};this.isSimulcast&&(o.sendEncodings=["0","1","2"].map((e=>({active:!0,rid:e,scaleResolutionDownBy:6*Number(e)||1})))),this.logger.debug("Applying videoTransceiverParams",o);const n=this.instance.getTransceivers().filter((e=>{var t,r;return"video"===(null===(t=e.receiver.track)||void 0===t?void 0:t.kind)||!e.sender.track&&!e.receiver.track&&(null===(r=e.mid)||void 0===r?void 0:r.includes("video"))}));if(t.forEach(((e,t)=>{var r;if(t<n.length){const i=n[t];if(this.logger.debug("Reusing existing video transceiver",i.mid),i.sender.replaceTrack(e),i.direction=o.direction||"sendrecv",(null===(r=o.streams)||void 0===r?void 0:r[0])&&(i.sender.streams=o.streams),o.sendEncodings){const e=i.sender.getParameters();e.encodings=o.sendEncodings,i.sender.setParameters(e)}}else this.logger.debug("Creating new video transceiver"),this.instance.addTransceiver(e,o)})),this.isSfu){const{msStreamsNumber:e=5}=this.options;this.logger.debug("Add ",e,"recvonly MS Streams"),o.direction="recvonly";for(let t=0;t<Number(e);t++)this.instance.addTransceiver("video",o)}}else if("function"==typeof this.instance.addTrack){const r=this._localStream;e.forEach((e=>this.instance.addTrack(e,r))),t.forEach((e=>this.instance.addTrack(e,r)))}else this.instance.addStream(this._localStream)}if(this.isOffer){if("have-local-offer"===this.instance.signalingState){this.logger.debug("Reusing pooled connection, managing transceivers");const e=(null===(r=this._localStream)||void 0===r?void 0:r.getAudioTracks())||[],t=(null===(i=this._localStream)||void 0===i?void 0:i.getVideoTracks())||[];this.instance.getTransceivers().forEach((r=>{var i,o,n,s;const a="audio"===(null===(i=r.receiver.track)||void 0===i?void 0:i.kind)||!r.sender.track&&!r.receiver.track&&(null===(o=r.mid)||void 0===o?void 0:o.includes("audio")),c="video"===(null===(n=r.receiver.track)||void 0===n?void 0:n.kind)||!r.sender.track&&!r.receiver.track&&(null===(s=r.mid)||void 0===s?void 0:s.includes("video"));a&&0===e.length&&(this.logger.debug("Setting unused audio transceiver to inactive",r.mid),r.direction="inactive"),c&&0===t.length&&(this.logger.debug("Setting unused video transceiver to inactive",r.mid),r.direction="inactive")}))}this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video"),"have-local-offer"===this.instance.signalingState&&(this.logger.debug("Reusing pooled connection with local offer"),this.startNegotiation(!0)),this._supportsAddTransceiver()||o||this.startNegotiation()}else this.startNegotiation()}))}detachAndStop(){var e;"function"==typeof(null===(e=this.instance)||void 0===e?void 0:e.getTransceivers)&&this.instance.getTransceivers().forEach((e=>{e.sender.track&&e.sender.track.stop(),e.receiver.track&&e.receiver.track.stop()})),this.stop()}stop(){var e,t,r;null===(e=this._localStream)||void 0===e||e.getTracks().forEach((e=>e.stop())),null===(t=this._remoteStream)||void 0===t||t.getTracks().forEach((e=>e.stop())),null===(r=this.instance)||void 0===r||r.close(),this.stopWatchMediaPackets()}_supportsAddTransceiver(){return"function"==typeof this.instance.addTransceiver}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)&&this._supportsAddTransceiver()){const t=this.instance.getTransceivers().find((t=>{var r,i;return(null===(r=t.receiver.track)||void 0===r?void 0:r.kind)===e||!t.sender.track&&!t.receiver.track&&(null===(i=t.mid)||void 0===i?void 0:i.includes(e))}));if(t)this.logger.debug("Found existing transceiver for",e,t.mid),"inactive"!==t.direction&&"sendonly"!==t.direction||(t.direction="recvonly");else{const t=this.instance.addTransceiver(e,{direction:"recvonly"});this.logger.debug("Add transceiver",e,t)}}}async _sdpReady(){if(this._processingLocalSDP)return void this.logger.debug("Already processing local SDP, skipping");if(this._processingLocalSDP=!0,clearTimeout(this._iceTimeout),!this.instance.localDescription)return void this.logger.error("Missing localDescription",this.instance);const{sdp:e}=this.instance.localDescription;if(!(e=>{try{const t=hs.getMediaSections(e);for(const e of t)if(!hs.splitLines(e).some((e=>0===e.indexOf("a=candidate"))))return!1;return!0}catch(e){return Zt().error("Error checking SDP",e),!1}})(e))return this.logger.info("No candidate - retry \n"),this._processingLocalSDP=!1,void this.startNegotiation(!0);if(!this._sdpIsValid())return this.logger.info("SDP ready but not valid"),this._processingLocalSDP=!1,void this._onIceTimeout();try{if(!await this._isAllowedToSendLocalSDP())return this.logger.info("Skipping onLocalSDPReady due to early invite"),void(this._processingLocalSDP=!1);this._waitNegotiation=new Promise((e=>{this._waitNegotiationCompleter=e})),await this.call.onLocalSDPReady(this),this._processingLocalSDP=!1,this.isAnswer&&this._negotiationCompleted()}catch(e){this._negotiationCompleted(e),this._processingLocalSDP=!1}}async _isAllowedToSendLocalSDP(){return await this._waitNegotiation,"offer"===this.type&&["have-local-offer","have-local-pranswer"].includes(this.instance.signalingState)||"answer"===this.type&&"stable"===this.instance.signalingState}_sdpIsValid(){return this.localSdp&&this.hasIceServers?fs(this.localSdp):Boolean(this.localSdp)}_forceNegotiation(){this.logger.info("Force negotiation again"),this._negotiating=!1,this.startNegotiation()}_onIceTimeout(){if(this._sdpIsValid())return void this._sdpReady();this.logger.info("ICE gathering timeout");const e=this.getConfiguration();if("relay"===e.iceTransportPolicy)return this.logger.info('RTCPeer already with "iceTransportPolicy: relay"'),this._negotiationCompleted({code:"ICE_GATHERING_FAILED",message:"Ice gathering timeout"}),void this.call.setState("destroy");this.setConfiguration(Object.assign(Object.assign({},e),{iceTransportPolicy:"relay"})),this._forceNegotiation()}_onIce(e){var t,r;if(this._iceTimeout&&clearTimeout(this._iceTimeout),!e.candidate)return this.instance.removeEventListener("icecandidate",this._onIce),void(this._candidatesSnapshot.length>0&&(this.logger.debug("No more candidates, calling _sdpReady"),this._sdpReady()));this._allCandidates.push(e.candidate),this.logger.debug("RTCPeer Candidate:",e.candidate),"host"===e.candidate.type?this._iceTimeout=setTimeout((()=>{this.instance.removeEventListener("icecandidate",this._onIce),this._onIceTimeout()}),this.options.maxIceGatheringTimeout):(null===(t=this.instance.localDescription)||void 0===t?void 0:t.sdp)&&(fs(this.instance.localDescription.sdp)?0===this._candidatesSnapshot.length&&"offer"===this.type&&(this._candidatesSnapshot=[...this._allCandidates],this.logger.info("SDP has candidates for all media sections, calling _sdpReady for early invite"),setTimeout((()=>this._sdpReady()),0)):(this.logger.info("SDP does not have candidates for all media sections, waiting for more candidates"),this.logger.debug(null===(r=this.instance.localDescription)||void 0===r?void 0:r.sdp)))}_retryWithMoreCandidates(){this._hasMoreCandidates()&&"connected"!==this.instance.connectionState&&(this.logger.info("More candidates found after ICE gathering complete, triggering renegotiation"),this._negotiating=!1,this._candidatesSnapshot=[],this._allCandidates=[],this.type="offer","stable"===this.instance.signalingState?this.startNegotiation(!0):(this.logger.warn("Signaling state is not stable, cannot start negotiation immediately"),this.restartIce()))}_hasMoreCandidates(){return this._allCandidates.length>this._candidatesSnapshot.length}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:r,googleMinBitrate:i,googleStartBitrate:o}=this.options;return e.sdp&&t&&(e.sdp=gs(e.sdp)),e.sdp&&r&&i&&o&&(e.sdp=((e,t,r,i)=>{const o=e.split("\r\n");return o.forEach(((e,n)=>{/^a=fmtp:\d*/.test(e)?o[n]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${r};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(o[n]+=`\r\nb=AS:${t}`)})),o.join("\r\n")})(e.sdp,r,i,o)),this.instance.setLocalDescription(e)}_setRemoteDescription(e){e.sdp&&this.options.useStereo&&(e.sdp=gs(e.sdp)),e.sdp&&this.instance.localDescription&&(e.sdp=(e=>{const t="\r\n",r=this.instance.localDescription.sdp.split(t),i=r.findIndex(ms),o=r.findIndex(ps);if(-1==o||-1==i||i<o)return e;const n=e.split(t),s=n.findIndex(ms),a=n.findIndex(ps),c=n.slice(s,a),d=n.slice(a,n.length-1);return[...n.slice(0,s),...d,...c,""].join(t)})(e.sdp));const t=e;return this.logger.debug("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}async _retrieveLocalStream(){if(Qn(this.options.localStream))return this.options.localStream;const e=await Ls(this.options);return Os(e)}_attachListeners(){this.instance.addEventListener("signalingstatechange",(()=>{switch(this.logger.debug("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1,this._restartingIce=!1,this.resetNeedResume(),"connected"===this.instance.connectionState&&this.emitMediaConnected();break;case"have-local-offer":"complete"===this.instance.iceGatheringState&&(this.instance.removeEventListener("icecandidate",this._onIce),this._sdpReady());break;case"closed":delete this.instance;break;default:this._negotiating=!0}})),this.instance.addEventListener("connectionstatechange",(()=>{switch(this.logger.debug("connectionState:",this.instance.connectionState),this.instance.connectionState){case"connecting":this._connectionStateTimer=setTimeout((()=>{this.logger.warn("connectionState timed out"),this._hasMoreCandidates()?this._retryWithMoreCandidates():this.restartIceWithRelayOnly()}),this.options.maxConnectionStateTimeout);break;case"connected":this.clearConnectionStateTimer(),this.emitMediaConnected();break;case"disconnected":this.logger.debug("[test] Prevent reattach!");break;case"failed":this.triggerResume()}})),this.instance.addEventListener("negotiationneeded",(()=>{this.logger.debug("Negotiation needed event"),this.startNegotiation()})),this.instance.addEventListener("iceconnectionstatechange",(()=>{this.logger.debug("iceConnectionState:",this.instance.iceConnectionState)})),this.instance.addEventListener("icegatheringstatechange",(()=>{this.logger.debug("iceGatheringState:",this.instance.iceGatheringState),"complete"===this.instance.iceGatheringState&&(this.logger.debug("ICE gathering complete"),this._sdpReady())})),this.instance.addEventListener("track",(e=>{this.logger.debug("Track event:",e,e.track.kind),this.call.emit("track",e),this._remoteStream=e.streams[0]})),this.instance.addEventListener("addstream",(e=>{e.stream&&(this._remoteStream=e.stream)})),this._attachAudioTrackListener(),this._attachVideoTrackListener()}clearTimers(){this.clearResumeTimer(),this.clearWatchMediaPacketsTimer(),this.clearConnectionStateTimer()}clearConnectionStateTimer(){clearTimeout(this._connectionStateTimer)}clearWatchMediaPacketsTimer(){clearTimeout(this._watchMediaPacketsTimer)}clearResumeTimer(){clearTimeout(this._resumeTimer),this._resumeTimer=void 0}emitMediaConnected(){this.logger.debug("Emitting media.connected event"),this.call.emit("media.connected")}_onEndedTrackHandler(e){const t=e.target;this.call.emit(("audio"===t.kind?"microphone":"camera")+".disconnected",{deviceId:t.id,label:t.label})}_attachAudioTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getAudioTracks().forEach((e=>{e.addEventListener("ended",this._onEndedTrackHandler)}))}_attachVideoTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getVideoTracks().forEach((e=>{e.addEventListener("ended",this._onEndedTrackHandler)}))}_detachAudioTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getAudioTracks().forEach((e=>{e.removeEventListener("ended",this._onEndedTrackHandler)}))}_detachVideoTrackListener(){var e;null===(e=this.localStream)||void 0===e||e.getVideoTracks().forEach((e=>{e.removeEventListener("ended",this._onEndedTrackHandler)}))}setConfiguration(e){var t;this.rtcConfigPolyfill=e,this.instance&&"function"==typeof(null===(t=this.instance)||void 0===t?void 0:t.setConfiguration)&&this.instance.setConfiguration(e)}getConfiguration(){var e;return this.instance&&"function"==typeof(null===(e=this.instance)||void 0===e?void 0:e.getConfiguration)?this.instance.getConfiguration():this.rtcConfigPolyfill||this.config}}"function"==typeof SuppressedError&&SuppressedError;const Us=e=>ir(e.type),zs=function*(e){Zt().debug("vertoEventWorker started");const{channels:t,instance:r,initialState:i}=e,{swEventChannel:o}=t,{rtcPeerId:n}=i;if(!n)throw new Error("Missing rtcPeerId for roomSubscribedWorker");const s=_i.createCatchableSaga((function*(e){var t,i;const{id:o,method:s,params:a={}}=e.payload,{callID:c,nodeId:d}=a,l=r.getRTCPeerById(c);if(!l)return void Zt().warn(`RTCPeer '${c}' not found for method: '${s}'`,a);const u=r.peer;switch(s){case"verto.media":case"verto.answer":l.uuid===(null==u?void 0:u.uuid)&&r.setState("verto.media"===s?"early":"active"),(null==a?void 0:a.sdp)&&l.onRemoteSdp(a.sdp),yield Oe(vi.upsert({id:null===(t=e.payload.params)||void 0===t?void 0:t.callID,nodeId:null===(i=e.payload.params)||void 0===i?void 0:i.nodeId})),yield je([r,r.execute],{method:r._getRPCMethod(),params:{message:$r(o,s),node_id:d}});break;case"verto.bye":yield je([r,r.onVertoBye],{rtcPeerId:c,byeCause:null==a?void 0:a.cause,byeCauseCode:null==a?void 0:a.causeCode,redirectDestination:null==a?void 0:a.redirectDestination}),yield je([r,r.execute],{method:r._getRPCMethod(),params:{message:$r(o,s),node_id:d}});break;case"verto.ping":{const{nodeId:e}=a,t=function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(r[i[o]]=e[i[o]])}return r}(a,["nodeId"]);yield je([r,r.execute],{method:r._getRPCMethod(),params:{message:Nr(t),node_id:e}});break}case"verto.mediaParams":{if(!c||!a.mediaParams){Zt().warn("Invalid mediaParams event",a);break}const{audio:e,video:t}=a.mediaParams;l&&t&&l.applyMediaConstraints("video",t),l&&e&&l.applyMediaConstraints("audio",e);break}case"verto.display":r.setActiveRTCPeer(n),r.emit("verto.display",e.payload.params);break;default:return Zt().warn(`Unknown Verto method: ${s}`,a)}}),(e=>{Zt().error("Verto Error",e)}));try{for(;;){const e=yield xe(o,(e=>{var t;return Zt().debug(`vertoEventWorker for: ${n} checking action...`),!!Us(e)&&(null===(t=e.payload.params)||void 0===t?void 0:t.callID)===n}));yield De(s,e)}}finally{Zt().debug(`vertoEventWorker for ${n} [cancelled]`)}},Bs=function*(e){var t;Zt().debug("roomSubscribedWorker started");const{channels:r,instance:i,initialState:o}=e,{swEventChannel:n}=r,{rtcPeerId:s}=o;if(!s)throw new Error("Missing rtcPeerId for roomSubscribedWorker");try{const e=yield xe(n,(e=>("video.room.subscribed"===e.type||"call.joined"===e.type)&&e.payload.call_id===s)),r=JSON.parse(JSON.stringify(e.payload));i.setActiveRTCPeer(s);const o=e.payload.room_session.id||e.payload.room_session.room_session_id;yield Oe(vi.upsert({id:e.payload.call_id,roomId:null===(t=e.payload.room_session)||void 0===t?void 0:t.room_id,roomSessionId:o,memberId:e.payload.member_id,previewUrl:e.payload.room_session.preview_url})),i.emit("room.subscribed",e.payload),Zt().debug("room.subscribed event emitted",s),i.emit("room.joined",Fs.call(i,r)),Zt().debug("room.joined event emitted",s),Zt().debug("roomSubscribedWorker ended",s)}finally{Zt().debug(`roomSubscribedWorker for ${s} [cancelled]`)}};function Fs(e){return["room_session","room"].forEach((t=>{e[t]&&e[t].recordings&&(e[t].recordings=(e[t].recordings||[]).map((t=>{let r=this.instanceMap.get(t.id);return r?r.setPayload({room_id:e.room.room_id,room_session_id:e.room_session.id,recording:t}):r=io.createRoomSessionRecordingObject({store:this.store,payload:{room_id:e.room.room_id,room_session_id:e.room_session.id,recording:t}}),this.instanceMap.set(t.id,r),r}))),e[t]&&e[t].playbacks&&(e[t].playbacks=(e[t].playbacks||[]).map((t=>{let r=this.instanceMap.get(t.id);return r?r.setPayload({room_id:e.room.room_id,room_session_id:e.room_session.id,playback:t}):r=io.createRoomSessionPlaybackObject({store:this.store,payload:{room_id:e.room.room_id,room_session_id:e.room_session.id,playback:t}}),this.instanceMap.set(t.id,r),r}))),e[t]&&e[t].streams&&(e[t].streams=(e[t].streams||[]).map((t=>{let r=this.instanceMap.get(t.id);return r?r.setPayload({room_id:e.room.room_id,room_session_id:e.room_session.id,stream:t}):r=io.createRoomSessionStreamObject({store:this.store,payload:{room_id:e.room.room_id,room_session_id:e.room_session.id,stream:t}}),this.instanceMap.set(t.id,r),r})))})),e}const Hs=function*(e){Zt().debug("promoteDemoteWorker started");const{channels:t,instance:r,initialState:i}=e,{swEventChannel:o}=t,{rtcPeerId:n}=i;if(!n)throw new Error("Missing rtcPeerId for promoteDemoteWorker");try{const e=yield xe(o,(e=>("video.member.promoted"===e.type||"video.member.demoted"===e.type)&&e.payload.member_id===r.memberId));Zt().debug("promoteDemoteWorker:",e.type,e.payload),yield Oe(li.updateAuthorization(e.payload.authorization));const t=yield We(Hn.getAuthorization);if(!t)throw new Error(`Invalid authorization for '${e.type}'`);const{audio_allowed:i,video_allowed:s}=t;switch(e.type){case"video.member.promoted":r.updateMediaOptions({audio:"both"===i,video:"both"===s,negotiateAudio:"none"!==i,negotiateVideo:"none"!==s});break;case"video.member.demoted":r.updateMediaOptions({audio:!1,video:!1,negotiateAudio:"none"!==i,negotiateVideo:"none"!==s})}r._triggerNewRTCPeer(),Zt().debug("promoteDemoteWorker ended",n)}finally{Zt().debug(`promoteDemoteWorker for ${n} [cancelled]`)}},qs=function*(e){Zt().debug("sessionAuthWorker started");const{instance:t}=e;switch((yield xe([Ur.authSuccessAction.type,Ur.authErrorAction.type])).type){case Ur.authSuccessAction.type:yield je([t,t.resume]);break;case Ur.authErrorAction.type:yield je([t,t.setState],"hangup")}Zt().debug("sessionAuthWorker ended")},Ks=function*(e){var t;const r=Zt();r.debug("sessionConnectionPoolWorker started");const i=e.initialState||{};try{r.debug("Waiting for session/connected action");const e=(null===(t=(yield xe("session/connected")).payload)||void 0===t?void 0:t.ice_servers)||[];if(!e||0===e.length)return void r.warn("No ICE servers available, cannot initialize connection pool");r.info("Session authorized, initializing connection pool"),yield je([Ns,Ns.initializePool],e,i),r.info("Connection pool initialized successfully"),yield xe(Ur.sessionDisconnectedAction.type),r.info("Session disconnected, cleaning up connection pool"),yield je([Ns,Ns.cleanup])}catch(e){r.error("Error in sessionConnectionPoolWorker",e)}finally{r.debug("sessionConnectionPoolWorker ended")}},Gs={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},Js=Object.assign(Object.assign({},Gs),{noiseSuppression:!1,autoGainControl:!1,googAutoGainControl:!1}),Qs={width:{ideal:1280,min:320},height:{ideal:720,min:180},aspectRatio:{ideal:16/9}},Xs={destinationNumber:"room",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:Gs,video:Qs,useStereo:!1,attach:!1,screenShare:!1,additionalDevice:!1,userVariables:{},requestTimeout:1e4,autoApplyMediaParams:!0,iceGatheringTimeout:2e3,maxIceGatheringTimeout:5e3,maxConnectionStateTimeout:3e3,watchMediaPackets:!0,watchMediaPacketsTimeout:2e3};class Ys extends qi{constructor(e){super(e),this.leaveReason=void 0,this.gotEarly=!1,this.state="new",this.prevState="new",this.rtcPeerMap=new Map,this.resuming=!1,this._myWorkers=[],this.onVertoBye=e=>{this.logger.debug("onVertoBye",e);const{rtcPeerId:t,byeCause:r="NORMAL_CLEARING",byeCauseCode:i="16",redirectDestination:o}=e;this.cause=String(r),this.causeCode=String(i);const n=this.getRTCPeerById(t);return n?o&&n.localSdp?(this.logger.debug("Redirect Destination to:",o,"for RTCPeer:",n.uuid),void this.executeInvite(n.localSdp,n.uuid,o)):(n.onRemoteBye({code:this.causeCode,message:this.cause}),void(this.activeRTCPeerId===(null==n?void 0:n.uuid)&&(this.logger.debug("onVertoBye go hangup"),this.setState("hangup")))):this.logger.warn("Invalid RTCPeer to hangup",e)},this.options=Object.assign(Object.assign({},Xs),e),this._checkDefaultMediaConstraints(),this.setState("new"),this.logger.trace("New Call with Options:",this.options),this._initPeer()}get id(){return this.__uuid}get active(){return"active"===this.state}get requesting(){return"requesting"===this.state}get trying(){return"trying"===this.state}get memberId(){return this.component.memberId}get previewUrl(){return this.component.previewUrl}get roomId(){return this.component.roomId}get roomSessionId(){return this.component.roomSessionId}get nodeId(){return this.component.nodeId||this.options.nodeId}get callId(){var e;return(null===(e=this.peer)||void 0===e?void 0:e.uuid)||""}get localStream(){var e;return null===(e=this.peer)||void 0===e?void 0:e.localStream}set localStream(e){this.peer&&(this.peer.localStream=e)}get remoteStream(){var e;return null===(e=this.peer)||void 0===e?void 0:e.remoteStream}get iceServers(){var e,t;return null!==(t=null===(e=this.options)||void 0===e?void 0:e.iceServers)&&void 0!==t?t:this.select(Hn.getIceServers)}get component(){return this.select((e=>Xi.getComponent(e,this.callId)))||{}}get cameraId(){return this.peer?this.peer.getDeviceId("video"):null}get cameraLabel(){return this.peer?this.peer.getDeviceLabel("video"):null}get cameraConstraints(){return this.peer?this.peer.getTrackConstraints("video"):null}get microphoneId(){return this.peer?this.peer.getDeviceId("audio"):null}get microphoneLabel(){return this.peer?this.peer.getDeviceLabel("audio"):null}get microphoneConstraints(){return this.peer?this.peer.getTrackConstraints("audio"):null}get withAudio(){var e;return Boolean(null===(e=this.peer)||void 0===e?void 0:e.hasAudioReceiver)}get withVideo(){var e;return Boolean(null===(e=this.peer)||void 0===e?void 0:e.hasVideoReceiver)}get localAudioTrack(){return this.peer?this.peer.localAudioTrack:null}get localVideoTrack(){return this.peer?this.peer.localVideoTrack:null}get peer(){return this.getRTCPeerById(this.activeRTCPeerId)}set peer(e){if(e){if(this.logger.debug("Set RTCPeer",e.uuid,e),this.rtcPeerMap.set(e.uuid,e),this.peer&&this.peer.instance&&this.callId!==e.uuid){const e=this.peer.uuid;this.logger.debug(">>> Stop old RTCPeer",e),this.hangup(e).catch(console.error),this.peer.detachAndStop()}this.logger.debug(">>> Replace RTCPeer with",e.uuid),this.activeRTCPeerId=e.uuid}else this.logger.warn("Invalid RTCPeer",e)}emit(e,...t){return super.emit(e,...t)}dialogParams(e){const{destinationNumber:t,attach:r,callerName:i,callerNumber:o,remoteCallerName:n,remoteCallerNumber:s,userVariables:a,screenShare:c,additionalDevice:d,fromFabricAddressId:l,pingSupported:u=!0}=this.options;return{dialogParams:{id:e,destinationNumber:t,attach:r,reattaching:r,callerName:i,callerNumber:o,remoteCallerName:n,remoteCallerNumber:s,userVariables:a,screenShare:c,additionalDevice:d,fromFabricAddressId:l,pingSupported:u,version:1e3}}}getRTCPeerById(e){return this.rtcPeerMap.get(e)}appendRTCPeer(e){return this.rtcPeerMap.set(e.uuid,e)}removeRTCPeer(e){return this.rtcPeerMap.delete(e)}setActiveRTCPeer(e){this.peer=this.getRTCPeerById(e)}setLocalStream(e){return new Promise((async(t,r)=>{try{if(!this.peer||!this.localStream)return r(new Error("Invalid RTCPeerConnection."));if(!Qn(e))return r(new Error("Invalid stream provided."));const i=this.localStream.getAudioTracks(),o=e.getAudioTracks();o.length<=0?this.logger.info("No audio track found in the stream provided. Audio will be unaffected."):(i.forEach((e=>{var t;es(e),null===(t=this.localStream)||void 0===t||t.removeTrack(e)})),o.forEach((e=>{var t;null===(t=this.localStream)||void 0===t||t.addTrack(e)})));const n=this.localStream.getVideoTracks(),s=e.getVideoTracks();s.length<=0?this.logger.info("No video track found in the stream provided. Video will be unaffected."):(n.forEach((e=>{var t;es(e),null===(t=this.localStream)||void 0===t||t.removeTrack(e)})),s.forEach((e=>{var t;null===(t=this.localStream)||void 0===t||t.addTrack(e)}))),await this.updateStream(this.localStream),this.logger.debug("setLocalStream done"),t(this.localStream)}catch(e){this.logger.error("setLocalStream",e),r(e)}}))}vertoExecute(e){return this.execute({method:this._getRPCMethod(),params:e})}_getRPCMethod(){const e=this.select(Hn.getAuthorization);return e&&kr(e)?"webrtc.verto":"video.message"}async _triggerNewRTCPeer(){this.logger.debug("_triggerNewRTCPeer Start");try{this.logger.debug("Build a new RTCPeer");const e=this._buildPeer("offer");this.logger.debug("Trigger start for the new RTCPeer!"),await e.start()}catch(e){this.logger.error("Error building new RTCPeer to promote/demote",e)}}updateCamera(e){return this.applyConstraintsAndRefreshStream({video:Object.assign({aspectRatio:16/9},e)})}updateMicrophone(e){return this.applyConstraintsAndRefreshStream({audio:e})}_getTransceiverDirection(e){let t="inactive";return"audio"===e&&(t=this.options.audio&&this.options.negotiateAudio?"sendrecv":this.options.audio&&!this.options.negotiateAudio?"sendonly":!this.options.audio&&this.options.negotiateAudio?"recvonly":"inactive"),"video"===e&&(t=this.options.video&&this.options.negotiateVideo?"sendrecv":this.options.video&&!this.options.negotiateVideo?"sendonly":!this.options.video&&this.options.negotiateVideo?"recvonly":"inactive"),t}manageSendersWithConstraints(e){return!1===e.audio&&(this.logger.info("Switching off the microphone"),this.stopOutboundAudio()),!1===e.video&&(this.logger.info("Switching off the camera"),this.stopOutboundVideo()),e.audio||e.video}updateConstraints(e,{attempt:t=0}={}){return t>1?Promise.reject(new Error("Failed to update constraints")):new Promise((async(r,i)=>{var o;try{if(!this.peer)return i(new Error("Invalid RTCPeerConnection."));if(!Object.keys(e).length)return i(new Error("Invalid audio/video constraints."));if(this.logger.debug("updateConstraints trying constraints",this.__uuid,e),!this.manageSendersWithConstraints(e))return this.logger.debug("Either `video` and `audio` (or both) constraints were set to `false` so their corresponding senders (if any) were stopped"),r();let n,s={};null===(o=this.localStream)||void 0===o||o.getTracks().forEach((t=>{var r;s[t.kind]=t.getConstraints(),void 0!==e[t.kind]&&(this.logger.debug("updateConstraints stop old tracks first?"),this.logger.debug("Track readyState:",t.kind,t.readyState),es(t),t.stop(),null===(r=this.localStream)||void 0===r||r.removeTrack(t))}));try{this.logger.info("updateConstraints with",e),n=await ds(e)}catch(e){return this.logger.error("Error updating device constraints:",e.name,e.message,e),this.logger.info("Restoring previous constraints",s),await this.updateConstraints(s,{attempt:t+1}),i(e)}this.logger.debug("updateConstraints done"),r(n)}catch(e){this.logger.error("updateConstraints",e),i(e)}}))}async updateStream(e){try{if(!this.peer)throw new Error("Invalid RTCPeerConnection.");const t=this.localVideoTrack,r=this.localAudioTrack;this.logger.debug("updateStream got stream",e),this.localStream||(this.localStream=new MediaStream);const i=e.getTracks();this.logger.debug(`updateStream got ${i.length} tracks`);for(const e of i)this.logger.debug("updateStream apply track: ",e),await this.handleTransceiverForTrack(e),this.emitDeviceUpdatedEvents({newTrack:e,prevAudioTrack:r,prevVideoTrack:t});this.logger.debug("updateStream done")}catch(e){throw this.logger.error("updateStream error",e),e}}async handleTransceiverForTrack(e){var t,r;if(!this.peer)return this.logger.error("Invalid RTCPeerConnection");const i=this.peer.instance.getTransceivers().find((({mid:t,sender:r,receiver:i})=>r.track&&r.track.kind===e.kind?(this.logger.debug("Found transceiver by sender"),!0):i.track&&i.track.kind===e.kind?(this.logger.debug("Found transceiver by receiver"),!0):null===t&&(this.logger.debug("Found disassociated transceiver"),!0)));if(i){this.logger.debug("handleTransceiverForTrack got transceiver",i.currentDirection,i.mid),(null===(t=i.sender.track)||void 0===t?void 0:t.id)!==e.id&&(await i.sender.replaceTrack(e),this.logger.debug(`handleTransceiverForTrack replaceTrack for ${e.kind}`));const r=this._getTransceiverDirection(e.kind);i.direction!==r&&(i.direction=r,this.logger.debug(`handleTransceiverForTrack set direction to ${r}`)),this.replaceOldTrack(e)}else{this.logger.debug("handleTransceiverForTrack no transceiver found; addTransceiver and start dancing!");const t=this._getTransceiverDirection(e.kind);this.peer.type="offer",null===(r=this.localStream)||void 0===r||r.addTrack(e),this.peer.instance.addTransceiver(e,{direction:t,streams:[this.localStream]})}}replaceOldTrack(e){if(!this.peer||!this.localStream)return this.logger.error("Invalid RTCPeerConnection");this.peer._detachAudioTrackListener(),this.peer._detachVideoTrackListener(),this.localStream.getTracks().forEach((t=>{var r;t.kind===e.kind&&t.id!==e.id&&(this.logger.debug("replaceOldTrack stop old track and apply new one"),es(t),null===(r=this.localStream)||void 0===r||r.removeTrack(t))})),this.localStream.addTrack(e),"audio"===e.kind&&(this.options.micId=e.getSettings().deviceId),"video"===e.kind&&(this.options.camId=e.getSettings().deviceId),this.peer._attachAudioTrackListener(),this.peer._attachVideoTrackListener()}emitDeviceUpdatedEvents({newTrack:e,prevAudioTrack:t,prevVideoTrack:r}){"audio"===e.kind?this.emit("microphone.updated",{previous:{deviceId:null==t?void 0:t.id,label:null==t?void 0:t.label},current:{deviceId:e.id,label:e.label}}):"video"===e.kind&&this.emit("camera.updated",{previous:{deviceId:null==r?void 0:r.id,label:null==r?void 0:r.label},current:{deviceId:e.id,label:e.label}})}async applyConstraintsAndRefreshStream(e){const t=await this.updateConstraints(e);t&&await this.updateStream(t)}runRTCPeerWorkers(e){const t=this.runWorker("vertoEventWorker",{worker:zs,initialState:{rtcPeerId:e}});if(this._myWorkers.push(t),!this.options.additionalDevice&&!this.options.screenShare){const t=this.runWorker("roomSubscribedWorker",{worker:Bs,initialState:{rtcPeerId:e}});this._myWorkers.push(t);const r=this.runWorker("promoteDemoteWorker",{worker:Hs,initialState:{rtcPeerId:e}});this._myWorkers.push(r)}}removeRTCWorkers(){for(const e of this._myWorkers)this.cancelWorker(e);this._myWorkers=[]}_destroyPeer(){this.peer&&(this.peer.detachAndStop(),this.removeRTCWorkers(),this.removeRTCPeer(this.peer.uuid),this.peer=void 0)}invite(){return pr({asyncCallable:async()=>new Promise((async(e,t)=>{await this._waitUntilSessionAuthorized(),this.direction="outbound",this.peer=this._buildPeer("offer");try{await this.peer.start(),e(this)}catch(e){this.logger.error("Invite error",e),this._destroyPeer(),t(e)}})),maxRetries:5,delayFn:mr({initialDelay:0}),expectedErrorHandler:e=>!this.requesting||![Bt,Ft].includes(e)||(this.logger.debug("Retrying verto.invite with new RTCPeer"),!1)})}answer(){return new Promise((async(e,t)=>{this.direction="inbound",this.peer||(this.peer=this._buildPeer("answer"));try{await this.peer.start(),e(this)}catch(e){this.logger.error("Answer error",e),t(e)}}))}async onLocalSDPReady(e){if(!e.instance.localDescription)throw this.logger.error("Missing localDescription",e),new Error("Invalid RTCPeerConnection localDescription");const{type:t,sdp:r}=e.instance.localDescription,i=this._mungeSDP(r);switch(this.logger.debug("LOCAL SDP \n",`Type: ${t}`,"\n\n",i),t){case"offer":return this._watchSessionAuth(),!this.resuming&&e.instance.remoteDescription?this.executeUpdateMedia(i,e.uuid):this.executeInvite(i,e.uuid);case"answer":return this.executeAnswer(i,e.uuid);default:return this.logger.error(`Unknown SDP type: '${t}' on call ${this.id}`)}}_closeWSConnection(){this._watchSessionAuth(),this.store.dispatch(Ur.sessionForceCloseAction())}_watchSessionAuth(){this.sessionAuthTask&&this.sessionAuthTask.cancel(),this.sessionAuthTask=this.runWorker("sessionAuthWorker",{worker:qs})}async resume(){var e;if(this.logger.warn(`[resume] Call ${this.id}`),null===(e=this.peer)||void 0===e?void 0:e.instance){const{connectionState:e}=this.peer.instance;this.logger.debug(`[resume] connectionState for ${this.id} is '${e}'`),"closed"!==e&&(this.resuming=!0,this.peer.restartIce())}}async executeInvite(e,t,r){const i=this.getRTCPeerById(t);if(!i||i.instance.remoteDescription&&!this.resuming)throw new Error(`RTCPeer '${t}' already has a remoteDescription. Invalid invite.`);"new"===this.state&&this.setState("requesting");try{const i=this.options.screenShare?{layout:this.options.layout,positions:this.options.positions}:{},o=Or(Object.assign(Object.assign(Object.assign({},this.dialogParams(t)),i),{sdp:e}));let n=[];n=this.options.screenShare?["video.room.screenshare"]:this.options.additionalDevice?["video.room.additionaldevice"]:this.getSubscriptions(),this.logger.debug("Subscribing to",n);const s=await this.vertoExecute({message:o,callID:t,node_id:null!=r?r:this.options.nodeId,subscribe:n});"requesting"===this.state&&this.setState("trying"),this.logger.debug("Invite response",s),this.resuming=!1}catch(e){throw this.setState("hangup"),e}}async executeAnswer(e,t,r){"new"===this.state&&this.setState("answering");try{const i=Wr(Object.assign(Object.assign({},this.dialogParams(t)),{sdp:e})),o=await this.vertoExecute({message:i,callID:t,node_id:null!=r?r:this.options.nodeId,subscribe:this.getSubscriptions()});this.logger.debug("Answer response",o),this.resuming=!1,this.setActiveRTCPeer(t)}catch(e){throw this.setState("hangup"),e}}async executeUpdateMedia(e,t){var r,i;try{const r=jr(Object.assign(Object.assign({},this.dialogParams(t)),{sdp:e,action:"updateMedia"})),i=await this.vertoExecute({message:r,callID:t,node_id:this.nodeId});if(this.logger.debug("UpdateMedia response",i),!this.peer)return this.logger.error("Invalid RTCPeer to updateMedia");if(!i.sdp)return this.logger.error("UpdateMedia invalid SDP answer",i);await this.peer.onRemoteSdp(i.sdp)}catch(e){throw this.logger.error("UpdateMedia error",e),null===(i=null===(r=this.peer)||void 0===r?void 0:r._pendingNegotiationPromise)||void 0===i||i.reject(e),e}}async hangup(e){const t=null!=e?e:this.callId;if(!t)throw new Error("Invalid RTCPeer ID to hangup");try{const e=Lr(this.dialogParams(t));await this.vertoExecute({message:e,callID:t,node_id:this.nodeId})}catch(e){this.logger.error("Hangup error:",e)}finally{if(t!==this.callId)return this.logger.warn("Prevent setState hangup",t,this.callId);this.setState("hangup")}}async hangupAll(){const e=this.callId;if(!e)throw new Error("Invalid RTCPeer ID to hangup");try{const t=Lr(Object.assign({cause:"REJECT_ALL",causeCode:"825"},this.dialogParams(e)));await this.vertoExecute({message:t,callID:e,node_id:this.nodeId})}catch(e){this.logger.error("HangupAll error:",e)}finally{this.setState("hangup")}}async sendDigits(e){const t=this.callId;if(!t)throw new Error("Invalid RTCPeer ID to send DTMF");const r=Dr(Object.assign(Object.assign({},this.dialogParams(t)),{dtmf:e}));await this.vertoExecute({message:r,callID:t,node_id:this.nodeId})}doReinviteWithRelayOnly(){this.peer&&this.active&&this.peer.restartIceWithRelayOnly()}stopOutboundAudio(){this.peer&&this.active&&this.peer.stopTrackSender("audio")}restoreOutboundAudio(){this.peer&&this.active&&this.peer.restoreTrackSender("audio")}stopOutboundVideo(){this.peer&&this.active&&this.peer.stopTrackSender("video")}restoreOutboundVideo(){this.peer&&this.active&&this.peer.restoreTrackSender("video")}setState(e){switch(this.prevState=this.state,this.state=e,this.logger.trace(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this.emit(this.state,this),e){case"purge":case"destroy":this._finalize();break;case"hangup":this.setState("destroy")}}updateMediaOptions(e){this.logger.debug("updateMediaOptions",Object.assign({},e)),this.options=Object.assign(Object.assign({},this.options),e),this._checkDefaultMediaConstraints()}_mungeSDP(e){return(e=>{const t=/^a=candidate.*.local\ .*/;return e.split("\r\n").filter((e=>!t.test(e))).join("\r\n")})(e)}_checkDefaultMediaConstraints(){!0===this.options.video&&(this.options.video=Qs),!0===this.options.audio&&(this.options.audio=this.options.screenShare?Js:Gs)}_initPeer(){this.options.remoteSdp&&(this.peer=this._buildPeer("answer"))}_buildPeer(e){const t=new $s(this,e);return this.appendRTCPeer(t),this.runRTCPeerWorkers(t.uuid),t}_finalize(){this.rtcPeerMap.forEach((e=>{e.stop()})),this.rtcPeerMap.clear()}_upsertTransceiverByKind(e,t){if(!this.peer)return this.logger.error("Invalid RTCPeerConnection");let r=this.peer.instance.getTransceivers().find((e=>{var r,i;return(null===(r=e.sender.track)||void 0===r?void 0:r.kind)===t||(null===(i=e.receiver.track)||void 0===i?void 0:i.kind)===t}));if(r){if(r.direction===e)return void this.logger.info(`Transceiver ${t} has the same direction "${e}".`);r.direction=e,this.logger.info(`Updated ${t} transceiver to "${e}" mode.`)}else"inactive"!==e&&(this.peer.type="offer",r=this.peer.instance.addTransceiver(t,{direction:e}),this.logger.info(`Added ${t} transceiver in "${e}" mode.`));"stopped"===e||"inactive"===e?(this.peer.stopTrackReceiver(t),this.peer.stopTrackSender(t)):"sendonly"===e?this.peer.stopTrackReceiver(t):"recvonly"===e&&this.peer.stopTrackSender(t)}async updateMedia(e){var t,r,i,o,n,s;try{const{audio:n,video:s}=e;if(!this.peer)throw new Error("Invalid RTCPeerConnection");if(this.peer.isNegotiating)throw new Error("The peer is already negotiating the media!");const a=this.peer,c=new Promise(((e,t)=>{a._pendingNegotiationPromise={resolve:e,reject:t}})),d=["sendonly","sendrecv"].includes((null==n?void 0:n.direction)||""),l=["sendonly","sendrecv"].includes((null==s?void 0:s.direction)||""),u=["sendrecv","receive"].includes((null==n?void 0:n.direction)||""),h=["sendrecv","receive"].includes((null==s?void 0:s.direction)||"");if(this.updateMediaOptions(Object.assign(Object.assign(Object.assign(Object.assign({},n&&{audio:null!==(t=null==n?void 0:n.constraints)&&void 0!==t?t:d}),s&&{video:null!==(r=null==s?void 0:s.constraints)&&void 0!==r?r:l}),n&&{negotiateAudio:u}),s&&{negotiateVideo:h})),await this.applyConstraintsAndRefreshStream(Object.assign(Object.assign({},n&&{audio:null!==(i=null==n?void 0:n.constraints)&&void 0!==i?i:d}),s&&{video:null!==(o=null==s?void 0:s.constraints)&&void 0!==o?o:l})),n&&!d&&this._upsertTransceiverByKind(n.direction,"audio"),s&&!l&&this._upsertTransceiverByKind(s.direction,"video"),await this.peer.startNegotiation(),await c,!ys({localSdp:this.peer.localSdp,remoteSdp:this.peer.remoteSdp,media:"audio"}))throw new Error("The server did not set the audio direction correctly");if(!ys({localSdp:this.peer.localSdp,remoteSdp:this.peer.remoteSdp,media:"video"}))throw new Error("The server did not set the video direction correctly")}catch(e){throw null===(s=null===(n=this.peer)||void 0===n?void 0:n._pendingNegotiationPromise)||void 0===s||s.reject(e),e}}async setAudioDirection(e){if(!["sendonly","sendrecv","recvonly","inactive"].includes(e))throw new Error("Invalid direction specified");return this.updateMedia({audio:{direction:e}})}async setVideoDirection(e){if(!["sendonly","sendrecv","recvonly","inactive"].includes(e))throw new Error("Invalid direction specified");return this.updateMedia({video:{direction:e}})}async hold(){const e=jr(Object.assign(Object.assign({},this.dialogParams(this.callId)),{action:"hold"}));await this.vertoExecute({message:e,callID:this.callId,node_id:this.nodeId})}async unhold(){const e=jr(Object.assign(Object.assign({},this.dialogParams(this.callId)),{action:"unhold"}));this.vertoExecute({message:e,callID:this.callId,node_id:this.nodeId})}}const Zs=Ur.createAction("swJs/audioSetSpeakerAction"),ea=({speakerId:e})=>function*({instance:t,runSaga:r}){if("undefined"!=typeof Audio)try{const i=t.getAudioEl();let o;t.on("track",(function(n){"audio"===n.track.kind&&(o=r(ra,{track:n.track,element:i,speakerId:e,room:t}))})),t.once("destroy",(()=>{o?.cancel()}))}catch(e){Zt().error("audioElementSaga",e)}else Zt().warn("`Audio` is not supported on this environment.")};function*ta({element:e,room:t}){const r=Ur.getCustomSagaActionType(t.__uuid,Zs);for(;;){const i=yield xe([r]);try{if(i.type===r){const r=yield je(Yn,e,i.payload);t.emit(`${$t}.speaker.updated`,i.payload),t.settleCustomSagaTrigger({dispatchId:i.dispatchId,payload:r,kind:"resolve"})}}catch(e){t.settleCustomSagaTrigger({dispatchId:i.dispatchId,payload:e,kind:"reject"}),Zt().error(e)}}}function*ra({track:e,element:t,speakerId:r,room:i}){(({track:e,element:t})=>{t.autoplay=!0,t.playsinline=!0,t.srcObject=new MediaStream([e]),e.addEventListener("ended",(()=>{t.srcObject=null,t.remove()}))})({track:e,element:t}),r&&Yn(t,r).catch((()=>{})),yield De(ta,{element:t,room:i})}const ia=function*(e){Zt().trace("videoManagerRoomsWorker started");const{instance:t,action:{type:r,payload:i}}=e,o={rooms:i.rooms.map((e=>ar(e)))};t.emit(ur(r),o),Zt().trace("videoManagerRoomsWorker ended")},oa=function*(e){Zt().trace("videoManagerRoomWorker started");const{instance:t,action:{type:r,payload:i}}=e;t.emit(ur(r),ar(i)),Zt().trace("videoManagerRoomWorker ended")},na=function*(e){Zt().trace("videoManagerWorker started");const{channels:{swEventChannel:t}}=e;function*r(t){const{type:r}=t;switch(r){case"video-manager.rooms.subscribed":yield De(ia,{action:t,...e});break;case"video-manager.room.added":case"video-manager.room.deleted":case"video-manager.room.ended":case"video-manager.room.started":case"video-manager.room.updated":yield De(oa,{action:t,...e});break;default:Zt().warn(`Unknown video-manager event: "${r}"`)}}for(;;){const e=yield xe(t,(e=>e.type.startsWith("video-manager.")));yield De(r,e)}Zt().trace("videoManagerWorker ended")};class sa extends Gi{constructor(e){super(e),this.runWorker("videoManagerWorker",{worker:na})}getSubscriptions(){const e=this.eventNames().map((e=>`video-manager.${e}`));return br(e)}}const aa={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,googAutoGainControl:!1},ca="sw-sdk-",da="sw-overlay-",la=e=>`${da}${e}`,ua=lr(class extends Ys{join(){return super.invite()}leave(){return super.hangup()}},{audioMute:io.audioMuteMember,audioUnmute:io.audioUnmuteMember,videoMute:io.videoMuteMember,videoUnmute:io.videoUnmuteMember,setMicrophoneVolume:io.setInputVolumeMember,setInputVolume:io.setInputVolumeMember,setInputSensitivity:io.setInputSensitivityMember}),ha=()=>{},ma="memberList.updated",pa=(e=>{const t=e.split(".")[0];return e.split(".").reduce(((e,r)=>(e.push(r),r===t&&e.push(Ut),e)),[]).join(".")})((({event:e,namespace:t})=>("string"==typeof e&&(e=(({namespace:e,event:t})=>!e||t.startsWith(e)?t:`${e}:${t}`)({event:e,namespace:t}),e=tr(e)),e))({event:ma})),ga=["video.room.joined","video.member.joined","video.member.left","video.member.updated"];function*fa({swEventChannel:e,instance:t}){const r=new Map;function*i(e){const i="video.room.joined"===e.type?e.payload.room_session.id:e.payload.room_session_id,o=(({action:e,memberList:t})=>{const r=(e=>"video.room.joined"===e.type?e.payload.room_session.members:[e.payload.member])(e);return r.forEach("video.member.left"===e.type?e=>{t.delete(e.id)}:e=>{t.set(e.id,e)}),Array.from(t.values())})({action:e,memberList:r});t.emit(pa,{room_session_id:i,members:o})}for(;;){const t=yield xe(e,(({type:e})=>ga.includes(e)));yield De(i,t)}}const va=function*({channels:{swEventChannel:e},instance:t}){const r=t.getSubscriptions();if(!(e=>e.some((e=>e.includes(ma))))(r))return;const{cleanup:i}=((e,t)=>{const r=(e=>br(ga).filter((t=>!e.includes(t))))(t);r.forEach((t=>{e.once(t,ha)}));const i=({members:t})=>{e.emit(ma,{members:t})};return e.on(pa,i),{cleanup:()=>{e.off(pa,i)}}})(t,r);yield De(fa,{swEventChannel:e,instance:t}),t.once("destroy",(()=>{i()}))},ya=function*(e){Zt().trace("childMemberJoinedWorker started");const{channels:t,instance:r,initialState:i,onDone:o,onFail:n}=e,{swEventChannel:s}=t,{parentId:a}=i;if(!a)throw new Error("Missing parentId for childMemberJoinedWorker");const c=yield xe(s,(e=>"video.member.joined"===e.type&&e.payload.member.parent_id===a)),{member:d}=c.payload;if(d?.parent_id){const e=yield We(Xi.getComponentsById);Object.values(e).find((e=>"memberId"in e&&e.memberId===d.parent_id))?(yield Oe(vi.upsert({id:r.callId,roomId:c.payload.room_id,roomSessionId:c.payload.room_session_id,memberId:d.id})),o?.()):n?.({error:new Error("Unknown parent_id")})}Zt().trace("childMemberJoinedWorker ended")},ba=function*(e){Zt().trace("videoStreamWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e;let a=o(i.stream.id);switch(a?a.setPayload(i):a=io.createRoomSessionStreamObject({store:t.store,payload:i}),n(i.stream.id,a),r){case"video.stream.started":t.emit("stream.started",a);break;case"video.stream.ended":t.emit("stream.ended",a),s(i.stream.id);break;default:Zt().warn(`Unknown video.stream event: "${r}"`)}Zt().trace("videoStreamWorker ended")},_a=function*(e){Zt().trace("videoRecordWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e;let a=o(i.recording.id);a?a.setPayload(i):a=io.createRoomSessionRecordingObject({store:t.store,payload:i}),n(i.recording.id,a);const c=ur(r);switch(r){case"video.recording.started":case"video.recording.updated":t.emit(c,a);break;case"video.recording.ended":t.emit(c,a),s(i.recording.id);break;default:Zt().warn(`Unknown video.stream event: "${r}"`)}Zt().trace("videoRecordWorker ended")},wa=function*(e){Zt().trace("videoPlaybackWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e;let a=o(i.playback.id);a?a.setPayload(i):a=io.createRoomSessionPlaybackObject({store:t.store,payload:i}),n(i.playback.id,a);const c=ur(r);switch(r){case"video.playback.started":case"video.playback.updated":t.emit(c,a);break;case"video.playback.ended":t.emit(c,a),s(i.playback.id);break;default:Zt().warn(`Unknown video.stream event: "${r}"`)}Zt().trace("videoPlaybackWorker ended")},ka=function*(e){Zt().trace("videoWorker started");const{channels:t,instance:r}=e,{swEventChannel:i}=t;function*o(t){const{type:i,payload:o}=t;switch(i){case"video.room.subscribed":return void(yield De(Mn.memberPositionWorker,{...e,instance:r,initialState:o}));case"video.playback.started":case"video.playback.updated":case"video.playback.ended":return void(yield De(wa,{action:t,...e}));case"video.recording.started":case"video.recording.updated":case"video.recording.ended":return void(yield De(_a,{action:t,...e}));case"video.stream.ended":case"video.stream.started":return void(yield De(ba,{action:t,...e}));case"video.room.audience_count":return void r.emit("room.audienceCount",o);case"video.member.talking":{const{member:e}=o;"talking"in e&&(r.emit("member.talking."+(e.talking?"started":"ended"),o),r.emit("member.talking."+(e.talking?"start":"stop"),o));break}case"video.layout.changed":r.currentLayoutEvent=t.payload}const n=ur(i,"video");r.emit(n,o)}const n=e=>e.type.startsWith("video.");for(;;){const e=yield xe(i,n);yield De(o,e)}Zt().trace("videoWorker ended")};class Sa extends Ys{_screenShareList=new Set;_audioEl;_overlayMap;_localVideoOverlay;get audioEl(){return this._audioEl}set overlayMap(e){this._overlayMap=e}get overlayMap(){return this._overlayMap}set localVideoOverlay(e){this._localVideoOverlay=e}get localVideoOverlay(){return this._localVideoOverlay}get screenShareList(){return Array.from(this._screenShareList)}_attachSpeakerTrackListener(){Xn()&&Rs().then((e=>{e.on("removed",(async e=>{const t=this._audioEl.sinkId,r=e.changes.find((e=>{const r=e.payload.deviceId;return r===t||""===r&&"default"===t||"default"===r&&""===t}));if(r){this.emit("speaker.disconnected",{deviceId:r.payload.deviceId,label:r.payload.label}),await(this._audioEl.setSinkId?.(""));const e=await xs("default");if(!e?.deviceId)return;this.emit("speaker.updated",{previous:{deviceId:r.payload.deviceId,label:r.payload.label},current:{deviceId:e.deviceId,label:e.label}})}}))}))}_finalize(){this._screenShareList.clear(),super._finalize()}async hangup(e){return this._screenShareList.forEach((e=>{e.leave()})),super.hangup(e)}leave(){return this.hangup()}attachPreConnectWorkers(){this.runWorker("memberListUpdated",{worker:va})}getAudioEl(){return this._audioEl||(this._audioEl=new Audio,this._attachSpeakerTrackListener()),this._audioEl}getMemberOverlay(e){return this.overlayMap.get(la(e))}async startScreenShare(e={}){return new Promise((async(t,r)=>{const{autoJoin:i=!0,audio:o=!1,video:n=!0,layout:s,positions:a}=e;try{const e=await ls({audio:!0===o?aa:o,video:n}),c={...this.options,screenShare:!0,recoverCall:!1,localStream:e,remoteStream:void 0,userVariables:{...this.options?.userVariables||{},memberCallId:this.callId,memberId:this.memberId},layout:s,positions:a},d=$i({store:this.store,Component:ua})(c);return e.getVideoTracks().forEach((e=>{e.addEventListener("ended",(()=>{d&&d.active&&d.leave()}))})),d.once("destroy",(()=>{d.emit("room.left"),this._screenShareList.delete(d)})),d.runWorker("childMemberJoinedWorker",{worker:ya,onDone:()=>t(d),onFail:r,initialState:{parentId:this.memberId}}),this._screenShareList.add(d),i?await d.join():t(d)}catch(e){this.logger.error("ScreenShare Error",e),r(e)}}))}updateSpeaker({deviceId:e}){const t=this.audioEl.sinkId;return this.once(`${$t}.speaker.updated`,(async e=>{const r=await xs(t),i=await xs(e),o=i?.deviceId===r?.deviceId;i?.deviceId&&!o&&this.emit("speaker.updated",{previous:{deviceId:r?.deviceId,label:r?.label},current:{deviceId:i.deviceId,label:i.label}})})),this.triggerCustomSaga(Zs(e))}}const Ca=lr(class extends Ys{join(){return super.invite()}leave(){return super.hangup()}},{audioMute:io.audioMuteMember,audioUnmute:io.audioUnmuteMember,videoMute:io.videoMuteMember,videoUnmute:io.videoUnmuteMember,setInputVolume:io.setInputVolumeMember,setMicrophoneVolume:io.setInputVolumeMember,setInputSensitivity:io.setInputSensitivityMember});class Ia extends Sa{_deviceList=new Set;_currentLayoutEvent;constructor(e){super(e),this.initWorker()}set currentLayoutEvent(e){this._currentLayoutEvent=e}get currentLayoutEvent(){return this._currentLayoutEvent}get currentLayout(){return this._currentLayoutEvent?.layout}get currentPosition(){return this._currentLayoutEvent?.layout.layers.find((e=>e.member_id===this.memberId))?.position}get deviceList(){return Array.from(this._deviceList)}get interactivityMode(){return this.select((({session:e})=>{const{authorization:t}=e;return t?.join_as??""}))}get permissions(){return this.select((({session:e})=>{const{authorization:t}=e;return t?.room?.scopes??[]}))}initWorker(){this.runWorker("videoWorker",{worker:ka})}getSubscriptions(){const e=this.eventNames().map((e=>`video.${String(e)}`));return br(e)}_finalize(){this._deviceList.clear(),super._finalize()}async hangup(e){return this._deviceList.forEach((e=>{e.leave()})),super.hangup(e)}join(){return super.invite()}getLayoutList(){return this.getLayouts()}getMemberList(){return this.getMembers()}async createScreenShareObject(e={}){return this.startScreenShare(e)}addCamera(e={}){const{autoJoin:t=!0,...r}=e;return this.addDevice({autoJoin:t,video:r})}addMicrophone(e={}){const{autoJoin:t=!0,...r}=e;return this.addDevice({autoJoin:t,audio:r})}async addDevice(e={}){return new Promise((async(t,r)=>{const{autoJoin:i=!0,audio:o=!1,video:n=!1}=e;if(!o&&!n)throw new TypeError("At least one of `audio` or `video` must be requested.");const s={...this.options,localStream:void 0,remoteStream:void 0,audio:o,video:n,additionalDevice:!0,recoverCall:!1,userVariables:{...this.options?.userVariables||{},memberCallId:this.callId,memberId:this.memberId}},a=$i({store:this.store,Component:Ca})(s);a.once("destroy",(()=>{a.emit("room.left"),this._deviceList.delete(a)}));try{return a.runWorker("childMemberJoinedWorker",{worker:ya,onDone:()=>t(a),onFail:r,initialState:{parentId:this.memberId}}),this._deviceList.add(a),i?await a.join():t(a)}catch(e){this.logger.error("RoomDevice Error",e),r(e)}}))}}const Ta=lr(Ia,{audioMute:io.audioMuteMember,audioUnmute:io.audioUnmuteMember,videoMute:io.videoMuteMember,videoUnmute:io.videoUnmuteMember,deaf:io.deafMember,undeaf:io.undeafMember,setInputVolume:io.setInputVolumeMember,setOutputVolume:io.setOutputVolumeMember,setMicrophoneVolume:io.setInputVolumeMember,setSpeakerVolume:io.setOutputVolumeMember,setInputSensitivity:io.setInputSensitivityMember,removeMember:io.removeMember,removeAllMembers:io.removeAllMembers,getMembers:io.getMembers,getLayouts:io.getLayouts,setLayout:io.setLayout,setPositions:io.setPositions,setMemberPosition:io.setMemberPosition,hideVideoMuted:io.hideVideoMuted,showVideoMuted:io.showVideoMuted,getRecordings:io.getRecordings,startRecording:io.startRecording,getPlaybacks:io.getPlaybacks,play:io.play,setHideVideoMuted:io.setHideVideoMuted,getMeta:io.getMeta,setMeta:io.setMeta,updateMeta:io.updateMeta,deleteMeta:io.deleteMeta,getMemberMeta:io.getMemberMeta,setMemberMeta:io.setMemberMeta,updateMemberMeta:io.updateMemberMeta,deleteMemberMeta:io.deleteMemberMeta,promote:io.promote,demote:io.demote,getStreams:io.getStreams,startStream:io.startStream,lock:io.lock,unlock:io.unlock,setRaisedHand:io.setRaisedHand,setPrioritizeHandraise:io.setPrioritizeHandraise}),Ea=e=>e instanceof Ia;function Pa(e){this.message=e}(Pa.prototype=new Error).name="InvalidCharacterError";var Ma="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Pa("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,o=0,n=0,s="";i=t.charAt(n++);~i&&(r=o%4?64*r+i:i,o++%4)?s+=String.fromCharCode(255&r>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};function Ra(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Ma(e).replace(/(.)/g,(function(e,t){var r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(e){return Ma(t)}}function Aa(e){this.message=e}function xa(e,t){if("string"!=typeof e)throw new Aa("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(Ra(e.split(".")[r]))}catch(e){throw new Aa("Invalid token specified: "+e.message)}}(Aa.prototype=new Error).name="InvalidTokenError";const Oa=()=>{if(window&&window.sessionStorage)return window.sessionStorage},La=e=>{let t="";try{const r=xa(e);t=r?.r??""}catch(r){try{t=xa(e,{header:!0}).typ||""}catch{t=""}}const r=Boolean(t);return{authStateKey:r&&`as-${t}`,protocolKey:r&&`pt-${t}`,callIdKey:r&&`ci-${t}`}},ja="ci-SAT",Da=function*(e){Zt().debug("wsClientWorker started");const{channels:t,initialState:r,instance:i}=e,{swEventChannel:o}=t,{handleIncomingInvite:n}=r;function*s(e){i.emit(e.type,e.payload)}function*a(e){n(e.payload.params)}const c=e=>"webrtc.message"===e.type&&"verto.invite"===e.payload.method;try{for(;;){const e=yield xe(o,(()=>!0));yield De(s,e),c(e)&&(Zt().debug("Receiving a call over WebSocket",e),yield De(a,e))}}finally{Zt().trace("wsClientWorker ended")}};class Wa extends qi{_payload;constructor(e){super(e),this._payload=e.payload}get id(){return this._payload.member.member_id}get callId(){return this._payload.member.call_id}get nodeId(){return this._payload.member.node_id}get memberId(){return this.id}get roomSessionId(){return this._payload.room_session_id}get roomId(){return this._payload.room_id}get parentId(){return this._payload.member.parent_id}get subscriberId(){return this._payload.member.subscriber_id}get addressId(){return this._payload.member.address_id}get name(){return this._payload.member.name}get type(){return this._payload.member.type}get requestedPosition(){return this._payload.member.requested_position}get currentPosition(){return this._payload.member.current_position}get meta(){return this._payload.member.meta}get handraised(){return this._payload.member.handraised}get talking(){return this._payload.member.talking}get audioMuted(){return this._payload.member.audio_muted}get videoMuted(){return this._payload.member.video_muted}get deaf(){return this._payload.member.deaf}get visible(){return this._payload.member.visible}get inputVolume(){return this._payload.member.input_volume}get outputVolume(){return this._payload.member.output_volume}get inputSensitivity(){return this._payload.member.input_sensitivity}get echoCancellation(){return this._payload.member.echo_cancellation}get autoGain(){return this._payload.member.auto_gain}get noiseSuppression(){return this._payload.member.noise_suppression}setPayload(e){const t={...this._payload,...e,member:{...this._payload.member,...e.member}};this._payload=t}}const Va=e=>$i({store:e.store,Component:Wa})(e),Na=function*(e){Zt().trace("callLeftWorker started");const{action:{payload:t},instance:r,instanceMap:i}=e,{room_session_id:o}=t;i.getAll().forEach((([e,t])=>{t instanceof Wa&&t.roomSessionId===o&&i.remove(e)})),r.emit("call.left",t),r.emit("room.left",t),Zt().trace("callLeftWorker ended")},$a=function*(e){Zt().trace("fabricMemberWorker started");const{instance:t,action:{type:r,payload:i},instanceMap:{get:o,set:n,remove:s}}=e,a=i.member.member_id;let c=o(a);if(c||"member.talking"===r||(c=Va({store:t.store,payload:i})),c&&c.setPayload(i),n(a,c),r.startsWith("member.updated.")){const e=cr(r);t.emit(e,i)}switch(r){case"member.joined":case"member.updated":case"member.talking":t.emit(r,i);break;case"member.left":t.emit(r,i),s(a)}Zt().trace("fabricMemberWorker ended")};class Ua{_flags;constructor(e){this._flags=e}get on(){return this._flags.some((e=>!e.endsWith(".off")))}get off(){return this._flags.some((e=>!e.endsWith(".on")))}}class za{_flags;_memberType;_muteAudio;_muteVideo;_deaf;_raisehand;constructor(e,t){this._flags=e,this._memberType=t}get muteAudio(){return this._muteAudio=this._muteAudio??new Ua(this._flags.filter((e=>e===this._memberType||e===`${this._memberType}.mute`||e.startsWith(`${this._memberType}.mute.audio`)))),this._muteAudio}get muteVideo(){return this._muteVideo=this._muteVideo??new Ua(this._flags.filter((e=>e===this._memberType||e===`${this._memberType}.mute`||e.startsWith(`${this._memberType}.mute.video`)))),this._muteVideo}get microphoneVolume(){return this._flags.some((e=>e===this._memberType||e===`${this._memberType}.microphone`||e.startsWith(`${this._memberType}.microphone.volume`)))}get microphoneSensitivity(){return this._flags.some((e=>e===this._memberType||e===`${this._memberType}.microphone`||e.startsWith(`${this._memberType}.microphone.sensitivity`)))}get speakerVolume(){return this._flags.some((e=>e===this._memberType||e===`${this._memberType}.speaker`||e.startsWith(`${this._memberType}.speaker.volume`)))}get deaf(){return this._deaf=this._deaf??new Ua(this._flags.filter((e=>e===this._memberType||e.startsWith(`${this._memberType}.deaf`)))),this._deaf}get raisehand(){return this._raisehand=this._raisehand??new Ua(this._flags.filter((e=>e===this._memberType||e.startsWith(`${this._memberType}.raisehand`)))),this._raisehand}get position(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.position`)))}get meta(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.meta`)))}get remove(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.remove`)))}get audioFlags(){return this._flags.some((e=>e===this._memberType||e.startsWith(`${this._memberType}.audioflags.set`)))}}class Ba{_flags;_self;_member;_vmutedHide;_lock;constructor(e){this._flags=e}_buildMemberCapability(e){return new za(this._flags.filter((t=>t.startsWith(e))),e)}get self(){return this._self=this._self??this._buildMemberCapability("self"),this._self}get member(){return this._member=this._member??this._buildMemberCapability("member"),this._member}get end(){return this._flags.some((e=>"end"===e))}get setLayout(){return this._flags.some((e=>e.startsWith("layout")))}get sendDigit(){return this._flags.some((e=>e.startsWith("digit")))}get vmutedHide(){return this._vmutedHide=this._vmutedHide??new Ua(this._flags.filter((e=>e.startsWith("vmuted")))),this._vmutedHide}get lock(){return this._lock=this._lock??new Ua(this._flags.filter((e=>e.startsWith("lock")))),this._lock}get device(){return this._flags.some((e=>"device"===e))}get screenshare(){return this._flags.some((e=>"screenshare"===e))}}const Fa=e=>({...e,id:e.member_id}),Ha=e=>({...Fa(e),updated:e.updated.map((e=>"member_id"===e?"id":e))}),qa=function*(e){Zt().trace("callJoinWorker started");const{action:t,instanceMap:r,instance:i}=e,{payload:o}=t,{get:n,set:s}=r;var a;yield De(Mn.memberPositionWorker,{...e,initialState:(a=o,{...a,room:{...a.room_session,members:a.room_session.members.map(Fa)},room_session:{...a.room_session,members:a.room_session.members.map(Fa)}}),dispatcher:function*(t,r){const i=ur(t,"video"),o={...r,member:{...r.member,member_id:r.member.id}};yield De($a,{...e,action:{type:i,payload:o}})}}),o.room_session.members?.forEach((e=>{let t=n(e.member_id);t?t.setPayload({member:e,room_id:o.room_id,room_session_id:o.room_session_id}):t=Va({store:i.store,payload:{member:e,room_id:o.room_id,room_session_id:o.room_session_id}}),s(e.member_id,t)})),i.member=n(o.member_id),i.capabilities=new Ba(o.capabilities);const c={...o,capabilities:i.capabilities};i.emit("call.joined",c),Zt().trace("callJoinWorker ended")},Ka=function*(e){const{action:t,channels:{swEventChannel:r},instance:i}=e,o=t.payload.call_id,n=t.payload.room_session_id;function*s(t){const{type:o,payload:n}=t;switch(o){case"call.joined":break;case"call.left":return yield je(Na,{...e,action:t}),!0;case"call.updated":i.emit(o,n),i.emit("room.updated",n);break;case"call.play":case"call.connect":case"call.room":i.emit(o,n);break;case"member.joined":case"member.left":{yield De($a,{...e,action:t});const i=(e=>{return{type:`video.${e.type}`,payload:(t=e.payload,{room_session_id:t.room_session_id,room_id:t.room_id,member:Fa(t.member)})};var t})(t);yield Oe(r,i);break}case"member.updated":{const e=(e=>{return{type:`video.${e.type}`,payload:(t=e.payload,{room_session_id:t.room_session_id,room_id:t.room_id,member:Ha(t.member)})};var t})(t);yield Oe(r,e);break}case"layout.changed":{i.currentLayoutEvent=t.payload,i.emit(o,n);const e=(e=>({type:`video.${e.type}`,payload:e.payload}))(t);yield Oe(r,e);break}case"member.talking":yield De($a,{...e,action:t});break;default:Zt().warn("Got an unknown fabric event",t)}return!1}Zt().debug(`callSegmentWorker started for: callId ${o}, roomSessionId ${n}`),yield De(qa,{...e,action:t});const a=e=>{const{type:t,payload:r}=e;return!(!(t.startsWith("call.")||t.startsWith("member.")||t.startsWith("layout."))||(!("call_id"in r)||o!==r.call_id)&&n!==r.room_session_id)};for(;;){const e=yield xe(r,a),t=yield De(s,e);if(yield(c=t,Ae(Pe,c)))return}var c},Ga=function*(e){Zt().trace("fabricWorker started");const{channels:{swEventChannel:t},instance:r}=e;function*i(t){const{type:i,payload:o}=t;switch(i){case"call.joined":if(!r.selfMember){const e=Va({store:r.store,payload:{member:t.payload.room_session.members.find((e=>e.member_id===t.payload.member_id)),room_id:t.payload.room_id,room_session_id:t.payload.room_session_id}});r.selfMember=e}yield De(Ka,{...e,instance:r,action:t});break;case"call.state":r.emit(i,o)}}let o=!1;const n=e=>"call.state"===e.type||"call.joined"===e.type&&(!!o||e.payload.call_id===e.payload.origin_call_id&&(o=!0,!0));for(;;){const e=yield xe(t,n);yield De(i,e)}Zt().trace("fabricWorker ended")},Ja=(e,t)=>!e?.memberId||e.memberId===t.member.id,Qa={audioMute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteAudio.off:this.capabilities?.member.muteAudio.off))throw new Ei("Missing audio mute capability")},audioUnmute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteAudio.on:this.capabilities?.member.muteAudio.on))throw new Ei("Missing audio unmute capability")},videoMute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteVideo.off:this.capabilities?.member.muteVideo.off))throw new Ei("Missing video mute capability")},videoUnmute:function(e){if(!(Ja(e,this)?this.capabilities?.self.muteVideo.on:this.capabilities?.member.muteVideo.on))throw new Ei("Missing video unmute capability")},deaf:function(e){if(!(Ja(e,this)?this.capabilities?.self.deaf.on:this.capabilities?.member.deaf.on))throw new Ei("Missing deaf capability")},undeaf:function(e){if(!(Ja(e,this)?this.capabilities?.self.deaf.off:this.capabilities?.member.deaf.off))throw new Ei("Missing undeaf capability")},removeMember:function(e){if(!e?.memberId)throw new TypeError('Invalid or missing "memberId" argument');const t=this.capabilities?.member.remove;if(!t)throw new Ei("Missing remove member capability")},setRaisedHand:function(e){const{raised:t=!0}=e||{},r=Ja(e,this),i=r?this.capabilities?.self.raisehand.on:this.capabilities?.member.raisehand.on,o=r?this.capabilities?.self.raisehand.off:this.capabilities?.member.raisehand.off;if(t&&!i)throw new Ei("Missing raisehand capability");if(!t&&!o)throw new Ei("Missing lowerhand capability")},setLayout:function(){if(!this.capabilities?.setLayout)throw new Ei("Missing setLayout capability")},setInputVolume:function(e){if(!(Ja(e,this)?this.capabilities?.self?.microphoneVolume:this.capabilities?.member?.microphoneVolume))throw new Ei("Missing setInputVolume capability");if(e.volume<-50||e.volume>50)throw new RangeError("The volume ranges from -50 to 50")},setOutputVolume:function(e){if(!(Ja(e,this)?this.capabilities?.self?.speakerVolume:this.capabilities?.member?.speakerVolume))throw new Ei("Missing setOutputVolume capability");if(e.volume<-50||e.volume>50)throw new RangeError("The volume ranges from -50 to 50")},setInputSensitivity:function(e){if(!(Ja(e,this)?this.capabilities?.self.microphoneSensitivity:this.capabilities?.member.microphoneSensitivity))throw new Ei("Missing setInputSensitivity capability");if(e.value<0||e.value>100)throw new RangeError("The sensitivity value ranges from 0 to 100")},setPositions:function(e){if(e.positions&&!Object.keys(e.positions).length)throw new TypeError("Invalid positions specified");if(!(Object.keys(e.positions).some((e=>["self",`${this.memberId}`].includes(e)))?this.capabilities?.self.position:this.capabilities?.member.position))throw new Ei("Missing setPositions capability")},lock:function(){if(!this.capabilities?.lock.on)throw new Ei("Missing lock capability")},unlock:function(){if(!this.capabilities?.lock.off)throw new Ei("Missing unlock capability")},setAudioFlags:function(e){if(!(Ja(e,this)?this.capabilities?.self.audioFlags:this.capabilities?.member.audioFlags))throw new Ei("Missing audio flags capability");const{echoCancellation:t,autoGain:r,noiseSuppression:i}=e||{};if(void 0===t&&void 0===r&&void 0===i)throw new TypeError("Invalid parameters: you must specify at least one of `echoCancellation`, `autoGain`, or `noiseSuppression`")},end:function(){const e=this.capabilities?.end;if(!e)throw new Ei("Missing 'end' capability")}};class Xa extends Sa{_self;_member;_currentLayoutEvent;_capabilities;constructor(e){super(e),this.initWorker()}get memberId(){return this._member?.memberId}dialogParams(e){const t=super.dialogParams(e);return t.dialogParams.attach=this.options.attach||this.resuming,t.dialogParams.reattaching=this.options.attach||this.resuming,t}set currentLayoutEvent(e){this._currentLayoutEvent=e}get currentLayoutEvent(){return this._currentLayoutEvent}get currentLayout(){return this._currentLayoutEvent?.layout}get currentPosition(){return this._currentLayoutEvent?.layout.layers.find((e=>e.member_id===this.memberId))?.position}get capabilities(){return this._capabilities}set capabilities(e){this._capabilities=e}get selfMember(){return this._self}set selfMember(e){this._self=e}set member(e){this._member=e}get member(){return this._member}initWorker(){this.runWorker("fabricWorker",{worker:Ga}),this.runWorker("makeAudioElement",{worker:ea({speakerId:this.options.speakerId})})}async join(){return this.options.attach&&(this.options.prevCallId=Oa()?.getItem(ja)??void 0,this.logger.debug(`Tying to reattach to previuos call? ${!!this.options.prevCallId} - prevCallId: ${this.options.prevCallId}`)),super.invite()}executeAction(e,t={}){const{method:r,channel:i,memberId:o,extraParams:n={}}=e,s=o&&"all"!==o?this.instanceMap.get(o):this.member;if(!s)throw new Error(o&&"all"!==o?`Member ${o} not found`:"No target member available");return this.execute({method:r,params:{...i&&{channels:[i]},self:{member_id:this.selfMember?.id,call_id:this.selfMember?.callId,node_id:this.selfMember?.nodeId},target:{member_id:"all"===o?o:s.id,call_id:s.callId,node_id:s.nodeId},...n}},t)}async resume(){if(this.logger.warn(`[resume] Call ${this.id}`),this.peer?.instance){const{connectionState:e}=this.peer.instance;this.logger.debug(`[resume] connectionState for ${this.id} is '${e}'`),["closed","failed","disconnected"].includes(e)&&(this.resuming=!this.selfMember,this.peer.restartIce())}}async start(){return new Promise((async(e,t)=>{try{this.once("room.subscribed",(t=>{Oa()?.setItem(ja,t.call_id),e()})),this.once("destroy",(()=>{Oa()?.removeItem(ja)})),await this.join()}catch(e){this.logger.error("WSClient call start",e),t(e)}}))}async audioMute(e){return this.executeAction({method:"call.mute",channel:"audio",memberId:e?.memberId})}async audioUnmute(e){return this.executeAction({method:"call.unmute",channel:"audio",memberId:e?.memberId})}async videoMute(e){return this.executeAction({method:"call.mute",channel:"video",memberId:e?.memberId})}async videoUnmute(e){return this.executeAction({method:"call.unmute",channel:"video",memberId:e?.memberId})}async deaf(e){return this.executeAction({method:"call.deaf",memberId:e?.memberId})}async undeaf(e){return this.executeAction({method:"call.undeaf",memberId:e?.memberId})}async getLayouts(){return this.executeAction({method:"call.layout.list"},{transformResolve:e=>({layouts:e.layouts})})}async getMembers(){return this.executeAction({method:"call.member.list"},{transformResolve:e=>({members:e.members})})}async removeMember(e){return this.executeAction({method:"call.member.remove",memberId:e.memberId})}async setRaisedHand(e){const{raised:t=!0,memberId:r}=e||{};return this.executeAction({method:t?"call.raisehand":"call.lowerhand",memberId:r})}async setLayout(e){return this.executeAction({method:"call.layout.set",extraParams:{layout:e.name,positions:e.positions}})}async setInputVolume(e){return this.executeAction({method:"call.microphone.volume.set",memberId:e.memberId,extraParams:{volume:e.volume}})}async setOutputVolume(e){return this.executeAction({method:"call.speaker.volume.set",memberId:e.memberId,extraParams:{volume:e.volume}})}async setInputSensitivity(e){return this.executeAction({method:"call.microphone.sensitivity.set",memberId:e.memberId,extraParams:{sensitivity:e.value}})}async setPositions(e){const t=[];if(Object.entries(e.positions).forEach((([e,r])=>{const i="self"===e?this.member:this.instanceMap.get(e);i&&t.push({target:{member_id:i.id,call_id:i.callId,node_id:i.nodeId},position:r})})),!t.length)throw new Error("Invalid targets");return this.execute({method:"call.member.position.set",params:{self:{member_id:this.selfMember?.id,call_id:this.selfMember?.callId,node_id:this.selfMember?.nodeId},targets:t}})}async lock(){return this.executeAction({method:"call.lock"})}async unlock(){return this.executeAction({method:"call.unlock"})}async setAudioFlags(e){const{memberId:t,...r}=e;return this.executeAction({method:"call.audioflags.set",memberId:t,extraParams:dr(r)})}async end(e){return this.executeAction({method:"call.end",memberId:e?.memberId})}}const Ya=e=>e instanceof Xa;class Za{id;_domElement;_status;constructor(e){this.id=e.id,this._status="hidden"}get userId(){return this.id.split(da)[1]}get domElement(){return this._domElement}set domElement(e){Zt().debug("Setting domElement for ",this.id),this._domElement=e}get status(){return this._status}set status(e){this._status=e}hide(){if(!this.domElement)return Zt().warn("Missing overlay to hide");this.domElement.style.opacity="0",this.status="hidden"}show(){if(!this.domElement)return Zt().warn("Missing overlay to show");this.domElement.style.opacity="1",this.status="visible"}}class ec extends Za{_mirrored;_room;constructor(e){super(e),this._mirrored=e.mirrorLocalVideoOverlay,this._room=e.room,this.fabricMemberVideoMutedHandler=this.fabricMemberVideoMutedHandler.bind(this),this.videoMemberVideoMutedHandler=this.videoMemberVideoMutedHandler.bind(this),this.attachListeners()}get userId(){return this.id.split(ca)[1]}get mirrored(){return this._mirrored}attachListeners(){Ya(this._room)?this._room.on("member.updated.videoMuted",this.fabricMemberVideoMutedHandler):Ea(this._room)&&this._room.on("member.updated.videoMuted",this.videoMemberVideoMutedHandler)}detachListeners(){Ya(this._room)?this._room.off("member.updated.videoMuted",this.fabricMemberVideoMutedHandler):Ea(this._room)&&this._room.off("member.updated.videoMuted",this.videoMemberVideoMutedHandler)}memberVideoMutedHandler(e,t){try{e===this._room.memberId&&(t?this.hide():this.show())}catch(e){Zt().error("Error handling videoMuted in LocalVideoOverlay",e)}}fabricMemberVideoMutedHandler(e){this.memberVideoMutedHandler(e.member.member_id,e.member.video_muted)}videoMemberVideoMutedHandler(e){this.memberVideoMutedHandler(e.member.id,e.member.video_muted)}setMediaStream(e){if(!this.domElement)return Zt().warn("Missing local overlay to set the stream");const t=this.domElement.querySelector("video");t&&(t.srcObject=e)}setMirror(e=this._mirrored){if(!this.domElement||!this.domElement.firstChild)return Zt().warn("Missing local overlay to set the mirror");const t=this.domElement.firstChild;t.style.transform=e?"scale(-1, 1)":"scale(1, 1)",t.style.webkitTransform=e?"scale(-1, 1)":"scale(1, 1)",this._mirrored=e}}const tc=()=>{const e=document.createElement("video");return e.muted=!0,e.autoplay=!0,e.playsInline=!0,e.addEventListener("pause",(()=>{e.play().catch((t=>{Zt().error("Video Element Paused",e,t)}))})),e},rc=({x:e,y:t,width:r,height:i})=>({top:`${t}%`,left:`${e}%`,width:`${r}%`,height:`${i}%`}),ic=({location:e})=>{const{top:t,left:r,width:i,height:o}=rc(e),n=document.createElement("div");return n.style.position="absolute",n.style.overflow="hidden",n.style.top=t,n.style.left=r,n.style.width=i,n.style.height=o,n},oc=({location:e,element:t})=>{const{top:r,left:i,width:o,height:n}=rc(e);return t.style.top=r,t.style.left=i,t.style.width=o,t.style.height=n,t},nc=({video:e,rootElement:t,paddingWrapper:r})=>{const i=function(e,t=0,r){let i=null,o=null;const n=function(){i&&(clearTimeout(i),o=null,i=null)},s=function(){if(!t)return e.apply(this,arguments);const s=this,a=arguments,c=r&&!i;return n(),o=function(){e.apply(s,a)},i=setTimeout((function(){if(i=null,!c){const e=o;return o=null,null==e?void 0:e()}}),t),c&&o?o():void 0};return s.cancel=n,s.flush=function(){const e=o;n(),e&&e()},s}((({width:t,height:i})=>{const o=e.videoHeight/e.videoWidth*100;if(r){const n=i/t*100;r.style.paddingBottom=`${n>o?o:n}%`,r.style.width=((t,r)=>{const i=e.videoWidth/e.videoHeight;return i>t/r?"100%":r*i+"px"})(t,i)}}),100),o=new ResizeObserver((e=>{e.forEach((e=>{if(e.contentBoxSize){const{inlineSize:t,blockSize:r}=Array.isArray(e.contentBoxSize)?e.contentBoxSize[0]:e.contentBoxSize;i({width:t,height:r})}else e.contentRect&&i({width:e.contentRect.width,height:e.contentRect.height})}))})),n=()=>{i({width:t.clientWidth,height:t.clientHeight})};return{start:()=>{o.observe(t),e.addEventListener("resize",n)},stop:()=>{o.disconnect(),e.removeEventListener("resize",n)}}},sc=async e=>{try{const{room:t,rootElement:r,applyLocalVideoOverlay:i=!0,applyMemberOverlay:o=!0,mirrorLocalVideoOverlay:n=!0}=e;let s=!1;const a=new Map,c=b();let d;r?d=r:(d=document.createElement("div"),d.id=`rootElement-${c}`);const l=(e=>`${ca}${e}`)(c),u=new ec({id:l,mirrorLocalVideoOverlay:n,room:t});i&&a.set(l,u);const h=(e=>{const{applyLocalVideoOverlay:t,applyMemberOverlay:r,overlayMap:i,localVideoOverlay:o,mirrorLocalVideoOverlay:n,rootElement:s}=e;return async e=>{Zt().debug("Process layout.changed");try{const{layout:a,memberId:c,localStream:d}=e,{layers:l=[]}=a,u=s.querySelector(".mcuLayers"),h=document.createDocumentFragment(),m=new Set;if(t){const e=l.find((({member_id:e})=>e===c)),t=o.id;let r=o.domElement;if(m.add(t),e){if(r)Zt().debug("Update local video overlay"),oc({location:e,element:r});else{Zt().debug("Build local video overlay"),r=ic({location:e}),r.id=t;const i=tc();i.srcObject=d,i.disablePictureInPicture=!0,i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.objectFit="cover",r.appendChild(i),o.domElement=r,n&&o.setMirror()}const i=d.getVideoTracks().filter((e=>e.enabled&&"live"===e.readyState)).length>0;i&&e.visible?(o.setMediaStream(d),o.show()):o.hide(),h.appendChild(r)}else Zt().warn("Local video overlay location not found",c),o.status="hidden",r&&o.hide()}r&&l.forEach((e=>{const t=e.member_id;if(!t)return;const r=la(t);m.add(r);let o=i.get(r);if(o&&o.domElement)Zt().debug("Update an overlay for",t),oc({location:e,element:o.domElement});else{Zt().debug("Build an overlay for",t),o=new Za({id:r}),i.set(r,o);const n=ic({location:e});n.id=`${r}-${b()}`,o.domElement=n}e.visible?o.show():o.hide(),h.appendChild(o.domElement)})),i.forEach(((e,t)=>{m.has(t)||(e.domElement&&e.domElement.parentNode&&e.domElement.parentNode.removeChild(e.domElement),i.delete(t))})),u&&(u.innerHTML="",u.appendChild(h))}catch(e){Zt().error("Layout Changed Error",e)}}})({applyLocalVideoOverlay:i,applyMemberOverlay:o,overlayMap:a,localVideoOverlay:u,mirrorLocalVideoOverlay:n,rootElement:d}),m=e=>{const r=t.peer?.hasVideoSender;r&&t.localStream?h({layout:e.layout,localStream:t.localStream,memberId:t.memberId}):(Zt().debug("No local video sender or local stream, hiding local video overlay",r,t.localStream),u.hide())},p=e=>{Zt().debug("Received layout.changed - videoTrack",s),s&&m(e)},g=async e=>{s=!0,await ac({applyLocalVideoOverlay:i,applyMemberOverlay:o,rootElement:d,track:e});const r=t.currentLayoutEvent;r&&m(r)},f=t.peer?.remoteVideoTrack;f&&await g(f);const v=async function(e){"video"===e.track.kind&&await g(e.track)},y=()=>{(e=>{for(;e.firstChild;)e.removeChild(e.firstChild)})(d),a.clear(),t.overlayMap=a,(Ya(t)||Ea(t))&&(t.off("track",v),t.off("layout.changed",p),t.off("destroy",y)),u.detachListeners()};return(Ya(t)||Ea(t))&&(t.on("track",v),t.on("layout.changed",p),t.once("destroy",y)),t.overlayMap=a,t.localVideoOverlay=u,{element:d,overlayMap:a,localVideoOverlay:u,unsubscribe:y}}catch(e){throw Zt().error("Unable to build the video element"),e}},ac=async e=>{try{const{applyLocalVideoOverlay:t,applyMemberOverlay:r,track:i,rootElement:o}=e,n=tc();if((({track:e,element:t})=>{t.srcObject=new MediaStream([e]),e.addEventListener("ended",(()=>{t.srcObject=null,t.remove()}))})({element:n,track:i}),n.style.width="100%",n.style.maxHeight="100%",o.querySelector(".mcuContent"))return void Zt().debug("MCU Content already there");const s=document.createElement("div");s.style.position="absolute",s.style.top="0",s.style.left="0",s.style.right="0",s.style.bottom="0",s.appendChild(n);const a=document.createElement("div");a.classList.add("paddingWrapper"),a.style.paddingBottom="56.25%",a.style.position="relative",a.style.width="100%",a.appendChild(s);let c=null;(t||r)&&(c=document.createElement("div"),c.classList.add("mcuLayers"),c.style.display="none",a.appendChild(c));const d=document.createElement("div");d.classList.add("mcuContent"),d.style.position="relative",d.style.width="100%",d.style.height="100%",d.style.margin="0 auto",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.appendChild(a),o.style.width="100%",o.style.height="100%",o.appendChild(d),Zt().debug("MCU readyState 1 >>",n.readyState),n.readyState===HTMLMediaElement.HAVE_NOTHING&&(Zt().debug("Wait for the MCU to be ready"),await(({element:e})=>new Promise((t=>{e.addEventListener("canplay",(function r(){e.removeEventListener("canplay",r),t()})),e.addEventListener("resize",(function r(){e.removeEventListener("resize",r),t()}))})))({element:n})),Zt().debug("MCU is ready..");const l=nc({rootElement:o,video:n,paddingWrapper:a});l.start(),i.addEventListener("ended",(()=>{l&&l.stop()})),c&&(c.style.display="block")}catch(e){Zt().error("Handle video track error",e)}};class cc extends Ki{_videoManager;_chat;_pubSub;get rooms(){return{makeRoomObject:e=>{const{rootElement:t,applyLocalVideoOverlay:r=!0,applyMemberOverlay:i=!0,mirrorLocalVideoOverlay:o=!0,stopCameraWhileMuted:n=!0,stopMicrophoneWhileMuted:s=!0,...a}=e,c=[];c.push(ea({speakerId:a.speakerId}));const d=(l={...a,store:this.store,customSagas:c},$i({store:l.store,customSagas:l.customSagas,Component:Ta})(l));var l;if(t)try{sc({applyLocalVideoOverlay:r,applyMemberOverlay:i,mirrorLocalVideoOverlay:o,room:d,rootElement:t})}catch(e){this.logger.error("Unable to build the video element automatically")}return d.on("room.subscribed",(e=>{const t=e.room_session.members?.find((e=>e.id===d.memberId));if(t?.audio_muted)try{d.stopOutboundAudio()}catch(e){this.logger.error("Error handling audio_muted",e)}if(t?.video_muted)try{d.stopOutboundVideo()}catch(e){this.logger.error("Error handling video_muted",e)}})),s&&d.on("member.updated.audio_muted",(({member:e})=>{try{e.id===d.memberId&&"audio_muted"in e&&(e.audio_muted?d.stopOutboundAudio():d.restoreOutboundAudio())}catch(e){this.logger.error("Error handling audio_muted",e)}})),n&&d.on("member.updated.video_muted",(({member:e})=>{try{e.id===d.memberId&&"video_muted"in e&&(e.video_muted?d.stopOutboundVideo():d.restoreOutboundVideo())}catch(e){this.logger.error("Error handling video_muted",e)}})),d}}}get chat(){return this._chat||(this._chat=tn.createBaseChatObject({store:this.store})),this._chat}get pubSub(){return this._pubSub||(this._pubSub=pn.createBasePubSubObject({store:this.store})),this._pubSub}get videoManager(){return this._videoManager||(this._videoManager=(e=>{const t=$i({store:e.store,Component:sa})(e);return new Proxy(t,{get:(e,t,r)=>"_eventsNamespace"===t?"":"eventChannel"===t?"video-manager.rooms":Reflect.get(e,t,r)})})(this.options)),this._videoManager}reauthenticate(e){this.store.dispatch(Ur.reauthAction({token:e}))}}const dc="function"==typeof CloseEvent?CloseEvent:class{constructor(e,t={}){this.type=e,Nt(this,"code"),Nt(this,"reason"),Nt(this,"wasClean"),this.code=void 0===t.code?0:t.code,this.reason=void 0===t.reason?"":t.reason,this.wasClean=void 0!==t.wasClean&&t.wasClean}};class lc extends pi{options;WebSocketConstructor=WebSocket;CloseEventConstructor=dc;agent="@signalwire/js/browser/3.29.2";tokenTyp;constructor(e){let t={};try{t=xa(e.token,{header:!0})}catch(e){}super({...e,host:t?.ch||e.host}),this.options=e,this.tokenTyp=t.typ??"VRT"}get allowReattach(){return!1!==this.options?.reattach&&(this.isVRT()||this.isSAT())}async retrieveRelayProtocol(){if(!this.allowReattach)return"";const{protocolKey:e}=La(this.options.token);return e?(this.logger.trace("Search protocol for",e),Oa()?.getItem(e)??""):""}async persistRelayProtocol(){if(!this.allowReattach)return;const{protocolKey:e}=La(this.options.token);e&&(this.logger.trace("Persist protocol",e,this.relayProtocol),Oa()?.setItem(e,this.relayProtocol))}removeRelayProtocol(){const{protocolKey:e}=La(this.options.token);e&&(this.logger.debug("Remove protocol",e,this.relayProtocol),Oa()?.removeItem(e))}removePrevCallId(){const{callIdKey:e}=La(this.options.token);e&&(this.logger.debug("Remove Call",e),Oa()?.removeItem(e))}async retrieveSwAuthorizationState(){const{authStateKey:e}=La(this.options.token);return e?Oa()?.getItem(e)??"":""}async persistSwAuthorizationState(e){if(!this.allowReattach)return;const{authStateKey:t}=La(this.options.token);t&&(this.logger.trace("Persist auth state",t,e),Oa()?.setItem(t,e))}removeSwAuthorizationState(){const{authStateKey:e}=La(this.options.token);e&&(this.logger.trace("Remove auth state",e),Oa()?.removeItem(e))}_onSocketClose(e){if("disconnected"===this.status){const{protocolKey:e,authStateKey:t,callIdKey:r}=La(this.options.token);this.logger.debug("Cleaning up storage"),e&&(this.logger.debug("Remove protocolKey",e),Oa()?.removeItem(e)),t&&(this.logger.debug("Remove authStateKey",t),Oa()?.removeItem(t)),r&&(this.logger.debug("Remove callIdKey",r),Oa()?.removeItem(r))}super._onSocketClose(e)}isVRT(){return"VRT"===this.tokenTyp}isSAT(){return"SAT"===this.tokenTyp}}const uc=e=>{const t={...e,emitter:Ui()},r=zi({userOptions:t,SessionConstructor:lc});return $i({store:r,Component:cc})(t)},hc=["subscribe","publish","getMessages","getMembers","getMemberState","getAllowedChannels","setMemberState"];var mc=/*#__PURE__*/Object.freeze({__proto__:null,Client:function(e){const t=uc(e),r={_session:t,disconnect:()=>t.disconnect()};return new Proxy(t.chat,{get:(e,i,o)=>i in r?r[i]:hc.includes(i)?(e=>async(...r)=>(await t.connect(),t.chat[e](...r)))(i):Reflect.get(e,i,o)})},ChatMember:In,ChatMessage:Cn});const pc=["getAllowedChannels","subscribe","publish"];var gc=/*#__PURE__*/Object.freeze({__proto__:null,PubSubMessage:pn.PubSubMessage,Client:function(e){const t=uc(e),r={_session:t,disconnect:()=>t.disconnect()};return new Proxy(t.pubSub,{get:(e,i,o)=>i in r?r[i]:pc.includes(i)?(e=>async(...r)=>(await t.connect(),t.pubSub[e](...r)))(i):Reflect.get(e,i,o)})}});async function fc(e,t,r,i,o){const n=await pr({asyncCallable:()=>fetch(e,t),maxRetries:r,validator:e=>{if(!e.ok&&e.status>=500)throw new Ti(e.status,e.statusText)},delayFn:hr({initialDelay:i,variation:o})});if(!n.ok){if(401===n.status)throw new Ii(n.status,"Unauthorized");let e;try{e=await n.json()}catch(e){}const t=e?.errors?JSON.stringify(e.errors):"Not Found";throw new Ti(n.status,t,e)}try{n.parsedBody=await n.json()}catch(e){}return n}const vc=({baseUrl:e,maxApiRequestRetries:t=0,apiRequestRetriesDelay:r=0,apiRequestRetriesDelayIncrement:i=0,timeout:o=3e4,...n},s=fc)=>async(a,c)=>{const d={...c?.body?{"Content-Type":"application/json"}:{},...n.headers,...c?.headers},l=yc({...n,...c,headers:d});let u;if(o){const e=new AbortController;l.signal=e.signal,u=setTimeout((()=>{e.abort()}),o)}try{return{body:(await s(bc({path:a,baseUrl:e,searchParams:c?.searchParams}),l,t,r,i)).parsedBody}}catch(e){throw e}finally{u&&clearTimeout(u)}},yc=e=>Object.entries(e).reduce(((e,[t,r])=>{return"body"===t?{...e,body:(i=r,"string"==typeof i?i:JSON.stringify(i))}:null!=r?{...e,[t]:r}:e;var i}),{}),bc=({path:e,baseUrl:t,searchParams:r})=>{const i=new URL(e,t);return r&&Object.entries(r).forEach((([e,t])=>{null!=t&&i.searchParams.append(e,t)})),i.toString()};function _c(e,t){const r=async e=>{if(!e)return Promise.resolve(void 0);const{body:r}=await t(e);return _c(r,t)};return{data:e.data,self:async()=>{const{self:t}=e.links;return r(t)},nextPage:async()=>{const{next:t}=e.links;return r(t)},prevPage:async()=>{const{prev:t}=e.links;return r(t)},firstPage:async()=>{const{first:t}=e.links;return r(t)},hasNext:Boolean(e.links.next),hasPrev:Boolean(e.links.prev)}}class wc{options;httpClient;constructor(e){this.options=e,this.httpClient=vc({baseUrl:`https://${this.httpHost}`,headers:{Authorization:`Bearer ${this.options.token}`},maxApiRequestRetries:this.options.maxApiRequestRetries,apiRequestRetriesDelay:this.options.apiRequestRetriesDelay,apiRequestRetriesDelayIncrement:this.options.apiRequestRetriesDelayIncrement})}get fetch(){return this.httpClient}get httpHost(){let e={};try{e=xa(this.options.token,{header:!0})}catch(e){}const t=this.options.host||e?.ch;return t?`fabric.${t.split(".").splice(1).join(".")}`:"fabric.signalwire.com"}async getAddress(e){let t="/api/fabric/addresses";var r;(r=e)&&"name"in r?t=`${t}?name=${e.name}`:(e=>e&&"id"in e)(e)&&(t=`${t}/${e.id}`);const{body:i}=await this.httpClient(t);if((e=>e&&"data"in e)(i)){if(!i.data[0])throw new Ti(404,"Not Found");return i.data[0]}return i}async getAddresses(e){const{type:t,displayName:r,pageSize:i,sortBy:o,sortOrder:n}=e||{},s=new URLSearchParams;t&&s.append("type",t),r&&s.append("display_name",r),i&&s.append("page_size",i.toString()),o&&s.append("sort_by",o),n&&s.append("sort_order",n);const a=function(e,t){const r=t.toString();return r?`${e}?${r}`:e}("/api/fabric/addresses",s);Zt().debug(`[getAddresses] query URL ${a}`);const{body:c}=await this.httpClient(a);return _c(c,this.httpClient)}async registerDevice(e){const{deviceType:t,deviceToken:r}=e,{body:i}=await this.httpClient("/subscriber/devices",{method:"POST",body:{device_type:t,device_token:r}});return i}async unregisterDevice(e){const{id:t}=e,r=`/subscriber/devices/${t}`;await this.httpClient(r,{method:"DELETE"})}async getSubscriberInfo(){const{body:e}=await this.httpClient("/api/fabric/subscriber/info");return e}}class kc{options;_client;_pendingInvites={};_handlers={};constructor(e){this.options=e,this._client=e.client}_buildNotification(e){const t=async t=>new Promise(((r,i)=>{delete this._pendingInvites[e.callID];try{const i=this.options.buildInboundCall(e,t);i.answer(),r(i)}catch(e){i(e)}})),r=()=>(delete this._pendingInvites[e.callID],this.options.executeVertoBye(e.callID,e.nodeId));return{invite:{details:e,accept:e=>t(e),reject:()=>r()}}}setNotificationHandlers(e){this._handlers.all=e.all,(e.pushNotification&&this._handlers.all!=e.pushNotification||!e.pushNotification)&&(this._handlers.pushNotification=e.pushNotification),(e.websocket&&this._handlers.all!=e.websocket||!e.websocket)&&(this._handlers.websocket=e.websocket)}handleIncomingInvite(e){if(e.callID in this._pendingInvites)return void this._client.logger.debug(`skiping nottification for pending invite to callID: ${e.callID}`);if(this._pendingInvites[e.callID]=e,!this._handlers.all&&!this._handlers[e.source])return void this._client.logger.warn("Skiping nottification due to no listeners");const t=this._buildNotification(e);this._handlers.all?.(t);const r=this._handlers[e.source];r?.(t)}}class Sc extends lc{options;connectVersion=Er;constructor(e){super(e),this.options=e}get signature(){if(this._rpcConnectResult){const{authorization:e}=this._rpcConnectResult;return e.jti}}async _checkTokenExpiration(){}async reauthenticate(){if(this.logger.debug("Session Reauthenticate",{ready:this.ready,expired:this.expired}),!this.ready||this.expired)return this.connect();const e={project:this._rpcConnectResult.authorization.project_id,jwt_token:this.options.token};try{const t=await this.execute(Mr(e));this._rpcConnectResult={...this._rpcConnectResult,...t}}catch(e){throw e}}async execute(e){return pr({asyncCallable:async()=>(await this._waitConnected(),super.execute(e)),maxRetries:this.options.maxApiRequestRetries,delayFn:hr({initialDelay:this.options.apiRequestRetriesDelay,variation:this.options.apiRequestRetriesDelayIncrement}),expectedErrorHandler:t=>(Zt().warn(t),!!Sr(e)||!(!(e=>{var t;return wr(e)&&"webrtc.verto"==e.method&&"verto.invite"===(null==(t=e.params)?void 0:t.message.method)})(e)||[Bt,Ft].includes(t))&&(Zt().debug("skip verto.invite retry on error:",t),!0))})}}class Cc extends Ki{wsClientOptions;_incomingCallManager;_disconnected=!1;constructor(e){super((e=>{const t=zi({userOptions:e,SessionConstructor:Sc});return{...e,store:t}})(e)),this.wsClientOptions=e,this._incomingCallManager=new kc({client:this,buildInboundCall:this.buildInboundCall.bind(this),executeVertoBye:this.executeVertoBye.bind(this)}),this.runWorker("wsClientWorker",{worker:Da,initialState:{handleIncomingInvite:e=>{this._incomingCallManager.handleIncomingInvite({source:"websocket",...e})}}}),this.initializeSessionConnectionPool()}makeFabricObject(e){const{rootElement:t,applyLocalVideoOverlay:r=!0,applyMemberOverlay:i=!0,stopCameraWhileMuted:o=!0,stopMicrophoneWhileMuted:n=!0,mirrorLocalVideoOverlay:s=!0,...a}=e,c=(e=>{const t=$i({store:e.store,Component:Xa})(e);return new Proxy(t,{get(e,t,r){if("string"==typeof t&&t in Qa){const r=e,i=r[t];if("function"==typeof i)return async function(...e){const o=Qa[t];return o&&o.apply(r,e),i.apply(r,e)}}return Reflect.get(e,t,r)}})})({...a,store:this.store});if(t)try{sc({applyLocalVideoOverlay:r,applyMemberOverlay:i,mirrorLocalVideoOverlay:s,room:c,rootElement:t})}catch(e){this.logger.error("Unable to build the video element automatically")}return c.on("room.subscribed",(e=>{const t=e.room_session.members?.find((e=>e.member_id===c.memberId));if(t?.audio_muted)try{c.stopOutboundAudio()}catch(e){this.logger.error("Error handling audio_muted",e)}if(t?.video_muted)try{c.stopOutboundVideo()}catch(e){this.logger.error("Error handling video_muted",e)}})),n&&c.on("member.updated.audioMuted",(({member:e})=>{try{e.member_id===c.memberId&&"audio_muted"in e&&(e.audio_muted?c.stopOutboundAudio():c.restoreOutboundAudio())}catch(e){this.logger.error("Error handling audio_muted",e)}})),o&&c.on("member.updated.videoMuted",(({member:e})=>{try{e.member_id===c.memberId&&"video_muted"in e&&(e.video_muted?c.stopOutboundVideo():c.restoreOutboundVideo())}catch(e){this.logger.error("Error handling video_muted",e)}})),c}buildOutboundCall(e){let t=!1,r=!1;if(e.to){const[i,o]=e.to.split("?");if(!i)throw new Error("Invalid destination address");"video"===new URLSearchParams(o).get("channel")&&(t=!0,r=!0)}const i=this.makeFabricObject({audio:e.audio??!0,video:e.video??t,negotiateAudio:e.negotiateAudio??!0,negotiateVideo:e.negotiateVideo??r,rootElement:e.rootElement||this.wsClientOptions.rootElement,applyLocalVideoOverlay:e.applyLocalVideoOverlay,applyMemberOverlay:e.applyMemberOverlay,stopCameraWhileMuted:e.stopCameraWhileMuted,stopMicrophoneWhileMuted:e.stopMicrophoneWhileMuted,mirrorLocalVideoOverlay:e.mirrorLocalVideoOverlay,watchMediaPackets:!1,destinationNumber:e.to??"",nodeId:e.nodeId,attach:e.attach??!1,disableUdpIceServers:e.disableUdpIceServers||!1,userVariables:e.userVariables||this.wsClientOptions.userVariables,fromFabricAddressId:e.fromFabricAddressId});return i.once("destroy",(()=>{this.logger.debug("RTC Connection Destroyed"),i.destroy()})),this.session.once("session.disconnected",(()=>{this.logger.debug("Session Disconnected"),i.destroy(),this.destroy()})),i.attachPreConnectWorkers(),i}buildInboundCall(e,t){const r=this.makeFabricObject({audio:t.audio??!0,video:t.video??!0,negotiateAudio:t.negotiateAudio??!0,negotiateVideo:t.negotiateVideo??!0,rootElement:t.rootElement||this.wsClientOptions.rootElement,applyLocalVideoOverlay:!0,applyMemberOverlay:!0,stopCameraWhileMuted:!0,stopMicrophoneWhileMuted:!0,watchMediaPackets:!1,nodeId:e.nodeId,remoteSdp:e.sdp,prevCallId:e.callID,disableUdpIceServers:t.disableUdpIceServers||!1,userVariables:t.userVariables||this.wsClientOptions.userVariables});return r.once("destroy",(()=>{this.logger.debug("RTC Connection Destroyed"),r.destroy()})),this.session.once("session.disconnected",(()=>{this.logger.debug("Session Disconnected"),r.destroy(),this.destroy()})),r.attachPreConnectWorkers(),r}async executeVertoBye(e,t){try{return await this.execute({method:"webrtc.verto",params:{callID:e,node_id:t,message:Lr({cause:"USER_BUSY",causeCode:"17",dialogParams:{callID:e}})}})}catch(t){throw this.logger.warn("The call is not available anymore",e),t}}async executeVertoSubscribe(e,t){try{return await this.execute({method:"webrtc.verto",params:{callID:e,node_id:t,subscribe:[],message:Vr({sessid:e,eventChannel:[]})}})}catch(t){throw this.logger.warn("The call is not available anymore",e),t}}disconnect(){return new Promise(((e,t)=>{this._disconnected&&e(),this.session.once("session.disconnected",(()=>{this.destroy(),e(),this._disconnected=!0})),super.disconnect()}))}async dial(e){return new Promise((async(t,r)=>{try{Oa()?.removeItem(ja),t(this.buildOutboundCall(e))}catch(e){this.logger.error("Unable to connect and dial a call",e),r(e)}}))}async reattach(e){return new Promise((async(t,r)=>{try{t(this.buildOutboundCall({...e,attach:!0}))}catch(e){this.logger.error("Unable to connect and reattach a call",e),r(e)}}))}handlePushNotification(e){const{incomingCallHandler:t}=e;return this._incomingCallManager.setNotificationHandlers({pushNotification:t}),new Promise((async(t,r)=>{const{decrypted:i,type:o}=e;"call_invite"!==o&&(this.logger.warn("Unknown notification type",e),r("Unknown notification type")),this.logger.debug("handlePushNotification",e);const{params:{params:n},node_id:s}=i;try{try{await this.executeVertoSubscribe(n.callID,s)}catch(e){this.logger.warn("Verto Subscribe",e)}this._incomingCallManager.handleIncomingInvite({source:"pushNotification",nodeId:s,...n}),t({resultType:"inboundCall"})}catch(e){r(e)}}))}updateToken(e){return new Promise(((t,r)=>{this.session.once("session.auth_error",(e=>{r(e)})),this.session.once("session.connected",(()=>{t()})),this.store.dispatch(Ur.reauthAction({token:e}))}))}async online({incomingCallHandlers:e}){return(e.all||e.pushNotification)&&this.logger.warn("Make sure the device is not registered to receive Push Notifications while it is online"),this._incomingCallManager.setNotificationHandlers(e),this.execute({method:"subscriber.online",params:{}})}offline(){return this._incomingCallManager.setNotificationHandlers({}),this.execute({method:"subscriber.offline",params:{}})}initializeSessionConnectionPool(){this.runWorker("sessionConnectionPoolWorker",{worker:Ks,initialState:{poolSize:1,iceCandidatePoolSize:10}})}}const Ic=(()=>{let e=null;return t=>(e||(e=new Promise((async(r,i)=>{try{const i={maxApiRequestRetries:10,apiRequestRetriesDelay:300,apiRequestRetriesDelayIncrement:100,...t},o=new Cc(i),n=new wc(i),s=e=>()=>{throw new Error(`This version Conversation.${e} is unsupported by the backend. Use @signalwire/client instead.`)};await o.connect(),r({registerDevice:n.registerDevice.bind(n),unregisterDevice:n.unregisterDevice.bind(n),getSubscriberInfo:n.getSubscriberInfo.bind(n),disconnect:async()=>{await o.disconnect(),e=null},online:o.online.bind(o),offline:o.offline.bind(o),dial:o.dial.bind(o),reattach:o.reattach.bind(o),handlePushNotification:o.handlePushNotification.bind(o),updateToken:o.updateToken.bind(o),address:{getAddresses:n.getAddresses.bind(n),getAddress:n.getAddress.bind(n)},conversation:{getConversations:s("getConversations"),getMessages:s("getMessages"),getConversationMessages:s("getConversationMessages"),subscribe:s("subscribe"),sendMessage:s("sendMessage"),join:s("join")},chat:{getMessages:s("getMessages"),subscribe:s("subscribe"),sendMessage:s("sendMessage"),join:s("join")},on:o.on.bind(o),off:o.off.bind(o),__httpClient:n,__wsClient:o})}catch(e){i(e)}})).catch((t=>{throw e=null,t}))),e)})();var Tc=/*#__PURE__*/Object.freeze({__proto__:null,isFabricRoomSession:Ya,SignalWire:Ic});const Ec={aspectRatio:{ideal:16/9}},Pc=e=>new Promise((async(t,r)=>{const{audio:i=!0,video:o=!0,iceServers:n,rootElementId:s,applyLocalVideoOverlay:a=!0,autoJoin:c=!1,stopCameraWhileMuted:d=!0,stopMicrophoneWhileMuted:l=!0,speakerId:u,...h}=e,m=uc({...h});if(await m.connect(),!m)return;let p;if(s){const e=document.getElementById(s);e?p=e:(p=document.body,Zt().warn(`We couldn't find an element with id: ${s}: using 'document.body' instead.`))}const g=m.rooms.makeRoomObject({audio:i,video:!0===o?Ec:o,negotiateAudio:!0,negotiateVideo:!0,iceServers:n,rootElement:p,applyLocalVideoOverlay:a,stopCameraWhileMuted:d,stopMicrophoneWhileMuted:l,speakerId:u});g.once("destroy",(()=>{g.emit("room.left"),m.disconnect()}));const f=()=>new Promise((async(e,t)=>{try{g.once("room.subscribed",(t=>{e(g)})),await g.join()}catch(e){Zt().error("Join",e),m.disconnect(),t(e)}})),v=new Proxy(g,{get:(e,t,r)=>"join"===t?f:Reflect.get(e,t,r)});if(c)try{await v.join(),t(v)}catch(e){r(e)}else t(v)})),Mc=["audioMute","audioUnmute","deaf","getLayouts","getMembers","getRecordings","hideVideoMuted","leave","removerMember","restoreOutboundAudio","restoreOutboundVideo","setInputSensitivity","setInputVolume","setLayout","setPositions","setMemberPosition","setOutputVolume","showVideoMuted","startRecording","stopOutboundAudio","stopOutboundVideo","undeaf","videoMute","videoUnmute","setMicrophoneVolume","setSpeakerVolume","getMeta","setMeta","updateMeta","deleteMeta","getMemberMeta","setMemberMeta","updateMemberMeta","deleteMemberMeta","promote","demote","lock","unlock"],Rc=["member.joined","layout.changed"],Ac=()=>{};var xc=/*#__PURE__*/Object.freeze({__proto__:null,RoomSession:function(e){const{audio:t=!0,video:r=!0,iceServers:i,rootElement:o,applyLocalVideoOverlay:n=!0,mirrorLocalVideoOverlay:s=!1,stopCameraWhileMuted:a=!0,stopMicrophoneWhileMuted:c=!0,speakerId:d,destinationNumber:l,localStream:u,watchMediaPackets:h,watchMediaPacketsTimeout:m,disableUdpIceServers:p=!1,...g}=e;["audio","video"].forEach((t=>{t in e&&Zt().warn(`The '${t}' parameter on the RoomSession constructor is deprecated. Set it on the '.join()' function instead.`)}));const f=!1!==e?.reattach,{callIdKey:v}=La(g.token),y={joined:({call_id:e})=>{f&&v&&Oa()?.setItem(v,e)},init:()=>{f&&_.on("room.subscribed",y.joined),_.options.prevCallId=y.getPrevCallId()},destroy:()=>{f&&(_.off("room.subscribed",y.joined),v&&Oa()?.removeItem(v))},getPrevCallId:()=>{if(f&&v)return Oa()?.getItem(v)??void 0}},b=uc(g),_=b.rooms.makeRoomObject({negotiateAudio:!0,negotiateVideo:!0,iceServers:i,rootElement:o,applyLocalVideoOverlay:n,mirrorLocalVideoOverlay:s,stopCameraWhileMuted:a,stopMicrophoneWhileMuted:c,speakerId:d,destinationNumber:l,localStream:u,watchMediaPackets:h,watchMediaPacketsTimeout:m,prevCallId:y.getPrevCallId(),disableUdpIceServers:p});_.once("destroy",(()=>{_.emit("room.left",{reason:_.leaveReason}),y.destroy(),b.disconnect()})),b.session.once("session.disconnected",(()=>{_.destroy()}));const w={join:e=>new Promise((async(i,o)=>{try{_.attachPreConnectWorkers(),await b.connect();const n=e?.audio??t,s=e?.video??r,a=b._sessionAuthorization;if(Zt().debug("getJoinMediaParams authorization?",a),a&&"video"===a.type){const t=(e=>{const{authorization:t,audio:r=!0,video:i=!0,sendAudio:o,sendVideo:n,receiveAudio:s,receiveVideo:a}=e;Zt().debug("getJoinMediaParams options",{...e});const{audio_allowed:c,video_allowed:d,join_as:l}=t,u="member"===(l??"member"),h=u&&"both"===c,m=u&&"both"===d,p="none"!==c,g="none"!==d,f=Boolean(o??r),v=Boolean(n??i),y=Boolean(s??r),b=Boolean(a??i);return!h&&f&&Zt().info("Not allowed to send audio on this room. Default values will be used."),!m&&v&&Zt().info("Not allowed to send video on this room. Default values will be used."),!p&&y&&Zt().info("Not allowed to receive video from the room. Default values will be used."),!g&&b&&Zt().info("Not allowed to receive video from the room. Default values will be used."),{mustSendAudio:h&&f,mustSendVideo:m&&v,mustRecvAudio:p&&y,mustRecvVideo:g&&b}})({authorization:a,sendAudio:Boolean(n),sendVideo:Boolean(s),...e});if(!Object.values(t).some(Boolean))return b.disconnect(),o(new Error(`Invalid arguments to join the room. The token used has join_as: '${a.join_as}'. \n${JSON.stringify(e,null,2)}\n`));Zt().debug("Set mediaOptions",t),_.updateMediaOptions({audio:!!t.mustSendAudio&&(n||!0),video:!!t.mustSendVideo&&(s||!0),negotiateAudio:t.mustRecvAudio,negotiateVideo:t.mustRecvVideo})}_.once("room.subscribed",(()=>{i(_)})),y.init(),Rc.forEach((e=>_.once(e,Ac))),await _.join()}catch(e){Zt().error("RoomSession Join",e),b.disconnect(),o(e)}}))};return new Proxy(_,{get(e,t,r){if(t in w)return w[t];if(!e.active&&Mc.includes(t))throw new Error(`Tried to access the property/method "${t}" before the room was connected. Please call roomSession.join() first.`);return Reflect.get(e,t,r)}})},createRoomObject:Pc,joinRoom:e=>Pc({...e,autoJoin:!0}),createClient:uc,isVideoRoomSession:Ea}),Oc=/*#__PURE__*/Object.freeze({__proto__:null,getDevices:ws,getCameraDevices:()=>ws("camera"),getMicrophoneDevices:()=>ws("microphone"),getSpeakerDevices:ks,getDevicesWithPermissions:bs,getCameraDevicesWithPermissions:()=>bs("camera"),getMicrophoneDevicesWithPermissions:()=>bs("microphone"),getSpeakerDevicesWithPermissions:()=>bs("speaker"),checkPermissions:ns,checkCameraPermissions:ss,checkMicrophonePermissions:as,checkSpeakerPermissions:cs,requestPermissions:async e=>{try{const t=await ds(e);Zn(t)}catch(e){throw e}},createDeviceWatcher:Ms,createCameraDeviceWatcher:()=>Ms({targets:["camera"]}),createMicrophoneDeviceWatcher:()=>Ms({targets:["microphone"]}),createSpeakerDeviceWatcher:Rs,supportsMediaDevices:Kn,supportsGetUserMedia:()=>"function"==typeof Gn().getUserMedia,supportsGetDisplayMedia:()=>"function"==typeof Gn().getDisplayMedia,getUserMedia:ds,getDisplayMedia:ls,enumerateDevices:is,enumerateDevicesByKind:os,getSupportedConstraints:Jn,supportsMediaOutput:Xn,setMediaElementSinkId:Yn,stopStream:Zn,stopTrack:es,createMicrophoneAnalyzer:async e=>{const t=await(async e=>{if(As(e))return e;let t;return t="string"==typeof e?{audio:{deviceId:e}}:{audio:e},ds(t)})(e);if(!t)throw new Error("Failed to get the audio stream");const r=new St,i=new(window.AudioContext||window.webkitAudioContext),o=(e=>{const t=e.createAnalyser();return t.fftSize=64,t.minDecibels=-90,t.maxDecibels=-10,t.smoothingTimeConstant=.85,t})(i);let n,s;try{i.createMediaStreamSource(t).connect(o)}catch(e){throw new Error("No audio track found")}t.getAudioTracks().forEach((e=>{e.addEventListener("ended",(()=>{r.emit("destroyed","disconnected")}))}));const a=()=>{try{const e=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(e);const t=e.reduce(((e,t)=>e+t),0)/20;s!==t&&(s=t,r.emit("volumeChanged",Math.min(s,100))),n=requestAnimationFrame(a)}catch(e){r.emit("destroyed","error")}};n=requestAnimationFrame(a);const c=()=>{n&&cancelAnimationFrame(n),"closed"!==i.state&&i.close().catch((e=>{Zt().error("Error closing the AudioContext",e)})),As(e)||t.getTracks().forEach((e=>e.stop())),r.emit("destroyed",null),r.removeAllListeners()};return new Proxy(r,{get:(e,t,r)=>"destroy"===t?c:Reflect.get(e,t,r)})}});e.Chat=mc,e.Fabric=Tc,e.LocalVideoOverlay=ec,e.PubSub=gc,e.SignalWire=Ic,e.UserOverlay=Za,e.Video=xc,e.WebRTC=Oc,e.buildVideoElement=sc,e.isFabricRoomSession=Ya,Object.defineProperty(e,"__esModule",{value:!0})}));
31
31
  //# sourceMappingURL=index.umd.js.map