@hysc/meeting 10.0.9 → 10.0.10

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 (94) hide show
  1. package/dist/index.d.mts +8 -7
  2. package/dist/index.d.ts +8 -7
  3. package/dist/index.js +3 -3
  4. package/dist/index.mjs +3 -3
  5. package/package.json +8 -8
  6. package/umd/boom-core/src/BoomCore/BCClient/clientEventType.d.ts +428 -0
  7. package/umd/boom-meeting/src/BMChat/BMChatVM.d.ts +26 -0
  8. package/umd/boom-meeting/src/BMChat/BMMessageInfo.d.ts +31 -0
  9. package/umd/boom-meeting/src/BMRoom/BMLiveVM.d.ts +35 -0
  10. package/umd/boom-meeting/src/BMRoom/BMRoomInfo.d.ts +215 -0
  11. package/umd/boom-meeting/src/BMRoom/BMRoomVM.d.ts +317 -0
  12. package/umd/boom-meeting/src/BMRoom/RoomEvent.d.ts +1 -0
  13. package/umd/boom-meeting/src/BMStream/BMSpeaker.d.ts +26 -0
  14. package/umd/boom-meeting/src/BMStream/BMStreamModel.d.ts +306 -0
  15. package/umd/boom-meeting/src/BMStream/BMStreamModelVM.d.ts +260 -0
  16. package/umd/boom-meeting/src/BMStream/getHTMLMediaStreamOptions.d.ts +35 -0
  17. package/umd/boom-meeting/src/BMStream/sortStream.d.ts +30 -0
  18. package/umd/boom-meeting/src/BMUser/BMUser.d.ts +156 -0
  19. package/umd/boom-meeting/src/BMUser/BMUserVM.d.ts +177 -0
  20. package/umd/boom-meeting/src/SingletonQueue/SingletonQueue.d.ts +26 -0
  21. package/umd/boom-meeting/src/audioPlay/AudioPlay.d.ts +31 -0
  22. package/umd/boom-meeting/src/bjy-common/function/debounce.d.ts +9 -0
  23. package/umd/boom-meeting/src/bjy-common/function/execute.d.ts +9 -0
  24. package/umd/boom-meeting/src/bjy-common/function/getErrorMessage.d.ts +1 -0
  25. package/umd/boom-meeting/src/bjy-common/function/isDef.d.ts +1 -0
  26. package/umd/boom-meeting/src/bjy-common/function/isNative.d.ts +1 -0
  27. package/umd/boom-meeting/src/bjy-common/function/isUndef.d.ts +1 -0
  28. package/umd/boom-meeting/src/bjy-common/function/nextTick.d.ts +2 -0
  29. package/umd/boom-meeting/src/bjy-common/function/throttling.d.ts +9 -0
  30. package/umd/boom-meeting/src/bjy-common/function/toNumber.d.ts +1 -0
  31. package/umd/boom-meeting/src/bjy-common/function/toString.d.ts +1 -0
  32. package/umd/boom-meeting/src/bjy-common/type/api.d.ts +66 -0
  33. package/umd/boom-meeting/src/bjy-common/type/options.d.ts +7 -0
  34. package/umd/boom-meeting/src/bjy-common/type/type.d.ts +90 -0
  35. package/umd/boom-meeting/src/bjy-common/util/CustomEvent.d.ts +30 -0
  36. package/umd/boom-meeting/src/bjy-common/util/Emitter.d.ts +57 -0
  37. package/umd/boom-meeting/src/bjy-common/util/NextTask.d.ts +28 -0
  38. package/umd/boom-meeting/src/bjy-common/util/Sleep.d.ts +14 -0
  39. package/umd/boom-meeting/src/bjy-common/util/Timer.d.ts +13 -0
  40. package/umd/boom-meeting/src/bjy-common/util/array.d.ts +96 -0
  41. package/umd/boom-meeting/src/bjy-common/util/browser.d.ts +6 -0
  42. package/umd/boom-meeting/src/bjy-common/util/constant.d.ts +50 -0
  43. package/umd/boom-meeting/src/bjy-common/util/holder.d.ts +6 -0
  44. package/umd/boom-meeting/src/bjy-common/util/is.d.ts +49 -0
  45. package/umd/boom-meeting/src/bjy-common/util/keypath.d.ts +41 -0
  46. package/umd/boom-meeting/src/bjy-common/util/logger.d.ts +42 -0
  47. package/umd/boom-meeting/src/bjy-common/util/network.d.ts +4 -0
  48. package/umd/boom-meeting/src/bjy-common/util/object.d.ts +83 -0
  49. package/umd/boom-meeting/src/bjy-common/util/os.d.ts +14 -0
  50. package/umd/boom-meeting/src/bjy-common/util/string.d.ts +102 -0
  51. package/umd/boom-meeting/src/constants.d.ts +129 -0
  52. package/umd/boom-meeting/src/error/RTCError.d.ts +20 -0
  53. package/umd/boom-meeting/src/error/errorMap.d.ts +70 -0
  54. package/umd/boom-meeting/src/error/errorType.d.ts +96 -0
  55. package/umd/boom-meeting/src/handleEvent/attachEvents.d.ts +48 -0
  56. package/umd/boom-meeting/src/handleEvent/brtcNetEvent.d.ts +9 -0
  57. package/umd/boom-meeting/src/handleEvent/customMessageEvent.d.ts +2 -0
  58. package/umd/boom-meeting/src/handleEvent/handleParticipantEvent.d.ts +24 -0
  59. package/umd/boom-meeting/src/handleEvent/handleRoomEvent.d.ts +20 -0
  60. package/umd/boom-meeting/src/handleEvent/messageEvent.d.ts +5 -0
  61. package/umd/boom-meeting/src/handleEvent/pullUser.d.ts +7 -0
  62. package/umd/boom-meeting/src/handleEvent/roomErrEvent.d.ts +9 -0
  63. package/umd/boom-meeting/src/handleEvent/streamEvent.d.ts +22 -0
  64. package/umd/boom-meeting/src/logger/logger.d.ts +86 -0
  65. package/umd/boom-meeting/src/type/customStats.d.ts +123 -0
  66. package/umd/boom-meeting/src/type/index.d.ts +9 -0
  67. package/umd/boom-meeting/src/type/stream.d.ts +15 -0
  68. package/umd/boom-meeting/src/type/user.d.ts +9 -0
  69. package/umd/boom-meeting/src/util/PackLoss.d.ts +7 -0
  70. package/umd/boom-meeting/src/util/Pqueue.d.ts +62 -0
  71. package/umd/boom-meeting/src/util/Privileges.d.ts +20 -0
  72. package/umd/boom-meeting/src/util/ReportCollector.d.ts +22 -0
  73. package/umd/boom-meeting/src/util/Stutter.d.ts +19 -0
  74. package/umd/boom-meeting/src/util/Thread.d.ts +12 -0
  75. package/umd/boom-meeting/src/util/base64.d.ts +4 -0
  76. package/umd/boom-meeting/src/util/benchmark.d.ts +1 -0
  77. package/umd/boom-meeting/src/util/checkPermissions.d.ts +1 -0
  78. package/umd/boom-meeting/src/util/checkSystemRequirements.d.ts +1 -0
  79. package/umd/boom-meeting/src/util/constant.d.ts +67 -0
  80. package/umd/boom-meeting/src/util/devices.d.ts +2 -0
  81. package/umd/boom-meeting/src/util/emitter.d.ts +43 -0
  82. package/umd/boom-meeting/src/util/formatUserId.d.ts +2 -0
  83. package/umd/boom-meeting/src/util/is.d.ts +70 -0
  84. package/umd/boom-meeting/src/util/peerToPeerProbe.d.ts +9 -0
  85. package/umd/boom-meeting/src/util/request.d.ts +45 -0
  86. package/umd/boom-meeting/src/util/roomUtils.d.ts +9 -0
  87. package/umd/boom-meeting/src/util/sortUtils.d.ts +10 -0
  88. package/umd/boom-meeting/src/util/util.d.ts +78 -0
  89. package/umd/index.js +24 -20
  90. package/umd/src/BMRoom/BMRoom.d.ts +6 -6
  91. package/umd/src/BMStream/BMStreamModel.d.ts +2 -1
  92. package/umd/utils/BoomError.d.ts +19 -0
  93. package/umd/utils/ErrorTypes.d.ts +139 -0
  94. package/umd/utils/index.d.ts +9 -0
package/umd/index.js CHANGED
@@ -1,25 +1,29 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@hysc/utils"),require("events")):"function"==typeof define&&define.amd?define(["exports","@hysc/utils","events"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BoomMeeting={},e.require$$0,e.require$$5)}(this,(function(exports,require$$0,require$$5){"use strict";function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var require$$0__default=_interopDefaultLegacy(require$$0),require$$5__default=_interopDefaultLegacy(require$$5),extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function __awaiter(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}function __values(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return o}function __spreadArray(e,t,r){if(r||2===arguments.length)for(var i,n=0,s=t.length;n<s;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getAugmentedNamespace(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})})),t}var dist$2={exports:{}},global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeGlobal$1=freeGlobal,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal$1||freeSelf||Function("return this")(),root$1=root,Symbol$1=root$1.Symbol,Symbol$2=Symbol$1,objectProto$s=Object.prototype,hasOwnProperty$o=objectProto$s.hasOwnProperty,nativeObjectToString$3=objectProto$s.toString,symToStringTag$1=Symbol$2?Symbol$2.toStringTag:void 0;function getRawTag(e){var t=hasOwnProperty$o.call(e,symToStringTag$1),r=e[symToStringTag$1];try{e[symToStringTag$1]=void 0;var i=!0}catch(e){}var n=nativeObjectToString$3.call(e);return i&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),n}var objectProto$r=Object.prototype,nativeObjectToString$2=objectProto$r.toString;function objectToString(e){return nativeObjectToString$2.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$2?Symbol$2.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}var symbolTag$3="[object Symbol]";function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag$3}var NAN$2=NaN;function baseToNumber(e){return"number"==typeof e?e:isSymbol(e)?NAN$2:+e}function arrayMap(e,t){for(var r=-1,i=null==e?0:e.length,n=Array(i);++r<i;)n[r]=t(e[r],r,e);return n}var isArray=Array.isArray,isArray$1=isArray,INFINITY$5=1/0,symbolProto$2=Symbol$2?Symbol$2.prototype:void 0,symbolToString=symbolProto$2?symbolProto$2.toString:void 0;function baseToString(e){if("string"==typeof e)return e;if(isArray$1(e))return arrayMap(e,baseToString)+"";if(isSymbol(e))return symbolToString?symbolToString.call(e):"";var t=e+"";return"0"==t&&1/e==-INFINITY$5?"-0":t}function createMathOperation(e,t){return function(r,i){var n;if(void 0===r&&void 0===i)return t;if(void 0!==r&&(n=r),void 0!==i){if(void 0===n)return i;"string"==typeof r||"string"==typeof i?(r=baseToString(r),i=baseToString(i)):(r=baseToNumber(r),i=baseToNumber(i)),n=e(r,i)}return n}}var add=createMathOperation((function(e,t){return e+t}),0),add$1=add,reWhitespace=/\s/;function trimmedEndIndex(e){for(var t=e.length;t--&&reWhitespace.test(e.charAt(t)););return t}var reTrimStart$2=/^\s+/;function baseTrim(e){return e?e.slice(0,trimmedEndIndex(e)+1).replace(reTrimStart$2,""):e}function isObject(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var NAN$1=NaN,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt;function toNumber(e){if("number"==typeof e)return e;if(isSymbol(e))return NAN$1;if(isObject(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=isObject(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=baseTrim(e);var r=reIsBinary.test(e);return r||reIsOctal.test(e)?freeParseInt(e.slice(2),r?2:8):reIsBadHex.test(e)?NAN$1:+e}var INFINITY$4=1/0,MAX_INTEGER=17976931348623157e292;function toFinite(e){return e?(e=toNumber(e))===INFINITY$4||e===-INFINITY$4?(e<0?-1:1)*MAX_INTEGER:e==e?e:0:0===e?e:0}function toInteger(e){var t=toFinite(e),r=t%1;return t==t?r?t-r:t:0}var FUNC_ERROR_TEXT$b="Expected a function";function after(e,t){if("function"!=typeof t)throw new TypeError(FUNC_ERROR_TEXT$b);return e=toInteger(e),function(){if(--e<1)return t.apply(this,arguments)}}function identity$1(e){return e}var asyncTag="[object AsyncFunction]",funcTag$2="[object Function]",genTag$1="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction$1(e){if(!isObject(e))return!1;var t=baseGetTag(e);return t==funcTag$2||t==genTag$1||t==asyncTag||t==proxyTag}var coreJsData=root$1["__core-js_shared__"],coreJsData$1=coreJsData,maskSrcKey=(uid=/[^.]+$/.exec(coreJsData$1&&coreJsData$1.keys&&coreJsData$1.keys.IE_PROTO||""),uid?"Symbol(src)_1."+uid:""),uid;function isMasked(e){return!!maskSrcKey&&maskSrcKey in e}var funcProto$2=Function.prototype,funcToString$2=funcProto$2.toString;function toSource(e){if(null!=e){try{return funcToString$2.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var reRegExpChar$1=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,funcProto$1=Function.prototype,objectProto$q=Object.prototype,funcToString$1=funcProto$1.toString,hasOwnProperty$n=objectProto$q.hasOwnProperty,reIsNative=RegExp("^"+funcToString$1.call(hasOwnProperty$n).replace(reRegExpChar$1,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function baseIsNative(e){return!(!isObject(e)||isMasked(e))&&(isFunction$1(e)?reIsNative:reIsHostCtor).test(toSource(e))}function getValue(e,t){return null==e?void 0:e[t]}function getNative(e,t){var r=getValue(e,t);return baseIsNative(r)?r:void 0}var WeakMap=getNative(root$1,"WeakMap"),WeakMap$1=WeakMap,metaMap=WeakMap$1&&new WeakMap$1,metaMap$1=metaMap,baseSetData=metaMap$1?function(e,t){return metaMap$1.set(e,t),e}:identity$1,baseSetData$1=baseSetData,objectCreate=Object.create,baseCreate=function(){function e(){}return function(t){if(!isObject(t))return{};if(objectCreate)return objectCreate(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}(),baseCreate$1=baseCreate;function createCtor(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=baseCreate$1(e.prototype),i=e.apply(r,t);return isObject(i)?i:r}}var WRAP_BIND_FLAG$8=1;function createBind(e,t,r){var i=t&WRAP_BIND_FLAG$8,n=createCtor(e);return function t(){var s=this&&this!==root$1&&this instanceof t?n:e;return s.apply(i?r:this,arguments)}}function apply(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var nativeMax$g=Math.max;function composeArgs(e,t,r,i){for(var n=-1,s=e.length,o=r.length,a=-1,c=t.length,u=nativeMax$g(s-o,0),d=Array(c+u),l=!i;++a<c;)d[a]=t[a];for(;++n<o;)(l||n<s)&&(d[r[n]]=e[n]);for(;u--;)d[a++]=e[n++];return d}var nativeMax$f=Math.max;function composeArgsRight(e,t,r,i){for(var n=-1,s=e.length,o=-1,a=r.length,c=-1,u=t.length,d=nativeMax$f(s-a,0),l=Array(d+u),h=!i;++n<d;)l[n]=e[n];for(var p=n;++c<u;)l[p+c]=t[c];for(;++o<a;)(h||n<s)&&(l[p+r[o]]=e[n++]);return l}function countHolders(e,t){for(var r=e.length,i=0;r--;)e[r]===t&&++i;return i}function baseLodash(){}var MAX_ARRAY_LENGTH$6=4294967295;function LazyWrapper(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=MAX_ARRAY_LENGTH$6,this.__views__=[]}function noop$2(){}LazyWrapper.prototype=baseCreate$1(baseLodash.prototype),LazyWrapper.prototype.constructor=LazyWrapper;var getData=metaMap$1?function(e){return metaMap$1.get(e)}:noop$2,getData$1=getData,realNames={},realNames$1=realNames,objectProto$p=Object.prototype,hasOwnProperty$m=objectProto$p.hasOwnProperty;function getFuncName(e){for(var t=e.name+"",r=realNames$1[t],i=hasOwnProperty$m.call(realNames$1,t)?r.length:0;i--;){var n=r[i],s=n.func;if(null==s||s==e)return n.name}return t}function LodashWrapper(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}function copyArray(e,t){var r=-1,i=e.length;for(t||(t=Array(i));++r<i;)t[r]=e[r];return t}function wrapperClone(e){if(e instanceof LazyWrapper)return e.clone();var t=new LodashWrapper(e.__wrapped__,e.__chain__);return t.__actions__=copyArray(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}LodashWrapper.prototype=baseCreate$1(baseLodash.prototype),LodashWrapper.prototype.constructor=LodashWrapper;var objectProto$o=Object.prototype,hasOwnProperty$l=objectProto$o.hasOwnProperty;function lodash$1(e){if(isObjectLike(e)&&!isArray$1(e)&&!(e instanceof LazyWrapper)){if(e instanceof LodashWrapper)return e;if(hasOwnProperty$l.call(e,"__wrapped__"))return wrapperClone(e)}return new LodashWrapper(e)}function isLaziable(e){var t=getFuncName(e),r=lodash$1[t];if("function"!=typeof r||!(t in LazyWrapper.prototype))return!1;if(e===r)return!0;var i=getData$1(r);return!!i&&e===i[0]}lodash$1.prototype=baseLodash.prototype,lodash$1.prototype.constructor=lodash$1;var HOT_COUNT=800,HOT_SPAN=16,nativeNow=Date.now;function shortOut(e){var t=0,r=0;return function(){var i=nativeNow(),n=HOT_SPAN-(i-r);if(r=i,n>0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var setData=shortOut(baseSetData$1),setData$1=setData,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /;function getWrapDetails(e){var t=e.match(reWrapDetails);return t?t[1].split(reSplitDetails):[]}var reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;function insertWrapDetails(e,t){var r=t.length;if(!r)return e;var i=r-1;return t[i]=(r>1?"& ":"")+t[i],t=t.join(r>2?", ":" "),e.replace(reWrapComment,"{\n/* [wrapped with "+t+"] */\n")}function constant(e){return function(){return e}}var defineProperty=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),defineProperty$1=defineProperty,baseSetToString=defineProperty$1?function(e,t){return defineProperty$1(e,"toString",{configurable:!0,enumerable:!1,value:constant(t),writable:!0})}:identity$1,baseSetToString$1=baseSetToString,setToString=shortOut(baseSetToString$1),setToString$1=setToString;function arrayEach(e,t){for(var r=-1,i=null==e?0:e.length;++r<i&&!1!==t(e[r],r,e););return e}function baseFindIndex(e,t,r,i){for(var n=e.length,s=r+(i?1:-1);i?s--:++s<n;)if(t(e[s],s,e))return s;return-1}function baseIsNaN(e){return e!=e}function strictIndexOf(e,t,r){for(var i=r-1,n=e.length;++i<n;)if(e[i]===t)return i;return-1}function baseIndexOf(e,t,r){return t==t?strictIndexOf(e,t,r):baseFindIndex(e,baseIsNaN,r)}function arrayIncludes(e,t){return!!(null==e?0:e.length)&&baseIndexOf(e,t,0)>-1}var WRAP_BIND_FLAG$7=1,WRAP_BIND_KEY_FLAG$6=2,WRAP_CURRY_FLAG$6=8,WRAP_CURRY_RIGHT_FLAG$3=16,WRAP_PARTIAL_FLAG$6=32,WRAP_PARTIAL_RIGHT_FLAG$3=64,WRAP_ARY_FLAG$4=128,WRAP_REARG_FLAG$3=256,WRAP_FLIP_FLAG$2=512,wrapFlags=[["ary",WRAP_ARY_FLAG$4],["bind",WRAP_BIND_FLAG$7],["bindKey",WRAP_BIND_KEY_FLAG$6],["curry",WRAP_CURRY_FLAG$6],["curryRight",WRAP_CURRY_RIGHT_FLAG$3],["flip",WRAP_FLIP_FLAG$2],["partial",WRAP_PARTIAL_FLAG$6],["partialRight",WRAP_PARTIAL_RIGHT_FLAG$3],["rearg",WRAP_REARG_FLAG$3]];function updateWrapDetails(e,t){return arrayEach(wrapFlags,(function(r){var i="_."+r[0];t&r[1]&&!arrayIncludes(e,i)&&e.push(i)})),e.sort()}function setWrapToString(e,t,r){var i=t+"";return setToString$1(e,insertWrapDetails(i,updateWrapDetails(getWrapDetails(i),r)))}var WRAP_BIND_FLAG$6=1,WRAP_BIND_KEY_FLAG$5=2,WRAP_CURRY_BOUND_FLAG$1=4,WRAP_CURRY_FLAG$5=8,WRAP_PARTIAL_FLAG$5=32,WRAP_PARTIAL_RIGHT_FLAG$2=64;function createRecurry(e,t,r,i,n,s,o,a,c,u){var d=t&WRAP_CURRY_FLAG$5;t|=d?WRAP_PARTIAL_FLAG$5:WRAP_PARTIAL_RIGHT_FLAG$2,(t&=~(d?WRAP_PARTIAL_RIGHT_FLAG$2:WRAP_PARTIAL_FLAG$5))&WRAP_CURRY_BOUND_FLAG$1||(t&=~(WRAP_BIND_FLAG$6|WRAP_BIND_KEY_FLAG$5));var l=[e,t,n,d?s:void 0,d?o:void 0,d?void 0:s,d?void 0:o,a,c,u],h=r.apply(void 0,l);return isLaziable(e)&&setData$1(h,l),h.placeholder=i,setWrapToString(h,e,t)}function getHolder(e){return e.placeholder}var MAX_SAFE_INTEGER$5=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/;function isIndex(e,t){var r=typeof e;return!!(t=null==t?MAX_SAFE_INTEGER$5:t)&&("number"==r||"symbol"!=r&&reIsUint.test(e))&&e>-1&&e%1==0&&e<t}var nativeMin$e=Math.min;function reorder(e,t){for(var r=e.length,i=nativeMin$e(t.length,r),n=copyArray(e);i--;){var s=t[i];e[i]=isIndex(s,r)?n[s]:void 0}return e}var PLACEHOLDER$1="__lodash_placeholder__";function replaceHolders(e,t){for(var r=-1,i=e.length,n=0,s=[];++r<i;){var o=e[r];o!==t&&o!==PLACEHOLDER$1||(e[r]=PLACEHOLDER$1,s[n++]=r)}return s}var WRAP_BIND_FLAG$5=1,WRAP_BIND_KEY_FLAG$4=2,WRAP_CURRY_FLAG$4=8,WRAP_CURRY_RIGHT_FLAG$2=16,WRAP_ARY_FLAG$3=128,WRAP_FLIP_FLAG$1=512;function createHybrid(e,t,r,i,n,s,o,a,c,u){var d=t&WRAP_ARY_FLAG$3,l=t&WRAP_BIND_FLAG$5,h=t&WRAP_BIND_KEY_FLAG$4,p=t&(WRAP_CURRY_FLAG$4|WRAP_CURRY_RIGHT_FLAG$2),m=t&WRAP_FLIP_FLAG$1,f=h?void 0:createCtor(e);return function g(){for(var v=arguments.length,y=Array(v),_=v;_--;)y[_]=arguments[_];if(p)var b=getHolder(g),S=countHolders(y,b);if(i&&(y=composeArgs(y,i,n,p)),s&&(y=composeArgsRight(y,s,o,p)),v-=S,p&&v<u){var I=replaceHolders(y,b);return createRecurry(e,t,createHybrid,g.placeholder,r,y,I,a,c,u-v)}var E=l?r:this,T=h?E[e]:e;return v=y.length,a?y=reorder(y,a):m&&v>1&&y.reverse(),d&&c<v&&(y.length=c),this&&this!==root$1&&this instanceof g&&(T=f||createCtor(T)),T.apply(E,y)}}function createCurry(e,t,r){var i=createCtor(e);return function n(){for(var s=arguments.length,o=Array(s),a=s,c=getHolder(n);a--;)o[a]=arguments[a];var u=s<3&&o[0]!==c&&o[s-1]!==c?[]:replaceHolders(o,c);if((s-=u.length)<r)return createRecurry(e,t,createHybrid,n.placeholder,void 0,o,u,void 0,void 0,r-s);var d=this&&this!==root$1&&this instanceof n?i:e;return apply(d,this,o)}}var WRAP_BIND_FLAG$4=1;function createPartial(e,t,r,i){var n=t&WRAP_BIND_FLAG$4,s=createCtor(e);return function t(){for(var o=-1,a=arguments.length,c=-1,u=i.length,d=Array(u+a),l=this&&this!==root$1&&this instanceof t?s:e;++c<u;)d[c]=i[c];for(;a--;)d[c++]=arguments[++o];return apply(l,n?r:this,d)}}var PLACEHOLDER="__lodash_placeholder__",WRAP_BIND_FLAG$3=1,WRAP_BIND_KEY_FLAG$3=2,WRAP_CURRY_BOUND_FLAG=4,WRAP_CURRY_FLAG$3=8,WRAP_ARY_FLAG$2=128,WRAP_REARG_FLAG$2=256,nativeMin$d=Math.min;function mergeData(e,t){var r=e[1],i=t[1],n=r|i,s=n<(WRAP_BIND_FLAG$3|WRAP_BIND_KEY_FLAG$3|WRAP_ARY_FLAG$2),o=i==WRAP_ARY_FLAG$2&&r==WRAP_CURRY_FLAG$3||i==WRAP_ARY_FLAG$2&&r==WRAP_REARG_FLAG$2&&e[7].length<=t[8]||i==(WRAP_ARY_FLAG$2|WRAP_REARG_FLAG$2)&&t[7].length<=t[8]&&r==WRAP_CURRY_FLAG$3;if(!s&&!o)return e;i&WRAP_BIND_FLAG$3&&(e[2]=t[2],n|=r&WRAP_BIND_FLAG$3?0:WRAP_CURRY_BOUND_FLAG);var a=t[3];if(a){var c=e[3];e[3]=c?composeArgs(c,a,t[4]):a,e[4]=c?replaceHolders(e[3],PLACEHOLDER):t[4]}return(a=t[5])&&(c=e[5],e[5]=c?composeArgsRight(c,a,t[6]):a,e[6]=c?replaceHolders(e[5],PLACEHOLDER):t[6]),(a=t[7])&&(e[7]=a),i&WRAP_ARY_FLAG$2&&(e[8]=null==e[8]?t[8]:nativeMin$d(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=n,e}var FUNC_ERROR_TEXT$a="Expected a function",WRAP_BIND_FLAG$2=1,WRAP_BIND_KEY_FLAG$2=2,WRAP_CURRY_FLAG$2=8,WRAP_CURRY_RIGHT_FLAG$1=16,WRAP_PARTIAL_FLAG$4=32,WRAP_PARTIAL_RIGHT_FLAG$1=64,nativeMax$e=Math.max;function createWrap(e,t,r,i,n,s,o,a){var c=t&WRAP_BIND_KEY_FLAG$2;if(!c&&"function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT$a);var u=i?i.length:0;if(u||(t&=~(WRAP_PARTIAL_FLAG$4|WRAP_PARTIAL_RIGHT_FLAG$1),i=n=void 0),o=void 0===o?o:nativeMax$e(toInteger(o),0),a=void 0===a?a:toInteger(a),u-=n?n.length:0,t&WRAP_PARTIAL_RIGHT_FLAG$1){var d=i,l=n;i=n=void 0}var h=c?void 0:getData$1(e),p=[e,t,r,i,n,d,l,s,o,a];if(h&&mergeData(p,h),e=p[0],t=p[1],r=p[2],i=p[3],n=p[4],!(a=p[9]=void 0===p[9]?c?0:e.length:nativeMax$e(p[9]-u,0))&&t&(WRAP_CURRY_FLAG$2|WRAP_CURRY_RIGHT_FLAG$1)&&(t&=~(WRAP_CURRY_FLAG$2|WRAP_CURRY_RIGHT_FLAG$1)),t&&t!=WRAP_BIND_FLAG$2)m=t==WRAP_CURRY_FLAG$2||t==WRAP_CURRY_RIGHT_FLAG$1?createCurry(e,t,a):t!=WRAP_PARTIAL_FLAG$4&&t!=(WRAP_BIND_FLAG$2|WRAP_PARTIAL_FLAG$4)||n.length?createHybrid.apply(void 0,p):createPartial(e,t,r,i);else var m=createBind(e,t,r);return setWrapToString((h?baseSetData$1:setData$1)(m,p),e,t)}var WRAP_ARY_FLAG$1=128;function ary(e,t,r){return t=r?void 0:t,t=e&&null==t?e.length:t,createWrap(e,WRAP_ARY_FLAG$1,void 0,void 0,void 0,void 0,t)}function baseAssignValue(e,t,r){"__proto__"==t&&defineProperty$1?defineProperty$1(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function eq(e,t){return e===t||e!=e&&t!=t}var objectProto$n=Object.prototype,hasOwnProperty$k=objectProto$n.hasOwnProperty;function assignValue(e,t,r){var i=e[t];hasOwnProperty$k.call(e,t)&&eq(i,r)&&(void 0!==r||t in e)||baseAssignValue(e,t,r)}function copyObject(e,t,r,i){var n=!r;r||(r={});for(var s=-1,o=t.length;++s<o;){var a=t[s],c=i?i(r[a],e[a],a,r,e):void 0;void 0===c&&(c=e[a]),n?baseAssignValue(r,a,c):assignValue(r,a,c)}return r}var nativeMax$d=Math.max;function overRest(e,t,r){return t=nativeMax$d(void 0===t?e.length-1:t,0),function(){for(var i=arguments,n=-1,s=nativeMax$d(i.length-t,0),o=Array(s);++n<s;)o[n]=i[t+n];n=-1;for(var a=Array(t+1);++n<t;)a[n]=i[n];return a[t]=r(o),apply(e,this,a)}}function baseRest(e,t){return setToString$1(overRest(e,t,identity$1),e+"")}var MAX_SAFE_INTEGER$4=9007199254740991;function isLength(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=MAX_SAFE_INTEGER$4}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction$1(e)}function isIterateeCall(e,t,r){if(!isObject(r))return!1;var i=typeof t;return!!("number"==i?isArrayLike(r)&&isIndex(t,r.length):"string"==i&&t in r)&&eq(r[t],e)}function createAssigner(e){return baseRest((function(t,r){var i=-1,n=r.length,s=n>1?r[n-1]:void 0,o=n>2?r[2]:void 0;for(s=e.length>3&&"function"==typeof s?(n--,s):void 0,o&&isIterateeCall(r[0],r[1],o)&&(s=n<3?void 0:s,n=1),t=Object(t);++i<n;){var a=r[i];a&&e(t,a,i,s)}return t}))}var objectProto$m=Object.prototype;function isPrototype(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||objectProto$m)}function baseTimes(e,t){for(var r=-1,i=Array(e);++r<e;)i[r]=t(r);return i}var argsTag$3="[object Arguments]";function baseIsArguments(e){return isObjectLike(e)&&baseGetTag(e)==argsTag$3}var objectProto$l=Object.prototype,hasOwnProperty$j=objectProto$l.hasOwnProperty,propertyIsEnumerable$1=objectProto$l.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(e){return isObjectLike(e)&&hasOwnProperty$j.call(e,"callee")&&!propertyIsEnumerable$1.call(e,"callee")},isArguments$1=isArguments;function stubFalse(){return!1}var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,Buffer$1=moduleExports$2?root$1.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,isBuffer$1=isBuffer,argsTag$2="[object Arguments]",arrayTag$2="[object Array]",boolTag$4="[object Boolean]",dateTag$4="[object Date]",errorTag$3="[object Error]",funcTag$1="[object Function]",mapTag$9="[object Map]",numberTag$4="[object Number]",objectTag$4="[object Object]",regexpTag$4="[object RegExp]",setTag$9="[object Set]",stringTag$4="[object String]",weakMapTag$3="[object WeakMap]",arrayBufferTag$4="[object ArrayBuffer]",dataViewTag$4="[object DataView]",float32Tag$2="[object Float32Array]",float64Tag$2="[object Float64Array]",int8Tag$2="[object Int8Array]",int16Tag$2="[object Int16Array]",int32Tag$2="[object Int32Array]",uint8Tag$2="[object Uint8Array]",uint8ClampedTag$2="[object Uint8ClampedArray]",uint16Tag$2="[object Uint16Array]",uint32Tag$2="[object Uint32Array]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(t){return e(t)}}typedArrayTags[float32Tag$2]=typedArrayTags[float64Tag$2]=typedArrayTags[int8Tag$2]=typedArrayTags[int16Tag$2]=typedArrayTags[int32Tag$2]=typedArrayTags[uint8Tag$2]=typedArrayTags[uint8ClampedTag$2]=typedArrayTags[uint16Tag$2]=typedArrayTags[uint32Tag$2]=!0,typedArrayTags[argsTag$2]=typedArrayTags[arrayTag$2]=typedArrayTags[arrayBufferTag$4]=typedArrayTags[boolTag$4]=typedArrayTags[dataViewTag$4]=typedArrayTags[dateTag$4]=typedArrayTags[errorTag$3]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag$9]=typedArrayTags[numberTag$4]=typedArrayTags[objectTag$4]=typedArrayTags[regexpTag$4]=typedArrayTags[setTag$9]=typedArrayTags[stringTag$4]=typedArrayTags[weakMapTag$3]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal$1.process,nodeUtil=function(){try{var e=freeModule$1&&freeModule$1.require&&freeModule$1.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeUtil$1=nodeUtil,nodeIsTypedArray=nodeUtil$1&&nodeUtil$1.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,isTypedArray$1=isTypedArray,objectProto$k=Object.prototype,hasOwnProperty$i=objectProto$k.hasOwnProperty;function arrayLikeKeys(e,t){var r=isArray$1(e),i=!r&&isArguments$1(e),n=!r&&!i&&isBuffer$1(e),s=!r&&!i&&!n&&isTypedArray$1(e),o=r||i||n||s,a=o?baseTimes(e.length,String):[],c=a.length;for(var u in e)!t&&!hasOwnProperty$i.call(e,u)||o&&("length"==u||n&&("offset"==u||"parent"==u)||s&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||isIndex(u,c))||a.push(u);return a}function overArg(e,t){return function(r){return e(t(r))}}var nativeKeys=overArg(Object.keys,Object),nativeKeys$1=nativeKeys,objectProto$j=Object.prototype,hasOwnProperty$h=objectProto$j.hasOwnProperty;function baseKeys(e){if(!isPrototype(e))return nativeKeys$1(e);var t=[];for(var r in Object(e))hasOwnProperty$h.call(e,r)&&"constructor"!=r&&t.push(r);return t}function keys(e){return isArrayLike(e)?arrayLikeKeys(e):baseKeys(e)}var objectProto$i=Object.prototype,hasOwnProperty$g=objectProto$i.hasOwnProperty,assign=createAssigner((function(e,t){if(isPrototype(t)||isArrayLike(t))copyObject(t,keys(t),e);else for(var r in t)hasOwnProperty$g.call(t,r)&&assignValue(e,r,t[r])})),assign$1=assign;function nativeKeysIn(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}var objectProto$h=Object.prototype,hasOwnProperty$f=objectProto$h.hasOwnProperty;function baseKeysIn(e){if(!isObject(e))return nativeKeysIn(e);var t=isPrototype(e),r=[];for(var i in e)("constructor"!=i||!t&&hasOwnProperty$f.call(e,i))&&r.push(i);return r}function keysIn(e){return isArrayLike(e)?arrayLikeKeys(e,!0):baseKeysIn(e)}var assignIn=createAssigner((function(e,t){copyObject(t,keysIn(t),e)})),extend=assignIn,assignInWith=createAssigner((function(e,t,r,i){copyObject(t,keysIn(t),e,i)})),extendWith=assignInWith,assignWith=createAssigner((function(e,t,r,i){copyObject(t,keys(t),e,i)})),assignWith$1=assignWith,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/;function isKey(e,t){if(isArray$1(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!isSymbol(e))||(reIsPlainProp.test(e)||!reIsDeepProp.test(e)||null!=t&&e in Object(t))}var nativeCreate=getNative(Object,"create"),nativeCreate$1=nativeCreate;function hashClear(){this.__data__=nativeCreate$1?nativeCreate$1(null):{},this.size=0}function hashDelete(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var HASH_UNDEFINED$2="__lodash_hash_undefined__",objectProto$g=Object.prototype,hasOwnProperty$e=objectProto$g.hasOwnProperty;function hashGet(e){var t=this.__data__;if(nativeCreate$1){var r=t[e];return r===HASH_UNDEFINED$2?void 0:r}return hasOwnProperty$e.call(t,e)?t[e]:void 0}var objectProto$f=Object.prototype,hasOwnProperty$d=objectProto$f.hasOwnProperty;function hashHas(e){var t=this.__data__;return nativeCreate$1?void 0!==t[e]:hasOwnProperty$d.call(t,e)}var HASH_UNDEFINED$1="__lodash_hash_undefined__";function hashSet(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=nativeCreate$1&&void 0===t?HASH_UNDEFINED$1:t,this}function Hash(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}function listCacheClear(){this.__data__=[],this.size=0}function assocIndexOf(e,t){for(var r=e.length;r--;)if(eq(e[r][0],t))return r;return-1}Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet;var arrayProto$5=Array.prototype,splice$2=arrayProto$5.splice;function listCacheDelete(e){var t=this.__data__,r=assocIndexOf(t,e);return!(r<0)&&(r==t.length-1?t.pop():splice$2.call(t,r,1),--this.size,!0)}function listCacheGet(e){var t=this.__data__,r=assocIndexOf(t,e);return r<0?void 0:t[r][1]}function listCacheHas(e){return assocIndexOf(this.__data__,e)>-1}function listCacheSet(e,t){var r=this.__data__,i=assocIndexOf(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}function ListCache(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet;var Map$1=getNative(root$1,"Map"),Map$2=Map$1;function mapCacheClear(){this.size=0,this.__data__={hash:new Hash,map:new(Map$2||ListCache),string:new Hash}}function isKeyable(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}function getMapData(e,t){var r=e.__data__;return isKeyable(t)?r["string"==typeof t?"string":"hash"]:r.map}function mapCacheDelete(e){var t=getMapData(this,e).delete(e);return this.size-=t?1:0,t}function mapCacheGet(e){return getMapData(this,e).get(e)}function mapCacheHas(e){return getMapData(this,e).has(e)}function mapCacheSet(e,t){var r=getMapData(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}function MapCache(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet;var FUNC_ERROR_TEXT$9="Expected a function";function memoize(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(FUNC_ERROR_TEXT$9);var r=function(){var i=arguments,n=t?t.apply(this,i):i[0],s=r.cache;if(s.has(n))return s.get(n);var o=e.apply(this,i);return r.cache=s.set(n,o)||s,o};return r.cache=new(memoize.Cache||MapCache),r}memoize.Cache=MapCache;var MAX_MEMOIZE_SIZE=500;function memoizeCapped(e){var t=memoize(e,(function(e){return r.size===MAX_MEMOIZE_SIZE&&r.clear(),e})),r=t.cache;return t}var rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=memoizeCapped((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(rePropName,(function(e,r,i,n){t.push(i?n.replace(reEscapeChar,"$1"):r||e)})),t})),stringToPath$1=stringToPath;function toString$1(e){return null==e?"":baseToString(e)}function castPath(e,t){return isArray$1(e)?e:isKey(e,t)?[e]:stringToPath$1(toString$1(e))}var INFINITY$3=1/0;function toKey(e){if("string"==typeof e||isSymbol(e))return e;var t=e+"";return"0"==t&&1/e==-INFINITY$3?"-0":t}function baseGet(e,t){for(var r=0,i=(t=castPath(t,e)).length;null!=e&&r<i;)e=e[toKey(t[r++])];return r&&r==i?e:void 0}function get(e,t,r){var i=null==e?void 0:baseGet(e,t);return void 0===i?r:i}function baseAt(e,t){for(var r=-1,i=t.length,n=Array(i),s=null==e;++r<i;)n[r]=s?void 0:get(e,t[r]);return n}function arrayPush(e,t){for(var r=-1,i=t.length,n=e.length;++r<i;)e[n+r]=t[r];return e}var spreadableSymbol=Symbol$2?Symbol$2.isConcatSpreadable:void 0;function isFlattenable(e){return isArray$1(e)||isArguments$1(e)||!!(spreadableSymbol&&e&&e[spreadableSymbol])}function baseFlatten(e,t,r,i,n){var s=-1,o=e.length;for(r||(r=isFlattenable),n||(n=[]);++s<o;){var a=e[s];t>0&&r(a)?t>1?baseFlatten(a,t-1,r,i,n):arrayPush(n,a):i||(n[n.length]=a)}return n}function flatten(e){return(null==e?0:e.length)?baseFlatten(e,1):[]}function flatRest(e){return setToString$1(overRest(e,void 0,flatten),e+"")}var at$1=flatRest(baseAt),at$2=at$1,getPrototype=overArg(Object.getPrototypeOf,Object),getPrototype$1=getPrototype,objectTag$3="[object Object]",funcProto=Function.prototype,objectProto$e=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$c=objectProto$e.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!=objectTag$3)return!1;var t=getPrototype$1(e);if(null===t)return!0;var r=hasOwnProperty$c.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString.call(r)==objectCtorString}var domExcTag="[object DOMException]",errorTag$2="[object Error]";function isError(e){if(!isObjectLike(e))return!1;var t=baseGetTag(e);return t==errorTag$2||t==domExcTag||"string"==typeof e.message&&"string"==typeof e.name&&!isPlainObject(e)}var attempt=baseRest((function(e,t){try{return apply(e,void 0,t)}catch(e){return isError(e)?e:new Error(e)}})),attempt$1=attempt,FUNC_ERROR_TEXT$8="Expected a function";function before(e,t){var r;if("function"!=typeof t)throw new TypeError(FUNC_ERROR_TEXT$8);return e=toInteger(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}var WRAP_BIND_FLAG$1=1,WRAP_PARTIAL_FLAG$3=32,bind$1=baseRest((function(e,t,r){var i=WRAP_BIND_FLAG$1;if(r.length){var n=replaceHolders(r,getHolder(bind$1));i|=WRAP_PARTIAL_FLAG$3}return createWrap(e,i,t,r,n)}));bind$1.placeholder={};var bind$2=bind$1,bindAll=flatRest((function(e,t){return arrayEach(t,(function(t){t=toKey(t),baseAssignValue(e,t,bind$2(e[t],e))})),e})),bindAll$1=bindAll,WRAP_BIND_FLAG=1,WRAP_BIND_KEY_FLAG$1=2,WRAP_PARTIAL_FLAG$2=32,bindKey=baseRest((function(e,t,r){var i=WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG$1;if(r.length){var n=replaceHolders(r,getHolder(bindKey));i|=WRAP_PARTIAL_FLAG$2}return createWrap(t,i,e,r,n)}));bindKey.placeholder={};var bindKey$1=bindKey;function baseSlice(e,t,r){var i=-1,n=e.length;t<0&&(t=-t>n?0:n+t),(r=r>n?n:r)<0&&(r+=n),n=t>r?0:r-t>>>0,t>>>=0;for(var s=Array(n);++i<n;)s[i]=e[i+t];return s}function castSlice(e,t,r){var i=e.length;return r=void 0===r?i:r,!t&&r>=i?e:baseSlice(e,t,r)}var rsAstralRange$3="\\ud800-\\udfff",rsComboMarksRange$4="\\u0300-\\u036f",reComboHalfMarksRange$4="\\ufe20-\\ufe2f",rsComboSymbolsRange$4="\\u20d0-\\u20ff",rsComboRange$4=rsComboMarksRange$4+reComboHalfMarksRange$4+rsComboSymbolsRange$4,rsVarRange$3="\\ufe0e\\ufe0f",rsZWJ$3="\\u200d",reHasUnicode=RegExp("["+rsZWJ$3+rsAstralRange$3+rsComboRange$4+rsVarRange$3+"]");function hasUnicode(e){return reHasUnicode.test(e)}function asciiToArray(e){return e.split("")}var rsAstralRange$2="\\ud800-\\udfff",rsComboMarksRange$3="\\u0300-\\u036f",reComboHalfMarksRange$3="\\ufe20-\\ufe2f",rsComboSymbolsRange$3="\\u20d0-\\u20ff",rsComboRange$3=rsComboMarksRange$3+reComboHalfMarksRange$3+rsComboSymbolsRange$3,rsVarRange$2="\\ufe0e\\ufe0f",rsAstral$1="["+rsAstralRange$2+"]",rsCombo$3="["+rsComboRange$3+"]",rsFitz$2="\\ud83c[\\udffb-\\udfff]",rsModifier$2="(?:"+rsCombo$3+"|"+rsFitz$2+")",rsNonAstral$2="[^"+rsAstralRange$2+"]",rsRegional$2="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair$2="[\\ud800-\\udbff][\\udc00-\\udfff]",rsZWJ$2="\\u200d",reOptMod$2=rsModifier$2+"?",rsOptVar$2="["+rsVarRange$2+"]?",rsOptJoin$2="(?:"+rsZWJ$2+"(?:"+[rsNonAstral$2,rsRegional$2,rsSurrPair$2].join("|")+")"+rsOptVar$2+reOptMod$2+")*",rsSeq$2=rsOptVar$2+reOptMod$2+rsOptJoin$2,rsSymbol$1="(?:"+[rsNonAstral$2+rsCombo$3+"?",rsCombo$3,rsRegional$2,rsSurrPair$2,rsAstral$1].join("|")+")",reUnicode$1=RegExp(rsFitz$2+"(?="+rsFitz$2+")|"+rsSymbol$1+rsSeq$2,"g");function unicodeToArray(e){return e.match(reUnicode$1)||[]}function stringToArray(e){return hasUnicode(e)?unicodeToArray(e):asciiToArray(e)}function createCaseFirst(e){return function(t){var r=hasUnicode(t=toString$1(t))?stringToArray(t):void 0,i=r?r[0]:t.charAt(0),n=r?castSlice(r,1).join(""):t.slice(1);return i[e]()+n}}var upperFirst=createCaseFirst("toUpperCase"),upperFirst$1=upperFirst;function capitalize(e){return upperFirst$1(toString$1(e).toLowerCase())}function arrayReduce(e,t,r,i){var n=-1,s=null==e?0:e.length;for(i&&s&&(r=e[++n]);++n<s;)r=t(r,e[n],n,e);return r}function basePropertyOf(e){return function(t){return null==e?void 0:e[t]}}var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},deburrLetter=basePropertyOf(deburredLetters),deburrLetter$1=deburrLetter,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,rsComboMarksRange$2="\\u0300-\\u036f",reComboHalfMarksRange$2="\\ufe20-\\ufe2f",rsComboSymbolsRange$2="\\u20d0-\\u20ff",rsComboRange$2=rsComboMarksRange$2+reComboHalfMarksRange$2+rsComboSymbolsRange$2,rsCombo$2="["+rsComboRange$2+"]",reComboMark=RegExp(rsCombo$2,"g");function deburr(e){return(e=toString$1(e))&&e.replace(reLatin,deburrLetter$1).replace(reComboMark,"")}var reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;function asciiWords(e){return e.match(reAsciiWord)||[]}var reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;function hasUnicodeWord(e){return reHasUnicodeWord.test(e)}var rsAstralRange$1="\\ud800-\\udfff",rsComboMarksRange$1="\\u0300-\\u036f",reComboHalfMarksRange$1="\\ufe20-\\ufe2f",rsComboSymbolsRange$1="\\u20d0-\\u20ff",rsComboRange$1=rsComboMarksRange$1+reComboHalfMarksRange$1+rsComboSymbolsRange$1,rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange$1="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos$1="['’]",rsBreak="["+rsBreakRange+"]",rsCombo$1="["+rsComboRange$1+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange$1+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz$1="\\ud83c[\\udffb-\\udfff]",rsModifier$1="(?:"+rsCombo$1+"|"+rsFitz$1+")",rsNonAstral$1="[^"+rsAstralRange$1+"]",rsRegional$1="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair$1="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ$1="\\u200d",rsMiscLower="(?:"+rsLower+"|"+rsMisc+")",rsMiscUpper="(?:"+rsUpper+"|"+rsMisc+")",rsOptContrLower="(?:"+rsApos$1+"(?:d|ll|m|re|s|t|ve))?",rsOptContrUpper="(?:"+rsApos$1+"(?:D|LL|M|RE|S|T|VE))?",reOptMod$1=rsModifier$1+"?",rsOptVar$1="["+rsVarRange$1+"]?",rsOptJoin$1="(?:"+rsZWJ$1+"(?:"+[rsNonAstral$1,rsRegional$1,rsSurrPair$1].join("|")+")"+rsOptVar$1+reOptMod$1+")*",rsOrdLower="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",rsOrdUpper="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",rsSeq$1=rsOptVar$1+reOptMod$1+rsOptJoin$1,rsEmoji="(?:"+[rsDingbat,rsRegional$1,rsSurrPair$1].join("|")+")"+rsSeq$1,reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptContrLower+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsMiscUpper+"+"+rsOptContrUpper+"(?="+[rsBreak,rsUpper+rsMiscLower,"$"].join("|")+")",rsUpper+"?"+rsMiscLower+"+"+rsOptContrLower,rsUpper+"+"+rsOptContrUpper,rsOrdUpper,rsOrdLower,rsDigits,rsEmoji].join("|"),"g");function unicodeWords(e){return e.match(reUnicodeWord)||[]}function words(e,t,r){return e=toString$1(e),void 0===(t=r?void 0:t)?hasUnicodeWord(e)?unicodeWords(e):asciiWords(e):e.match(t)||[]}var rsApos="['’]",reApos=RegExp(rsApos,"g");function createCompounder(e){return function(t){return arrayReduce(words(deburr(t).replace(reApos,"")),e,"")}}var camelCase=createCompounder((function(e,t,r){return t=t.toLowerCase(),e+(r?capitalize(t):t)})),camelCase$1=camelCase;function castArray(){if(!arguments.length)return[];var e=arguments[0];return isArray$1(e)?e:[e]}var nativeIsFinite$1=root$1.isFinite,nativeMin$c=Math.min;function createRound(e){var t=Math[e];return function(e,r){if(e=toNumber(e),(r=null==r?0:nativeMin$c(toInteger(r),292))&&nativeIsFinite$1(e)){var i=(toString$1(e)+"e").split("e");return+((i=(toString$1(t(i[0]+"e"+(+i[1]+r)))+"e").split("e"))[0]+"e"+(+i[1]-r))}return t(e)}}var ceil=createRound("ceil"),ceil$1=ceil;function chain(e){var t=lodash$1(e);return t.__chain__=!0,t}var nativeCeil$3=Math.ceil,nativeMax$c=Math.max;function chunk(e,t,r){t=(r?isIterateeCall(e,t,r):void 0===t)?1:nativeMax$c(toInteger(t),0);var i=null==e?0:e.length;if(!i||t<1)return[];for(var n=0,s=0,o=Array(nativeCeil$3(i/t));n<i;)o[s++]=baseSlice(e,n,n+=t);return o}function baseClamp(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e}function clamp(e,t,r){return void 0===r&&(r=t,t=void 0),void 0!==r&&(r=(r=toNumber(r))==r?r:0),void 0!==t&&(t=(t=toNumber(t))==t?t:0),baseClamp(toNumber(e),t,r)}function stackClear(){this.__data__=new ListCache,this.size=0}function stackDelete(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}function stackGet(e){return this.__data__.get(e)}function stackHas(e){return this.__data__.has(e)}var LARGE_ARRAY_SIZE$2=200;function stackSet(e,t){var r=this.__data__;if(r instanceof ListCache){var i=r.__data__;if(!Map$2||i.length<LARGE_ARRAY_SIZE$2-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new MapCache(i)}return r.set(e,t),this.size=r.size,this}function Stack(e){var t=this.__data__=new ListCache(e);this.size=t.size}function baseAssign(e,t){return e&&copyObject(t,keys(t),e)}function baseAssignIn(e,t){return e&&copyObject(t,keysIn(t),e)}Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root$1.Buffer:void 0,allocUnsafe=Buffer?Buffer.allocUnsafe:void 0;function cloneBuffer(e,t){if(t)return e.slice();var r=e.length,i=allocUnsafe?allocUnsafe(r):new e.constructor(r);return e.copy(i),i}function arrayFilter(e,t){for(var r=-1,i=null==e?0:e.length,n=0,s=[];++r<i;){var o=e[r];t(o,r,e)&&(s[n++]=o)}return s}function stubArray(){return[]}var objectProto$d=Object.prototype,propertyIsEnumerable=objectProto$d.propertyIsEnumerable,nativeGetSymbols$1=Object.getOwnPropertySymbols,getSymbols=nativeGetSymbols$1?function(e){return null==e?[]:(e=Object(e),arrayFilter(nativeGetSymbols$1(e),(function(t){return propertyIsEnumerable.call(e,t)})))}:stubArray,getSymbols$1=getSymbols;function copySymbols(e,t){return copyObject(e,getSymbols$1(e),t)}var nativeGetSymbols=Object.getOwnPropertySymbols,getSymbolsIn=nativeGetSymbols?function(e){for(var t=[];e;)arrayPush(t,getSymbols$1(e)),e=getPrototype$1(e);return t}:stubArray,getSymbolsIn$1=getSymbolsIn;function copySymbolsIn(e,t){return copyObject(e,getSymbolsIn$1(e),t)}function baseGetAllKeys(e,t,r){var i=t(e);return isArray$1(e)?i:arrayPush(i,r(e))}function getAllKeys(e){return baseGetAllKeys(e,keys,getSymbols$1)}function getAllKeysIn(e){return baseGetAllKeys(e,keysIn,getSymbolsIn$1)}var DataView$1=getNative(root$1,"DataView"),DataView$2=DataView$1,Promise$1=getNative(root$1,"Promise"),Promise$2=Promise$1,Set$1=getNative(root$1,"Set"),Set$2=Set$1,mapTag$8="[object Map]",objectTag$2="[object Object]",promiseTag="[object Promise]",setTag$8="[object Set]",weakMapTag$2="[object WeakMap]",dataViewTag$3="[object DataView]",dataViewCtorString=toSource(DataView$2),mapCtorString=toSource(Map$2),promiseCtorString=toSource(Promise$2),setCtorString=toSource(Set$2),weakMapCtorString=toSource(WeakMap$1),getTag=baseGetTag;(DataView$2&&getTag(new DataView$2(new ArrayBuffer(1)))!=dataViewTag$3||Map$2&&getTag(new Map$2)!=mapTag$8||Promise$2&&getTag(Promise$2.resolve())!=promiseTag||Set$2&&getTag(new Set$2)!=setTag$8||WeakMap$1&&getTag(new WeakMap$1)!=weakMapTag$2)&&(getTag=function(e){var t=baseGetTag(e),r=t==objectTag$2?e.constructor:void 0,i=r?toSource(r):"";if(i)switch(i){case dataViewCtorString:return dataViewTag$3;case mapCtorString:return mapTag$8;case promiseCtorString:return promiseTag;case setCtorString:return setTag$8;case weakMapCtorString:return weakMapTag$2}return t});var getTag$1=getTag,objectProto$c=Object.prototype,hasOwnProperty$b=objectProto$c.hasOwnProperty;function initCloneArray(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&hasOwnProperty$b.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Uint8Array$1=root$1.Uint8Array,Uint8Array$2=Uint8Array$1;function cloneArrayBuffer(e){var t=new e.constructor(e.byteLength);return new Uint8Array$2(t).set(new Uint8Array$2(e)),t}function cloneDataView(e,t){var r=t?cloneArrayBuffer(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var reFlags$1=/\w*$/;function cloneRegExp(e){var t=new e.constructor(e.source,reFlags$1.exec(e));return t.lastIndex=e.lastIndex,t}var symbolProto$1=Symbol$2?Symbol$2.prototype:void 0,symbolValueOf$1=symbolProto$1?symbolProto$1.valueOf:void 0;function cloneSymbol(e){return symbolValueOf$1?Object(symbolValueOf$1.call(e)):{}}function cloneTypedArray(e,t){var r=t?cloneArrayBuffer(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var boolTag$3="[object Boolean]",dateTag$3="[object Date]",mapTag$7="[object Map]",numberTag$3="[object Number]",regexpTag$3="[object RegExp]",setTag$7="[object Set]",stringTag$3="[object String]",symbolTag$2="[object Symbol]",arrayBufferTag$3="[object ArrayBuffer]",dataViewTag$2="[object DataView]",float32Tag$1="[object Float32Array]",float64Tag$1="[object Float64Array]",int8Tag$1="[object Int8Array]",int16Tag$1="[object Int16Array]",int32Tag$1="[object Int32Array]",uint8Tag$1="[object Uint8Array]",uint8ClampedTag$1="[object Uint8ClampedArray]",uint16Tag$1="[object Uint16Array]",uint32Tag$1="[object Uint32Array]";function initCloneByTag(e,t,r){var i=e.constructor;switch(t){case arrayBufferTag$3:return cloneArrayBuffer(e);case boolTag$3:case dateTag$3:return new i(+e);case dataViewTag$2:return cloneDataView(e,r);case float32Tag$1:case float64Tag$1:case int8Tag$1:case int16Tag$1:case int32Tag$1:case uint8Tag$1:case uint8ClampedTag$1:case uint16Tag$1:case uint32Tag$1:return cloneTypedArray(e,r);case mapTag$7:return new i;case numberTag$3:case stringTag$3:return new i(e);case regexpTag$3:return cloneRegExp(e);case setTag$7:return new i;case symbolTag$2:return cloneSymbol(e)}}function initCloneObject(e){return"function"!=typeof e.constructor||isPrototype(e)?{}:baseCreate$1(getPrototype$1(e))}var mapTag$6="[object Map]";function baseIsMap(e){return isObjectLike(e)&&getTag$1(e)==mapTag$6}var nodeIsMap=nodeUtil$1&&nodeUtil$1.isMap,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isMap$1=isMap,setTag$6="[object Set]";function baseIsSet(e){return isObjectLike(e)&&getTag$1(e)==setTag$6}var nodeIsSet=nodeUtil$1&&nodeUtil$1.isSet,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isSet$1=isSet,CLONE_DEEP_FLAG$7=1,CLONE_FLAT_FLAG$1=2,CLONE_SYMBOLS_FLAG$5=4,argsTag$1="[object Arguments]",arrayTag$1="[object Array]",boolTag$2="[object Boolean]",dateTag$2="[object Date]",errorTag$1="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag$5="[object Map]",numberTag$2="[object Number]",objectTag$1="[object Object]",regexpTag$2="[object RegExp]",setTag$5="[object Set]",stringTag$2="[object String]",symbolTag$1="[object Symbol]",weakMapTag$1="[object WeakMap]",arrayBufferTag$2="[object ArrayBuffer]",dataViewTag$1="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",cloneableTags={};function baseClone(e,t,r,i,n,s){var o,a=t&CLONE_DEEP_FLAG$7,c=t&CLONE_FLAT_FLAG$1,u=t&CLONE_SYMBOLS_FLAG$5;if(r&&(o=n?r(e,i,n,s):r(e)),void 0!==o)return o;if(!isObject(e))return e;var d=isArray$1(e);if(d){if(o=initCloneArray(e),!a)return copyArray(e,o)}else{var l=getTag$1(e),h=l==funcTag||l==genTag;if(isBuffer$1(e))return cloneBuffer(e,a);if(l==objectTag$1||l==argsTag$1||h&&!n){if(o=c||h?{}:initCloneObject(e),!a)return c?copySymbolsIn(e,baseAssignIn(o,e)):copySymbols(e,baseAssign(o,e))}else{if(!cloneableTags[l])return n?e:{};o=initCloneByTag(e,l,a)}}s||(s=new Stack);var p=s.get(e);if(p)return p;s.set(e,o),isSet$1(e)?e.forEach((function(i){o.add(baseClone(i,t,r,i,e,s))})):isMap$1(e)&&e.forEach((function(i,n){o.set(n,baseClone(i,t,r,n,e,s))}));var m=d?void 0:(u?c?getAllKeysIn:getAllKeys:c?keysIn:keys)(e);return arrayEach(m||e,(function(i,n){m&&(i=e[n=i]),assignValue(o,n,baseClone(i,t,r,n,e,s))})),o}cloneableTags[argsTag$1]=cloneableTags[arrayTag$1]=cloneableTags[arrayBufferTag$2]=cloneableTags[dataViewTag$1]=cloneableTags[boolTag$2]=cloneableTags[dateTag$2]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag$5]=cloneableTags[numberTag$2]=cloneableTags[objectTag$1]=cloneableTags[regexpTag$2]=cloneableTags[setTag$5]=cloneableTags[stringTag$2]=cloneableTags[symbolTag$1]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag$1]=cloneableTags[funcTag]=cloneableTags[weakMapTag$1]=!1;var CLONE_SYMBOLS_FLAG$4=4;function clone(e){return baseClone(e,CLONE_SYMBOLS_FLAG$4)}var CLONE_DEEP_FLAG$6=1,CLONE_SYMBOLS_FLAG$3=4;function cloneDeep(e){return baseClone(e,CLONE_DEEP_FLAG$6|CLONE_SYMBOLS_FLAG$3)}var CLONE_DEEP_FLAG$5=1,CLONE_SYMBOLS_FLAG$2=4;function cloneDeepWith(e,t){return baseClone(e,CLONE_DEEP_FLAG$5|CLONE_SYMBOLS_FLAG$2,t="function"==typeof t?t:void 0)}var CLONE_SYMBOLS_FLAG$1=4;function cloneWith(e,t){return baseClone(e,CLONE_SYMBOLS_FLAG$1,t="function"==typeof t?t:void 0)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function compact(e){for(var t=-1,r=null==e?0:e.length,i=0,n=[];++t<r;){var s=e[t];s&&(n[i++]=s)}return n}function concat(){var e=arguments.length;if(!e)return[];for(var t=Array(e-1),r=arguments[0],i=e;i--;)t[i-1]=arguments[i];return arrayPush(isArray$1(r)?copyArray(r):[r],baseFlatten(t,1))}var HASH_UNDEFINED="__lodash_hash_undefined__";function setCacheAdd(e){return this.__data__.set(e,HASH_UNDEFINED),this}function setCacheHas(e){return this.__data__.has(e)}function SetCache(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new MapCache;++t<r;)this.add(e[t])}function arraySome(e,t){for(var r=-1,i=null==e?0:e.length;++r<i;)if(t(e[r],r,e))return!0;return!1}function cacheHas(e,t){return e.has(t)}SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var COMPARE_PARTIAL_FLAG$5=1,COMPARE_UNORDERED_FLAG$3=2;function equalArrays(e,t,r,i,n,s){var o=r&COMPARE_PARTIAL_FLAG$5,a=e.length,c=t.length;if(a!=c&&!(o&&c>a))return!1;var u=s.get(e),d=s.get(t);if(u&&d)return u==t&&d==e;var l=-1,h=!0,p=r&COMPARE_UNORDERED_FLAG$3?new SetCache:void 0;for(s.set(e,t),s.set(t,e);++l<a;){var m=e[l],f=t[l];if(i)var g=o?i(f,m,l,t,e,s):i(m,f,l,e,t,s);if(void 0!==g){if(g)continue;h=!1;break}if(p){if(!arraySome(t,(function(e,t){if(!cacheHas(p,t)&&(m===e||n(m,e,r,i,s)))return p.push(t)}))){h=!1;break}}else if(m!==f&&!n(m,f,r,i,s)){h=!1;break}}return s.delete(e),s.delete(t),h}function mapToArray(e){var t=-1,r=Array(e.size);return e.forEach((function(e,i){r[++t]=[i,e]})),r}function setToArray(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=e})),r}var COMPARE_PARTIAL_FLAG$4=1,COMPARE_UNORDERED_FLAG$2=2,boolTag$1="[object Boolean]",dateTag$1="[object Date]",errorTag="[object Error]",mapTag$4="[object Map]",numberTag$1="[object Number]",regexpTag$1="[object RegExp]",setTag$4="[object Set]",stringTag$1="[object String]",symbolTag="[object Symbol]",arrayBufferTag$1="[object ArrayBuffer]",dataViewTag="[object DataView]",symbolProto=Symbol$2?Symbol$2.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;function equalByTag(e,t,r,i,n,s,o){switch(r){case dataViewTag:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case arrayBufferTag$1:return!(e.byteLength!=t.byteLength||!s(new Uint8Array$2(e),new Uint8Array$2(t)));case boolTag$1:case dateTag$1:case numberTag$1:return eq(+e,+t);case errorTag:return e.name==t.name&&e.message==t.message;case regexpTag$1:case stringTag$1:return e==t+"";case mapTag$4:var a=mapToArray;case setTag$4:var c=i&COMPARE_PARTIAL_FLAG$4;if(a||(a=setToArray),e.size!=t.size&&!c)return!1;var u=o.get(e);if(u)return u==t;i|=COMPARE_UNORDERED_FLAG$2,o.set(e,t);var d=equalArrays(a(e),a(t),i,n,s,o);return o.delete(e),d;case symbolTag:if(symbolValueOf)return symbolValueOf.call(e)==symbolValueOf.call(t)}return!1}var COMPARE_PARTIAL_FLAG$3=1,objectProto$b=Object.prototype,hasOwnProperty$a=objectProto$b.hasOwnProperty;function equalObjects(e,t,r,i,n,s){var o=r&COMPARE_PARTIAL_FLAG$3,a=getAllKeys(e),c=a.length;if(c!=getAllKeys(t).length&&!o)return!1;for(var u=c;u--;){var d=a[u];if(!(o?d in t:hasOwnProperty$a.call(t,d)))return!1}var l=s.get(e),h=s.get(t);if(l&&h)return l==t&&h==e;var p=!0;s.set(e,t),s.set(t,e);for(var m=o;++u<c;){var f=e[d=a[u]],g=t[d];if(i)var v=o?i(g,f,d,t,e,s):i(f,g,d,e,t,s);if(!(void 0===v?f===g||n(f,g,r,i,s):v)){p=!1;break}m||(m="constructor"==d)}if(p&&!m){var y=e.constructor,_=t.constructor;y==_||!("constructor"in e)||!("constructor"in t)||"function"==typeof y&&y instanceof y&&"function"==typeof _&&_ instanceof _||(p=!1)}return s.delete(e),s.delete(t),p}var COMPARE_PARTIAL_FLAG$2=1,argsTag="[object Arguments]",arrayTag="[object Array]",objectTag="[object Object]",objectProto$a=Object.prototype,hasOwnProperty$9=objectProto$a.hasOwnProperty;function baseIsEqualDeep(e,t,r,i,n,s){var o=isArray$1(e),a=isArray$1(t),c=o?arrayTag:getTag$1(e),u=a?arrayTag:getTag$1(t),d=(c=c==argsTag?objectTag:c)==objectTag,l=(u=u==argsTag?objectTag:u)==objectTag,h=c==u;if(h&&isBuffer$1(e)){if(!isBuffer$1(t))return!1;o=!0,d=!1}if(h&&!d)return s||(s=new Stack),o||isTypedArray$1(e)?equalArrays(e,t,r,i,n,s):equalByTag(e,t,c,r,i,n,s);if(!(r&COMPARE_PARTIAL_FLAG$2)){var p=d&&hasOwnProperty$9.call(e,"__wrapped__"),m=l&&hasOwnProperty$9.call(t,"__wrapped__");if(p||m){var f=p?e.value():e,g=m?t.value():t;return s||(s=new Stack),n(f,g,r,i,s)}}return!!h&&(s||(s=new Stack),equalObjects(e,t,r,i,n,s))}function baseIsEqual(e,t,r,i,n){return e===t||(null==e||null==t||!isObjectLike(e)&&!isObjectLike(t)?e!=e&&t!=t:baseIsEqualDeep(e,t,r,i,baseIsEqual,n))}var COMPARE_PARTIAL_FLAG$1=1,COMPARE_UNORDERED_FLAG$1=2;function baseIsMatch(e,t,r,i){var n=r.length,s=n,o=!i;if(null==e)return!s;for(e=Object(e);n--;){var a=r[n];if(o&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++n<s;){var c=(a=r[n])[0],u=e[c],d=a[1];if(o&&a[2]){if(void 0===u&&!(c in e))return!1}else{var l=new Stack;if(i)var h=i(u,d,c,e,t,l);if(!(void 0===h?baseIsEqual(d,u,COMPARE_PARTIAL_FLAG$1|COMPARE_UNORDERED_FLAG$1,i,l):h))return!1}}return!0}function isStrictComparable(e){return e==e&&!isObject(e)}function getMatchData(e){for(var t=keys(e),r=t.length;r--;){var i=t[r],n=e[i];t[r]=[i,n,isStrictComparable(n)]}return t}function matchesStrictComparable(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}}function baseMatches(e){var t=getMatchData(e);return 1==t.length&&t[0][2]?matchesStrictComparable(t[0][0],t[0][1]):function(r){return r===e||baseIsMatch(r,e,t)}}function baseHasIn(e,t){return null!=e&&t in Object(e)}function hasPath(e,t,r){for(var i=-1,n=(t=castPath(t,e)).length,s=!1;++i<n;){var o=toKey(t[i]);if(!(s=null!=e&&r(e,o)))break;e=e[o]}return s||++i!=n?s:!!(n=null==e?0:e.length)&&isLength(n)&&isIndex(o,n)&&(isArray$1(e)||isArguments$1(e))}function hasIn(e,t){return null!=e&&hasPath(e,t,baseHasIn)}var COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;function baseMatchesProperty(e,t){return isKey(e)&&isStrictComparable(t)?matchesStrictComparable(toKey(e),t):function(r){var i=get(r,e);return void 0===i&&i===t?hasIn(r,e):baseIsEqual(t,i,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG)}}function baseProperty(e){return function(t){return null==t?void 0:t[e]}}function basePropertyDeep(e){return function(t){return baseGet(t,e)}}function property(e){return isKey(e)?baseProperty(toKey(e)):basePropertyDeep(e)}function baseIteratee(e){return"function"==typeof e?e:null==e?identity$1:"object"==typeof e?isArray$1(e)?baseMatchesProperty(e[0],e[1]):baseMatches(e):property(e)}var FUNC_ERROR_TEXT$7="Expected a function";function cond(e){var t=null==e?0:e.length,r=baseIteratee;return e=t?arrayMap(e,(function(e){if("function"!=typeof e[1])throw new TypeError(FUNC_ERROR_TEXT$7);return[r(e[0]),e[1]]})):[],baseRest((function(r){for(var i=-1;++i<t;){var n=e[i];if(apply(n[0],this,r))return apply(n[1],this,r)}}))}function baseConformsTo(e,t,r){var i=r.length;if(null==e)return!i;for(e=Object(e);i--;){var n=r[i],s=t[n],o=e[n];if(void 0===o&&!(n in e)||!s(o))return!1}return!0}function baseConforms(e){var t=keys(e);return function(r){return baseConformsTo(r,e,t)}}var CLONE_DEEP_FLAG$4=1;function conforms(e){return baseConforms(baseClone(e,CLONE_DEEP_FLAG$4))}function conformsTo(e,t){return null==t||baseConformsTo(e,t,keys(t))}function arrayAggregator(e,t,r,i){for(var n=-1,s=null==e?0:e.length;++n<s;){var o=e[n];t(i,o,r(o),e)}return i}function createBaseFor(e){return function(t,r,i){for(var n=-1,s=Object(t),o=i(t),a=o.length;a--;){var c=o[e?a:++n];if(!1===r(s[c],c,s))break}return t}}var baseFor=createBaseFor(),baseFor$1=baseFor;function baseForOwn(e,t){return e&&baseFor$1(e,t,keys)}function createBaseEach(e,t){return function(r,i){if(null==r)return r;if(!isArrayLike(r))return e(r,i);for(var n=r.length,s=t?n:-1,o=Object(r);(t?s--:++s<n)&&!1!==i(o[s],s,o););return r}}var baseEach=createBaseEach(baseForOwn),baseEach$1=baseEach;function baseAggregator(e,t,r,i){return baseEach$1(e,(function(e,n,s){t(i,e,r(e),s)})),i}function createAggregator(e,t){return function(r,i){var n=isArray$1(r)?arrayAggregator:baseAggregator,s=t?t():{};return n(r,e,baseIteratee(i),s)}}var objectProto$9=Object.prototype,hasOwnProperty$8=objectProto$9.hasOwnProperty,countBy=createAggregator((function(e,t,r){hasOwnProperty$8.call(e,r)?++e[r]:baseAssignValue(e,r,1)})),countBy$1=countBy;function create(e,t){var r=baseCreate$1(e);return null==t?r:baseAssign(r,t)}var WRAP_CURRY_FLAG$1=8;function curry(e,t,r){var i=createWrap(e,WRAP_CURRY_FLAG$1,void 0,void 0,void 0,void 0,void 0,t=r?void 0:t);return i.placeholder=curry.placeholder,i}curry.placeholder={};var WRAP_CURRY_RIGHT_FLAG=16;function curryRight(e,t,r){var i=createWrap(e,WRAP_CURRY_RIGHT_FLAG,void 0,void 0,void 0,void 0,void 0,t=r?void 0:t);return i.placeholder=curryRight.placeholder,i}curryRight.placeholder={};var now=function(){return root$1.Date.now()},now$1=now,FUNC_ERROR_TEXT$6="Expected a function",nativeMax$b=Math.max,nativeMin$b=Math.min;function debounce(e,t,r){var i,n,s,o,a,c,u=0,d=!1,l=!1,h=!0;if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT$6);function p(t){var r=i,s=n;return i=n=void 0,u=t,o=e.apply(s,r)}function m(e){return u=e,a=setTimeout(g,t),d?p(e):o}function f(e){var r=e-c;return void 0===c||r>=t||r<0||l&&e-u>=s}function g(){var e=now$1();if(f(e))return v(e);a=setTimeout(g,function(e){var r=t-(e-c);return l?nativeMin$b(r,s-(e-u)):r}(e))}function v(e){return a=void 0,h&&i?p(e):(i=n=void 0,o)}function y(){var e=now$1(),r=f(e);if(i=arguments,n=this,c=e,r){if(void 0===a)return m(c);if(l)return clearTimeout(a),a=setTimeout(g,t),p(c)}return void 0===a&&(a=setTimeout(g,t)),o}return t=toNumber(t)||0,isObject(r)&&(d=!!r.leading,s=(l="maxWait"in r)?nativeMax$b(toNumber(r.maxWait)||0,t):s,h="trailing"in r?!!r.trailing:h),y.cancel=function(){void 0!==a&&clearTimeout(a),u=0,i=c=n=a=void 0},y.flush=function(){return void 0===a?o:v(now$1())},y}function defaultTo(e,t){return null==e||e!=e?t:e}var objectProto$8=Object.prototype,hasOwnProperty$7=objectProto$8.hasOwnProperty,defaults=baseRest((function(e,t){e=Object(e);var r=-1,i=t.length,n=i>2?t[2]:void 0;for(n&&isIterateeCall(t[0],t[1],n)&&(i=1);++r<i;)for(var s=t[r],o=keysIn(s),a=-1,c=o.length;++a<c;){var u=o[a],d=e[u];(void 0===d||eq(d,objectProto$8[u])&&!hasOwnProperty$7.call(e,u))&&(e[u]=s[u])}return e})),defaults$1=defaults;function assignMergeValue(e,t,r){(void 0!==r&&!eq(e[t],r)||void 0===r&&!(t in e))&&baseAssignValue(e,t,r)}function isArrayLikeObject(e){return isObjectLike(e)&&isArrayLike(e)}function safeGet(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}function toPlainObject(e){return copyObject(e,keysIn(e))}function baseMergeDeep(e,t,r,i,n,s,o){var a=safeGet(e,r),c=safeGet(t,r),u=o.get(c);if(u)assignMergeValue(e,r,u);else{var d=s?s(a,c,r+"",e,t,o):void 0,l=void 0===d;if(l){var h=isArray$1(c),p=!h&&isBuffer$1(c),m=!h&&!p&&isTypedArray$1(c);d=c,h||p||m?isArray$1(a)?d=a:isArrayLikeObject(a)?d=copyArray(a):p?(l=!1,d=cloneBuffer(c,!0)):m?(l=!1,d=cloneTypedArray(c,!0)):d=[]:isPlainObject(c)||isArguments$1(c)?(d=a,isArguments$1(a)?d=toPlainObject(a):isObject(a)&&!isFunction$1(a)||(d=initCloneObject(c))):l=!1}l&&(o.set(c,d),n(d,c,i,s,o),o.delete(c)),assignMergeValue(e,r,d)}}function baseMerge(e,t,r,i,n){e!==t&&baseFor$1(t,(function(s,o){if(n||(n=new Stack),isObject(s))baseMergeDeep(e,t,o,r,baseMerge,i,n);else{var a=i?i(safeGet(e,o),s,o+"",e,t,n):void 0;void 0===a&&(a=s),assignMergeValue(e,o,a)}}),keysIn)}function customDefaultsMerge(e,t,r,i,n,s){return isObject(e)&&isObject(t)&&(s.set(t,e),baseMerge(e,t,void 0,customDefaultsMerge,s),s.delete(t)),e}var mergeWith=createAssigner((function(e,t,r,i){baseMerge(e,t,r,i)})),mergeWith$1=mergeWith,defaultsDeep=baseRest((function(e){return e.push(void 0,customDefaultsMerge),apply(mergeWith$1,void 0,e)})),defaultsDeep$1=defaultsDeep,FUNC_ERROR_TEXT$5="Expected a function";function baseDelay(e,t,r){if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT$5);return setTimeout((function(){e.apply(void 0,r)}),t)}var defer=baseRest((function(e,t){return baseDelay(e,1,t)})),defer$1=defer,delay=baseRest((function(e,t,r){return baseDelay(e,toNumber(t)||0,r)})),delay$1=delay;function arrayIncludesWith(e,t,r){for(var i=-1,n=null==e?0:e.length;++i<n;)if(r(t,e[i]))return!0;return!1}var LARGE_ARRAY_SIZE$1=200;function baseDifference(e,t,r,i){var n=-1,s=arrayIncludes,o=!0,a=e.length,c=[],u=t.length;if(!a)return c;r&&(t=arrayMap(t,baseUnary(r))),i?(s=arrayIncludesWith,o=!1):t.length>=LARGE_ARRAY_SIZE$1&&(s=cacheHas,o=!1,t=new SetCache(t));e:for(;++n<a;){var d=e[n],l=null==r?d:r(d);if(d=i||0!==d?d:0,o&&l==l){for(var h=u;h--;)if(t[h]===l)continue e;c.push(d)}else s(t,l,i)||c.push(d)}return c}var difference=baseRest((function(e,t){return isArrayLikeObject(e)?baseDifference(e,baseFlatten(t,1,isArrayLikeObject,!0)):[]})),difference$1=difference;function last(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}var differenceBy=baseRest((function(e,t){var r=last(t);return isArrayLikeObject(r)&&(r=void 0),isArrayLikeObject(e)?baseDifference(e,baseFlatten(t,1,isArrayLikeObject,!0),baseIteratee(r)):[]})),differenceBy$1=differenceBy,differenceWith=baseRest((function(e,t){var r=last(t);return isArrayLikeObject(r)&&(r=void 0),isArrayLikeObject(e)?baseDifference(e,baseFlatten(t,1,isArrayLikeObject,!0),void 0,r):[]})),differenceWith$1=differenceWith,divide=createMathOperation((function(e,t){return e/t}),1),divide$1=divide;function drop(e,t,r){var i=null==e?0:e.length;return i?baseSlice(e,(t=r||void 0===t?1:toInteger(t))<0?0:t,i):[]}function dropRight(e,t,r){var i=null==e?0:e.length;return i?baseSlice(e,0,(t=i-(t=r||void 0===t?1:toInteger(t)))<0?0:t):[]}function baseWhile(e,t,r,i){for(var n=e.length,s=i?n:-1;(i?s--:++s<n)&&t(e[s],s,e););return r?baseSlice(e,i?0:s,i?s+1:n):baseSlice(e,i?s+1:0,i?n:s)}function dropRightWhile(e,t){return e&&e.length?baseWhile(e,baseIteratee(t),!0,!0):[]}function dropWhile(e,t){return e&&e.length?baseWhile(e,baseIteratee(t),!0):[]}function castFunction(e){return"function"==typeof e?e:identity$1}function forEach(e,t){return(isArray$1(e)?arrayEach:baseEach$1)(e,castFunction(t))}function arrayEachRight(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}var baseForRight=createBaseFor(!0),baseForRight$1=baseForRight;function baseForOwnRight(e,t){return e&&baseForRight$1(e,t,keys)}var baseEachRight=createBaseEach(baseForOwnRight,!0),baseEachRight$1=baseEachRight;function forEachRight(e,t){return(isArray$1(e)?arrayEachRight:baseEachRight$1)(e,castFunction(t))}function endsWith(e,t,r){e=toString$1(e),t=baseToString(t);var i=e.length,n=r=void 0===r?i:baseClamp(toInteger(r),0,i);return(r-=t.length)>=0&&e.slice(r,n)==t}function baseToPairs(e,t){return arrayMap(t,(function(t){return[t,e[t]]}))}function setToPairs(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=[e,e]})),r}var mapTag$3="[object Map]",setTag$3="[object Set]";function createToPairs(e){return function(t){var r=getTag$1(t);return r==mapTag$3?mapToArray(t):r==setTag$3?setToPairs(t):baseToPairs(t,e(t))}}var toPairs=createToPairs(keys),toPairs$1=toPairs,toPairsIn=createToPairs(keysIn),toPairsIn$1=toPairsIn,htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},escapeHtmlChar=basePropertyOf(htmlEscapes),escapeHtmlChar$1=escapeHtmlChar,reUnescapedHtml=/[&<>"']/g,reHasUnescapedHtml=RegExp(reUnescapedHtml.source);function escape(e){return(e=toString$1(e))&&reHasUnescapedHtml.test(e)?e.replace(reUnescapedHtml,escapeHtmlChar$1):e}var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);function escapeRegExp(e){return(e=toString$1(e))&&reHasRegExpChar.test(e)?e.replace(reRegExpChar,"\\$&"):e}function arrayEvery(e,t){for(var r=-1,i=null==e?0:e.length;++r<i;)if(!t(e[r],r,e))return!1;return!0}function baseEvery(e,t){var r=!0;return baseEach$1(e,(function(e,i,n){return r=!!t(e,i,n)})),r}function every(e,t,r){var i=isArray$1(e)?arrayEvery:baseEvery;return r&&isIterateeCall(e,t,r)&&(t=void 0),i(e,baseIteratee(t))}var MAX_ARRAY_LENGTH$5=4294967295;function toLength(e){return e?baseClamp(toInteger(e),0,MAX_ARRAY_LENGTH$5):0}function baseFill(e,t,r,i){var n=e.length;for((r=toInteger(r))<0&&(r=-r>n?0:n+r),(i=void 0===i||i>n?n:toInteger(i))<0&&(i+=n),i=r>i?0:toLength(i);r<i;)e[r++]=t;return e}function fill(e,t,r,i){var n=null==e?0:e.length;return n?(r&&"number"!=typeof r&&isIterateeCall(e,t,r)&&(r=0,i=n),baseFill(e,t,r,i)):[]}function baseFilter(e,t){var r=[];return baseEach$1(e,(function(e,i,n){t(e,i,n)&&r.push(e)})),r}function filter(e,t){return(isArray$1(e)?arrayFilter:baseFilter)(e,baseIteratee(t))}function createFind(e){return function(t,r,i){var n=Object(t);if(!isArrayLike(t)){var s=baseIteratee(r);t=keys(t),r=function(e){return s(n[e],e,n)}}var o=e(t,r,i);return o>-1?n[s?t[o]:o]:void 0}}var nativeMax$a=Math.max;function findIndex(e,t,r){var i=null==e?0:e.length;if(!i)return-1;var n=null==r?0:toInteger(r);return n<0&&(n=nativeMax$a(i+n,0)),baseFindIndex(e,baseIteratee(t),n)}var find=createFind(findIndex),find$1=find;function baseFindKey(e,t,r){var i;return r(e,(function(e,r,n){if(t(e,r,n))return i=r,!1})),i}function findKey(e,t){return baseFindKey(e,baseIteratee(t),baseForOwn)}var nativeMax$9=Math.max,nativeMin$a=Math.min;function findLastIndex(e,t,r){var i=null==e?0:e.length;if(!i)return-1;var n=i-1;return void 0!==r&&(n=toInteger(r),n=r<0?nativeMax$9(i+n,0):nativeMin$a(n,i-1)),baseFindIndex(e,baseIteratee(t),n,!0)}var findLast=createFind(findLastIndex),findLast$1=findLast;function findLastKey(e,t){return baseFindKey(e,baseIteratee(t),baseForOwnRight)}function head(e){return e&&e.length?e[0]:void 0}function baseMap(e,t){var r=-1,i=isArrayLike(e)?Array(e.length):[];return baseEach$1(e,(function(e,n,s){i[++r]=t(e,n,s)})),i}function map(e,t){return(isArray$1(e)?arrayMap:baseMap)(e,baseIteratee(t))}function flatMap(e,t){return baseFlatten(map(e,t),1)}var INFINITY$2=1/0;function flatMapDeep(e,t){return baseFlatten(map(e,t),INFINITY$2)}function flatMapDepth(e,t,r){return r=void 0===r?1:toInteger(r),baseFlatten(map(e,t),r)}var INFINITY$1=1/0;function flattenDeep(e){return(null==e?0:e.length)?baseFlatten(e,INFINITY$1):[]}function flattenDepth(e,t){return(null==e?0:e.length)?baseFlatten(e,t=void 0===t?1:toInteger(t)):[]}var WRAP_FLIP_FLAG=512;function flip(e){return createWrap(e,WRAP_FLIP_FLAG)}var floor=createRound("floor"),floor$1=floor,FUNC_ERROR_TEXT$4="Expected a function",WRAP_CURRY_FLAG=8,WRAP_PARTIAL_FLAG$1=32,WRAP_ARY_FLAG=128,WRAP_REARG_FLAG$1=256;function createFlow(e){return flatRest((function(t){var r=t.length,i=r,n=LodashWrapper.prototype.thru;for(e&&t.reverse();i--;){var s=t[i];if("function"!=typeof s)throw new TypeError(FUNC_ERROR_TEXT$4);if(n&&!o&&"wrapper"==getFuncName(s))var o=new LodashWrapper([],!0)}for(i=o?i:r;++i<r;){var a=getFuncName(s=t[i]),c="wrapper"==a?getData$1(s):void 0;o=c&&isLaziable(c[0])&&c[1]==(WRAP_ARY_FLAG|WRAP_CURRY_FLAG|WRAP_PARTIAL_FLAG$1|WRAP_REARG_FLAG$1)&&!c[4].length&&1==c[9]?o[getFuncName(c[0])].apply(o,c[3]):1==s.length&&isLaziable(s)?o[a]():o.thru(s)}return function(){var e=arguments,i=e[0];if(o&&1==e.length&&isArray$1(i))return o.plant(i).value();for(var n=0,s=r?t[n].apply(this,e):i;++n<r;)s=t[n].call(this,s);return s}}))}var flow=createFlow(),flow$1=flow,flowRight=createFlow(!0),flowRight$1=flowRight;function forIn(e,t){return null==e?e:baseFor$1(e,castFunction(t),keysIn)}function forInRight(e,t){return null==e?e:baseForRight$1(e,castFunction(t),keysIn)}function forOwn(e,t){return e&&baseForOwn(e,castFunction(t))}function forOwnRight(e,t){return e&&baseForOwnRight(e,castFunction(t))}function fromPairs(e){for(var t=-1,r=null==e?0:e.length,i={};++t<r;){var n=e[t];i[n[0]]=n[1]}return i}function baseFunctions(e,t){return arrayFilter(t,(function(t){return isFunction$1(e[t])}))}function functions(e){return null==e?[]:baseFunctions(e,keys(e))}function functionsIn(e){return null==e?[]:baseFunctions(e,keysIn(e))}var objectProto$7=Object.prototype,hasOwnProperty$6=objectProto$7.hasOwnProperty,groupBy=createAggregator((function(e,t,r){hasOwnProperty$6.call(e,r)?e[r].push(t):baseAssignValue(e,r,[t])})),groupBy$1=groupBy;function baseGt(e,t){return e>t}function createRelationalOperation(e){return function(t,r){return"string"==typeof t&&"string"==typeof r||(t=toNumber(t),r=toNumber(r)),e(t,r)}}var gt=createRelationalOperation(baseGt),gt$1=gt,gte=createRelationalOperation((function(e,t){return e>=t})),gte$1=gte,objectProto$6=Object.prototype,hasOwnProperty$5=objectProto$6.hasOwnProperty;function baseHas(e,t){return null!=e&&hasOwnProperty$5.call(e,t)}function has$1(e,t){return null!=e&&hasPath(e,t,baseHas)}var nativeMax$8=Math.max,nativeMin$9=Math.min;function baseInRange(e,t,r){return e>=nativeMin$9(t,r)&&e<nativeMax$8(t,r)}function inRange(e,t,r){return t=toFinite(t),void 0===r?(r=t,t=0):r=toFinite(r),baseInRange(e=toNumber(e),t,r)}var stringTag="[object String]";function isString(e){return"string"==typeof e||!isArray$1(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag}function baseValues(e,t){return arrayMap(t,(function(t){return e[t]}))}function values(e){return null==e?[]:baseValues(e,keys(e))}var nativeMax$7=Math.max;function includes(e,t,r,i){e=isArrayLike(e)?e:values(e),r=r&&!i?toInteger(r):0;var n=e.length;return r<0&&(r=nativeMax$7(n+r,0)),isString(e)?r<=n&&e.indexOf(t,r)>-1:!!n&&baseIndexOf(e,t,r)>-1}var nativeMax$6=Math.max;function indexOf$2(e,t,r){var i=null==e?0:e.length;if(!i)return-1;var n=null==r?0:toInteger(r);return n<0&&(n=nativeMax$6(i+n,0)),baseIndexOf(e,t,n)}function initial(e){return(null==e?0:e.length)?baseSlice(e,0,-1):[]}var nativeMin$8=Math.min;function baseIntersection(e,t,r){for(var i=r?arrayIncludesWith:arrayIncludes,n=e[0].length,s=e.length,o=s,a=Array(s),c=1/0,u=[];o--;){var d=e[o];o&&t&&(d=arrayMap(d,baseUnary(t))),c=nativeMin$8(d.length,c),a[o]=!r&&(t||n>=120&&d.length>=120)?new SetCache(o&&d):void 0}d=e[0];var l=-1,h=a[0];e:for(;++l<n&&u.length<c;){var p=d[l],m=t?t(p):p;if(p=r||0!==p?p:0,!(h?cacheHas(h,m):i(u,m,r))){for(o=s;--o;){var f=a[o];if(!(f?cacheHas(f,m):i(e[o],m,r)))continue e}h&&h.push(m),u.push(p)}}return u}function castArrayLikeObject(e){return isArrayLikeObject(e)?e:[]}var intersection=baseRest((function(e){var t=arrayMap(e,castArrayLikeObject);return t.length&&t[0]===e[0]?baseIntersection(t):[]})),intersection$1=intersection,intersectionBy=baseRest((function(e){var t=last(e),r=arrayMap(e,castArrayLikeObject);return t===last(r)?t=void 0:r.pop(),r.length&&r[0]===e[0]?baseIntersection(r,baseIteratee(t)):[]})),intersectionBy$1=intersectionBy,intersectionWith=baseRest((function(e){var t=last(e),r=arrayMap(e,castArrayLikeObject);return(t="function"==typeof t?t:void 0)&&r.pop(),r.length&&r[0]===e[0]?baseIntersection(r,void 0,t):[]})),intersectionWith$1=intersectionWith;function baseInverter(e,t,r,i){return baseForOwn(e,(function(e,n,s){t(i,r(e),n,s)})),i}function createInverter(e,t){return function(r,i){return baseInverter(r,e,t(i),{})}}var objectProto$5=Object.prototype,nativeObjectToString$1=objectProto$5.toString,invert=createInverter((function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=nativeObjectToString$1.call(t)),e[t]=r}),constant(identity$1)),invert$1=invert,objectProto$4=Object.prototype,hasOwnProperty$4=objectProto$4.hasOwnProperty,nativeObjectToString=objectProto$4.toString,invertBy=createInverter((function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=nativeObjectToString.call(t)),hasOwnProperty$4.call(e,t)?e[t].push(r):e[t]=[r]}),baseIteratee),invertBy$1=invertBy;function parent(e,t){return t.length<2?e:baseGet(e,baseSlice(t,0,-1))}function baseInvoke(e,t,r){var i=null==(e=parent(e,t=castPath(t,e)))?e:e[toKey(last(t))];return null==i?void 0:apply(i,e,r)}var invoke=baseRest(baseInvoke),invoke$1=invoke,invokeMap=baseRest((function(e,t,r){var i=-1,n="function"==typeof t,s=isArrayLike(e)?Array(e.length):[];return baseEach$1(e,(function(e){s[++i]=n?apply(t,e,r):baseInvoke(e,t,r)})),s})),invokeMap$1=invokeMap,arrayBufferTag="[object ArrayBuffer]";function baseIsArrayBuffer(e){return isObjectLike(e)&&baseGetTag(e)==arrayBufferTag}var nodeIsArrayBuffer=nodeUtil$1&&nodeUtil$1.isArrayBuffer,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isArrayBuffer$1=isArrayBuffer,boolTag="[object Boolean]";function isBoolean(e){return!0===e||!1===e||isObjectLike(e)&&baseGetTag(e)==boolTag}var dateTag="[object Date]";function baseIsDate(e){return isObjectLike(e)&&baseGetTag(e)==dateTag}var nodeIsDate=nodeUtil$1&&nodeUtil$1.isDate,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isDate$1=isDate;function isElement(e){return isObjectLike(e)&&1===e.nodeType&&!isPlainObject(e)}var mapTag$2="[object Map]",setTag$2="[object Set]",objectProto$3=Object.prototype,hasOwnProperty$3=objectProto$3.hasOwnProperty;function isEmpty(e){if(null==e)return!0;if(isArrayLike(e)&&(isArray$1(e)||"string"==typeof e||"function"==typeof e.splice||isBuffer$1(e)||isTypedArray$1(e)||isArguments$1(e)))return!e.length;var t=getTag$1(e);if(t==mapTag$2||t==setTag$2)return!e.size;if(isPrototype(e))return!baseKeys(e).length;for(var r in e)if(hasOwnProperty$3.call(e,r))return!1;return!0}function isEqual(e,t){return baseIsEqual(e,t)}function isEqualWith(e,t,r){var i=(r="function"==typeof r?r:void 0)?r(e,t):void 0;return void 0===i?baseIsEqual(e,t,void 0,r):!!i}var nativeIsFinite=root$1.isFinite;function isFinite$1(e){return"number"==typeof e&&nativeIsFinite(e)}function isInteger(e){return"number"==typeof e&&e==toInteger(e)}function isMatch(e,t){return e===t||baseIsMatch(e,t,getMatchData(t))}function isMatchWith(e,t,r){return r="function"==typeof r?r:void 0,baseIsMatch(e,t,getMatchData(t),r)}var numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}function isNaN$1(e){return isNumber(e)&&e!=+e}var isMaskable=coreJsData$1?isFunction$1:stubFalse,isMaskable$1=isMaskable,CORE_ERROR_TEXT="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.";function isNative$1(e){if(isMaskable$1(e))throw new Error(CORE_ERROR_TEXT);return baseIsNative(e)}function isNil(e){return null==e}function isNull(e){return null===e}var regexpTag="[object RegExp]";function baseIsRegExp(e){return isObjectLike(e)&&baseGetTag(e)==regexpTag}var nodeIsRegExp=nodeUtil$1&&nodeUtil$1.isRegExp,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isRegExp$1=isRegExp,MAX_SAFE_INTEGER$3=9007199254740991;function isSafeInteger(e){return isInteger(e)&&e>=-MAX_SAFE_INTEGER$3&&e<=MAX_SAFE_INTEGER$3}function isUndefined(e){return void 0===e}var weakMapTag="[object WeakMap]";function isWeakMap(e){return isObjectLike(e)&&getTag$1(e)==weakMapTag}var weakSetTag="[object WeakSet]";function isWeakSet(e){return isObjectLike(e)&&baseGetTag(e)==weakSetTag}var CLONE_DEEP_FLAG$3=1;function iteratee(e){return baseIteratee("function"==typeof e?e:baseClone(e,CLONE_DEEP_FLAG$3))}var arrayProto$4=Array.prototype,nativeJoin=arrayProto$4.join;function join(e,t){return null==e?"":nativeJoin.call(e,t)}var kebabCase=createCompounder((function(e,t,r){return e+(r?"-":"")+t.toLowerCase()})),kebabCase$1=kebabCase,keyBy=createAggregator((function(e,t,r){baseAssignValue(e,r,t)})),keyBy$1=keyBy;function strictLastIndexOf(e,t,r){for(var i=r+1;i--;)if(e[i]===t)return i;return i}var nativeMax$5=Math.max,nativeMin$7=Math.min;function lastIndexOf(e,t,r){var i=null==e?0:e.length;if(!i)return-1;var n=i;return void 0!==r&&(n=(n=toInteger(r))<0?nativeMax$5(i+n,0):nativeMin$7(n,i-1)),t==t?strictLastIndexOf(e,t,n):baseFindIndex(e,baseIsNaN,n,!0)}var lowerCase=createCompounder((function(e,t,r){return e+(r?" ":"")+t.toLowerCase()})),lowerCase$1=lowerCase,lowerFirst=createCaseFirst("toLowerCase"),lowerFirst$1=lowerFirst;function baseLt(e,t){return e<t}var lt=createRelationalOperation(baseLt),lt$1=lt,lte=createRelationalOperation((function(e,t){return e<=t})),lte$1=lte;function mapKeys(e,t){var r={};return t=baseIteratee(t),baseForOwn(e,(function(e,i,n){baseAssignValue(r,t(e,i,n),e)})),r}function mapValues(e,t){var r={};return t=baseIteratee(t),baseForOwn(e,(function(e,i,n){baseAssignValue(r,i,t(e,i,n))})),r}var CLONE_DEEP_FLAG$2=1;function matches(e){return baseMatches(baseClone(e,CLONE_DEEP_FLAG$2))}var CLONE_DEEP_FLAG$1=1;function matchesProperty(e,t){return baseMatchesProperty(e,baseClone(t,CLONE_DEEP_FLAG$1))}function baseExtremum(e,t,r){for(var i=-1,n=e.length;++i<n;){var s=e[i],o=t(s);if(null!=o&&(void 0===a?o==o&&!isSymbol(o):r(o,a)))var a=o,c=s}return c}function max(e){return e&&e.length?baseExtremum(e,identity$1,baseGt):void 0}function maxBy(e,t){return e&&e.length?baseExtremum(e,baseIteratee(t),baseGt):void 0}function baseSum(e,t){for(var r,i=-1,n=e.length;++i<n;){var s=t(e[i]);void 0!==s&&(r=void 0===r?s:r+s)}return r}var NAN=NaN;function baseMean(e,t){var r=null==e?0:e.length;return r?baseSum(e,t)/r:NAN}function mean(e){return baseMean(e,identity$1)}function meanBy(e,t){return baseMean(e,baseIteratee(t))}var merge=createAssigner((function(e,t,r){baseMerge(e,t,r)})),merge$1=merge,method=baseRest((function(e,t){return function(r){return baseInvoke(r,e,t)}})),method$1=method,methodOf=baseRest((function(e,t){return function(r){return baseInvoke(e,r,t)}})),methodOf$1=methodOf;function min(e){return e&&e.length?baseExtremum(e,identity$1,baseLt):void 0}function minBy(e,t){return e&&e.length?baseExtremum(e,baseIteratee(t),baseLt):void 0}function mixin$1(e,t,r){var i=keys(t),n=baseFunctions(t,i),s=!(isObject(r)&&"chain"in r&&!r.chain),o=isFunction$1(e);return arrayEach(n,(function(r){var i=t[r];e[r]=i,o&&(e.prototype[r]=function(){var t=this.__chain__;if(s||t){var r=e(this.__wrapped__),n=r.__actions__=copyArray(this.__actions__);return n.push({func:i,args:arguments,thisArg:e}),r.__chain__=t,r}return i.apply(e,arrayPush([this.value()],arguments))})})),e}var multiply=createMathOperation((function(e,t){return e*t}),1),multiply$1=multiply,FUNC_ERROR_TEXT$3="Expected a function";function negate(e){if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT$3);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}function iteratorToArray(e){for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r}var mapTag$1="[object Map]",setTag$1="[object Set]",symIterator$1=Symbol$2?Symbol$2.iterator:void 0;function toArray(e){if(!e)return[];if(isArrayLike(e))return isString(e)?stringToArray(e):copyArray(e);if(symIterator$1&&e[symIterator$1])return iteratorToArray(e[symIterator$1]());var t=getTag$1(e);return(t==mapTag$1?mapToArray:t==setTag$1?setToArray:values)(e)}function wrapperNext(){void 0===this.__values__&&(this.__values__=toArray(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?void 0:this.__values__[this.__index__++]}}function baseNth(e,t){var r=e.length;if(r)return isIndex(t+=t<0?r:0,r)?e[t]:void 0}function nth(e,t){return e&&e.length?baseNth(e,toInteger(t)):void 0}function nthArg(e){return e=toInteger(e),baseRest((function(t){return baseNth(t,e)}))}function baseUnset(e,t){return null==(e=parent(e,t=castPath(t,e)))||delete e[toKey(last(t))]}function customOmitClone(e){return isPlainObject(e)?void 0:e}var CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4,omit=flatRest((function(e,t){var r={};if(null==e)return r;var i=!1;t=arrayMap(t,(function(t){return t=castPath(t,e),i||(i=t.length>1),t})),copyObject(e,getAllKeysIn(e),r),i&&(r=baseClone(r,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG,customOmitClone));for(var n=t.length;n--;)baseUnset(r,t[n]);return r})),omit$1=omit;function baseSet(e,t,r,i){if(!isObject(e))return e;for(var n=-1,s=(t=castPath(t,e)).length,o=s-1,a=e;null!=a&&++n<s;){var c=toKey(t[n]),u=r;if("__proto__"===c||"constructor"===c||"prototype"===c)return e;if(n!=o){var d=a[c];void 0===(u=i?i(d,c,a):void 0)&&(u=isObject(d)?d:isIndex(t[n+1])?[]:{})}assignValue(a,c,u),a=a[c]}return e}function basePickBy(e,t,r){for(var i=-1,n=t.length,s={};++i<n;){var o=t[i],a=baseGet(e,o);r(a,o)&&baseSet(s,castPath(o,e),a)}return s}function pickBy(e,t){if(null==e)return{};var r=arrayMap(getAllKeysIn(e),(function(e){return[e]}));return t=baseIteratee(t),basePickBy(e,r,(function(e,r){return t(e,r[0])}))}function omitBy(e,t){return pickBy(e,negate(baseIteratee(t)))}function once$1(e){return before(2,e)}function baseSortBy(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}function compareAscending(e,t){if(e!==t){var r=void 0!==e,i=null===e,n=e==e,s=isSymbol(e),o=void 0!==t,a=null===t,c=t==t,u=isSymbol(t);if(!a&&!u&&!s&&e>t||s&&o&&c&&!a&&!u||i&&o&&c||!r&&c||!n)return 1;if(!i&&!s&&!u&&e<t||u&&r&&n&&!i&&!s||a&&r&&n||!o&&n||!c)return-1}return 0}function compareMultiple(e,t,r){for(var i=-1,n=e.criteria,s=t.criteria,o=n.length,a=r.length;++i<o;){var c=compareAscending(n[i],s[i]);if(c)return i>=a?c:c*("desc"==r[i]?-1:1)}return e.index-t.index}function baseOrderBy(e,t,r){t=t.length?arrayMap(t,(function(e){return isArray$1(e)?function(t){return baseGet(t,1===e.length?e[0]:e)}:e})):[identity$1];var i=-1;t=arrayMap(t,baseUnary(baseIteratee));var n=baseMap(e,(function(e,r,n){var s=arrayMap(t,(function(t){return t(e)}));return{criteria:s,index:++i,value:e}}));return baseSortBy(n,(function(e,t){return compareMultiple(e,t,r)}))}function orderBy(e,t,r,i){return null==e?[]:(isArray$1(t)||(t=null==t?[]:[t]),isArray$1(r=i?void 0:r)||(r=null==r?[]:[r]),baseOrderBy(e,t,r))}function createOver(e){return flatRest((function(t){return t=arrayMap(t,baseUnary(baseIteratee)),baseRest((function(r){var i=this;return e(t,(function(e){return apply(e,i,r)}))}))}))}var over=createOver(arrayMap),over$1=over,castRest=baseRest,castRest$1=castRest,nativeMin$6=Math.min,overArgs=castRest$1((function(e,t){var r=(t=1==t.length&&isArray$1(t[0])?arrayMap(t[0],baseUnary(baseIteratee)):arrayMap(baseFlatten(t,1),baseUnary(baseIteratee))).length;return baseRest((function(i){for(var n=-1,s=nativeMin$6(i.length,r);++n<s;)i[n]=t[n].call(this,i[n]);return apply(e,this,i)}))})),overArgs$1=overArgs,overEvery=createOver(arrayEvery),overEvery$1=overEvery,overSome=createOver(arraySome),overSome$1=overSome,MAX_SAFE_INTEGER$2=9007199254740991,nativeFloor$3=Math.floor;function baseRepeat(e,t){var r="";if(!e||t<1||t>MAX_SAFE_INTEGER$2)return r;do{t%2&&(r+=e),(t=nativeFloor$3(t/2))&&(e+=e)}while(t);return r}var asciiSize=baseProperty("length"),asciiSize$1=asciiSize,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsAstral="["+rsAstralRange+"]",rsCombo="["+rsComboRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsZWJ="\\u200d",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeSize(e){for(var t=reUnicode.lastIndex=0;reUnicode.test(e);)++t;return t}function stringSize(e){return hasUnicode(e)?unicodeSize(e):asciiSize$1(e)}var nativeCeil$2=Math.ceil;function createPadding(e,t){var r=(t=void 0===t?" ":baseToString(t)).length;if(r<2)return r?baseRepeat(t,e):t;var i=baseRepeat(t,nativeCeil$2(e/stringSize(t)));return hasUnicode(t)?castSlice(stringToArray(i),0,e).join(""):i.slice(0,e)}var nativeCeil$1=Math.ceil,nativeFloor$2=Math.floor;function pad(e,t,r){e=toString$1(e);var i=(t=toInteger(t))?stringSize(e):0;if(!t||i>=t)return e;var n=(t-i)/2;return createPadding(nativeFloor$2(n),r)+e+createPadding(nativeCeil$1(n),r)}function padEnd(e,t,r){e=toString$1(e);var i=(t=toInteger(t))?stringSize(e):0;return t&&i<t?e+createPadding(t-i,r):e}function padStart(e,t,r){e=toString$1(e);var i=(t=toInteger(t))?stringSize(e):0;return t&&i<t?createPadding(t-i,r)+e:e}var reTrimStart$1=/^\s+/,nativeParseInt=root$1.parseInt;function parseInt$1(e,t,r){return r||null==t?t=0:t&&(t=+t),nativeParseInt(toString$1(e).replace(reTrimStart$1,""),t||0)}var WRAP_PARTIAL_FLAG=32,partial=baseRest((function(e,t){var r=replaceHolders(t,getHolder(partial));return createWrap(e,WRAP_PARTIAL_FLAG,void 0,t,r)}));partial.placeholder={};var partial$1=partial,WRAP_PARTIAL_RIGHT_FLAG=64,partialRight=baseRest((function(e,t){var r=replaceHolders(t,getHolder(partialRight));return createWrap(e,WRAP_PARTIAL_RIGHT_FLAG,void 0,t,r)}));partialRight.placeholder={};var partialRight$1=partialRight,partition=createAggregator((function(e,t,r){e[r?0:1].push(t)}),(function(){return[[],[]]})),partition$1=partition;function basePick(e,t){return basePickBy(e,t,(function(t,r){return hasIn(e,r)}))}var pick=flatRest((function(e,t){return null==e?{}:basePick(e,t)})),pick$1=pick;function wrapperPlant(e){for(var t,r=this;r instanceof baseLodash;){var i=wrapperClone(r);i.__index__=0,i.__values__=void 0,t?n.__wrapped__=i:t=i;var n=i;r=r.__wrapped__}return n.__wrapped__=e,t}function propertyOf(e){return function(t){return null==e?void 0:baseGet(e,t)}}function baseIndexOfWith(e,t,r,i){for(var n=r-1,s=e.length;++n<s;)if(i(e[n],t))return n;return-1}var arrayProto$3=Array.prototype,splice$1=arrayProto$3.splice;function basePullAll(e,t,r,i){var n=i?baseIndexOfWith:baseIndexOf,s=-1,o=t.length,a=e;for(e===t&&(t=copyArray(t)),r&&(a=arrayMap(e,baseUnary(r)));++s<o;)for(var c=0,u=t[s],d=r?r(u):u;(c=n(a,d,c,i))>-1;)a!==e&&splice$1.call(a,c,1),splice$1.call(e,c,1);return e}function pullAll(e,t){return e&&e.length&&t&&t.length?basePullAll(e,t):e}var pull=baseRest(pullAll),pull$1=pull;function pullAllBy(e,t,r){return e&&e.length&&t&&t.length?basePullAll(e,t,baseIteratee(r)):e}function pullAllWith(e,t,r){return e&&e.length&&t&&t.length?basePullAll(e,t,void 0,r):e}var arrayProto$2=Array.prototype,splice=arrayProto$2.splice;function basePullAt(e,t){for(var r=e?t.length:0,i=r-1;r--;){var n=t[r];if(r==i||n!==s){var s=n;isIndex(n)?splice.call(e,n,1):baseUnset(e,n)}}return e}var pullAt=flatRest((function(e,t){var r=null==e?0:e.length,i=baseAt(e,t);return basePullAt(e,arrayMap(t,(function(e){return isIndex(e,r)?+e:e})).sort(compareAscending)),i})),pullAt$1=pullAt,nativeFloor$1=Math.floor,nativeRandom$1=Math.random;function baseRandom(e,t){return e+nativeFloor$1(nativeRandom$1()*(t-e+1))}var freeParseFloat=parseFloat,nativeMin$5=Math.min,nativeRandom=Math.random;function random(e,t,r){if(r&&"boolean"!=typeof r&&isIterateeCall(e,t,r)&&(t=r=void 0),void 0===r&&("boolean"==typeof t?(r=t,t=void 0):"boolean"==typeof e&&(r=e,e=void 0)),void 0===e&&void 0===t?(e=0,t=1):(e=toFinite(e),void 0===t?(t=e,e=0):t=toFinite(t)),e>t){var i=e;e=t,t=i}if(r||e%1||t%1){var n=nativeRandom();return nativeMin$5(e+n*(t-e+freeParseFloat("1e-"+((n+"").length-1))),t)}return baseRandom(e,t)}var nativeCeil=Math.ceil,nativeMax$4=Math.max;function baseRange(e,t,r,i){for(var n=-1,s=nativeMax$4(nativeCeil((t-e)/(r||1)),0),o=Array(s);s--;)o[i?s:++n]=e,e+=r;return o}function createRange(e){return function(t,r,i){return i&&"number"!=typeof i&&isIterateeCall(t,r,i)&&(r=i=void 0),t=toFinite(t),void 0===r?(r=t,t=0):r=toFinite(r),baseRange(t,r,i=void 0===i?t<r?1:-1:toFinite(i),e)}}var range=createRange(),range$1=range,rangeRight=createRange(!0),rangeRight$1=rangeRight,WRAP_REARG_FLAG=256,rearg=flatRest((function(e,t){return createWrap(e,WRAP_REARG_FLAG,void 0,void 0,void 0,t)})),rearg$1=rearg;function baseReduce(e,t,r,i,n){return n(e,(function(e,n,s){r=i?(i=!1,e):t(r,e,n,s)})),r}function reduce(e,t,r){var i=isArray$1(e)?arrayReduce:baseReduce,n=arguments.length<3;return i(e,baseIteratee(t),r,n,baseEach$1)}function arrayReduceRight(e,t,r,i){var n=null==e?0:e.length;for(i&&n&&(r=e[--n]);n--;)r=t(r,e[n],n,e);return r}function reduceRight(e,t,r){var i=isArray$1(e)?arrayReduceRight:baseReduce,n=arguments.length<3;return i(e,baseIteratee(t),r,n,baseEachRight$1)}function reject$1(e,t){return(isArray$1(e)?arrayFilter:baseFilter)(e,negate(baseIteratee(t)))}function remove(e,t){var r=[];if(!e||!e.length)return r;var i=-1,n=[],s=e.length;for(t=baseIteratee(t);++i<s;){var o=e[i];t(o,i,e)&&(r.push(o),n.push(i))}return basePullAt(e,n),r}function repeat(e,t,r){return t=(r?isIterateeCall(e,t,r):void 0===t)?1:toInteger(t),baseRepeat(toString$1(e),t)}function replace(){var e=arguments,t=toString$1(e[0]);return e.length<3?t:t.replace(e[1],e[2])}var FUNC_ERROR_TEXT$2="Expected a function";function rest(e,t){if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT$2);return baseRest(e,t=void 0===t?t:toInteger(t))}function result(e,t,r){var i=-1,n=(t=castPath(t,e)).length;for(n||(n=1,e=void 0);++i<n;){var s=null==e?void 0:e[toKey(t[i])];void 0===s&&(i=n,s=r),e=isFunction$1(s)?s.call(e):s}return e}var arrayProto$1=Array.prototype,nativeReverse=arrayProto$1.reverse;function reverse(e){return null==e?e:nativeReverse.call(e)}var round=createRound("round"),round$1=round;function arraySample(e){var t=e.length;return t?e[baseRandom(0,t-1)]:void 0}function baseSample(e){return arraySample(values(e))}function sample(e){return(isArray$1(e)?arraySample:baseSample)(e)}function shuffleSelf(e,t){var r=-1,i=e.length,n=i-1;for(t=void 0===t?i:t;++r<t;){var s=baseRandom(r,n),o=e[s];e[s]=e[r],e[r]=o}return e.length=t,e}function arraySampleSize(e,t){return shuffleSelf(copyArray(e),baseClamp(t,0,e.length))}function baseSampleSize(e,t){var r=values(e);return shuffleSelf(r,baseClamp(t,0,r.length))}function sampleSize(e,t,r){return t=(r?isIterateeCall(e,t,r):void 0===t)?1:toInteger(t),(isArray$1(e)?arraySampleSize:baseSampleSize)(e,t)}function set(e,t,r){return null==e?e:baseSet(e,t,r)}function setWith(e,t,r,i){return i="function"==typeof i?i:void 0,null==e?e:baseSet(e,t,r,i)}function arrayShuffle(e){return shuffleSelf(copyArray(e))}function baseShuffle(e){return shuffleSelf(values(e))}function shuffle(e){return(isArray$1(e)?arrayShuffle:baseShuffle)(e)}var mapTag="[object Map]",setTag="[object Set]";function size(e){if(null==e)return 0;if(isArrayLike(e))return isString(e)?stringSize(e):e.length;var t=getTag$1(e);return t==mapTag||t==setTag?e.size:baseKeys(e).length}function slice(e,t,r){var i=null==e?0:e.length;return i?(r&&"number"!=typeof r&&isIterateeCall(e,t,r)?(t=0,r=i):(t=null==t?0:toInteger(t),r=void 0===r?i:toInteger(r)),baseSlice(e,t,r)):[]}var snakeCase=createCompounder((function(e,t,r){return e+(r?"_":"")+t.toLowerCase()})),snakeCase$1=snakeCase;function baseSome(e,t){var r;return baseEach$1(e,(function(e,i,n){return!(r=t(e,i,n))})),!!r}function some(e,t,r){var i=isArray$1(e)?arraySome:baseSome;return r&&isIterateeCall(e,t,r)&&(t=void 0),i(e,baseIteratee(t))}var sortBy=baseRest((function(e,t){if(null==e)return[];var r=t.length;return r>1&&isIterateeCall(e,t[0],t[1])?t=[]:r>2&&isIterateeCall(t[0],t[1],t[2])&&(t=[t[0]]),baseOrderBy(e,baseFlatten(t,1),[])})),sortBy$1=sortBy,MAX_ARRAY_LENGTH$4=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH$4-1,nativeFloor=Math.floor,nativeMin$4=Math.min;function baseSortedIndexBy(e,t,r,i){var n=0,s=null==e?0:e.length;if(0===s)return 0;for(var o=(t=r(t))!=t,a=null===t,c=isSymbol(t),u=void 0===t;n<s;){var d=nativeFloor((n+s)/2),l=r(e[d]),h=void 0!==l,p=null===l,m=l==l,f=isSymbol(l);if(o)var g=i||m;else g=u?m&&(i||h):a?m&&h&&(i||!p):c?m&&h&&!p&&(i||!f):!p&&!f&&(i?l<=t:l<t);g?n=d+1:s=d}return nativeMin$4(s,MAX_ARRAY_INDEX)}var MAX_ARRAY_LENGTH$3=4294967295,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH$3>>>1;function baseSortedIndex(e,t,r){var i=0,n=null==e?i:e.length;if("number"==typeof t&&t==t&&n<=HALF_MAX_ARRAY_LENGTH){for(;i<n;){var s=i+n>>>1,o=e[s];null!==o&&!isSymbol(o)&&(r?o<=t:o<t)?i=s+1:n=s}return n}return baseSortedIndexBy(e,t,identity$1,r)}function sortedIndex(e,t){return baseSortedIndex(e,t)}function sortedIndexBy(e,t,r){return baseSortedIndexBy(e,t,baseIteratee(r))}function sortedIndexOf(e,t){var r=null==e?0:e.length;if(r){var i=baseSortedIndex(e,t);if(i<r&&eq(e[i],t))return i}return-1}function sortedLastIndex(e,t){return baseSortedIndex(e,t,!0)}function sortedLastIndexBy(e,t,r){return baseSortedIndexBy(e,t,baseIteratee(r),!0)}function sortedLastIndexOf(e,t){if(null==e?0:e.length){var r=baseSortedIndex(e,t,!0)-1;if(eq(e[r],t))return r}return-1}function baseSortedUniq(e,t){for(var r=-1,i=e.length,n=0,s=[];++r<i;){var o=e[r],a=t?t(o):o;if(!r||!eq(a,c)){var c=a;s[n++]=0===o?0:o}}return s}function sortedUniq(e){return e&&e.length?baseSortedUniq(e):[]}function sortedUniqBy(e,t){return e&&e.length?baseSortedUniq(e,baseIteratee(t)):[]}var MAX_ARRAY_LENGTH$2=4294967295;function split(e,t,r){return r&&"number"!=typeof r&&isIterateeCall(e,t,r)&&(t=r=void 0),(r=void 0===r?MAX_ARRAY_LENGTH$2:r>>>0)?(e=toString$1(e))&&("string"==typeof t||null!=t&&!isRegExp$1(t))&&!(t=baseToString(t))&&hasUnicode(e)?castSlice(stringToArray(e),0,r):e.split(t,r):[]}var FUNC_ERROR_TEXT$1="Expected a function",nativeMax$3=Math.max;function spread(e,t){if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT$1);return t=null==t?0:nativeMax$3(toInteger(t),0),baseRest((function(r){var i=r[t],n=castSlice(r,0,t);return i&&arrayPush(n,i),apply(e,this,n)}))}var startCase=createCompounder((function(e,t,r){return e+(r?" ":"")+upperFirst$1(t)})),startCase$1=startCase;function startsWith(e,t,r){return e=toString$1(e),r=null==r?0:baseClamp(toInteger(r),0,e.length),t=baseToString(t),e.slice(r,r+t.length)==t}function stubObject(){return{}}function stubString(){return""}function stubTrue(){return!0}var subtract=createMathOperation((function(e,t){return e-t}),0),subtract$1=subtract;function sum(e){return e&&e.length?baseSum(e,identity$1):0}function sumBy(e,t){return e&&e.length?baseSum(e,baseIteratee(t)):0}function tail(e){var t=null==e?0:e.length;return t?baseSlice(e,1,t):[]}function take(e,t,r){return e&&e.length?baseSlice(e,0,(t=r||void 0===t?1:toInteger(t))<0?0:t):[]}function takeRight(e,t,r){var i=null==e?0:e.length;return i?baseSlice(e,(t=i-(t=r||void 0===t?1:toInteger(t)))<0?0:t,i):[]}function takeRightWhile(e,t){return e&&e.length?baseWhile(e,baseIteratee(t),!1,!0):[]}function takeWhile(e,t){return e&&e.length?baseWhile(e,baseIteratee(t)):[]}function tap(e,t){return t(e),e}var objectProto$2=Object.prototype,hasOwnProperty$2=objectProto$2.hasOwnProperty;function customDefaultsAssignIn(e,t,r,i){return void 0===e||eq(e,objectProto$2[r])&&!hasOwnProperty$2.call(i,r)?t:e}var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"};function escapeStringChar(e){return"\\"+stringEscapes[e]}var reInterpolate=/<%=([\s\S]+?)%>/g,reInterpolate$1=reInterpolate,reEscape=/<%-([\s\S]+?)%>/g,reEscape$1=reEscape,reEvaluate=/<%([\s\S]+?)%>/g,reEvaluate$1=reEvaluate,templateSettings={escape:reEscape$1,evaluate:reEvaluate$1,interpolate:reInterpolate$1,variable:"",imports:{_:{escape:escape}}},templateSettings$1=templateSettings,INVALID_TEMPL_VAR_ERROR_TEXT="Invalid `variable` option passed into `_.template`",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reForbiddenIdentifierChars=/[()=,{}\[\]\/\s]/,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,objectProto$1=Object.prototype,hasOwnProperty$1=objectProto$1.hasOwnProperty;function template(e,t,r){var i=templateSettings$1.imports._.templateSettings||templateSettings$1;r&&isIterateeCall(e,t,r)&&(t=void 0),e=toString$1(e),t=extendWith({},t,i,customDefaultsAssignIn);var n,s,o=extendWith({},t.imports,i.imports,customDefaultsAssignIn),a=keys(o),c=baseValues(o,a),u=0,d=t.interpolate||reNoMatch,l="__p += '",h=RegExp((t.escape||reNoMatch).source+"|"+d.source+"|"+(d===reInterpolate$1?reEsTemplate:reNoMatch).source+"|"+(t.evaluate||reNoMatch).source+"|$","g"),p=hasOwnProperty$1.call(t,"sourceURL")?"//# sourceURL="+(t.sourceURL+"").replace(/\s/g," ")+"\n":"";e.replace(h,(function(t,r,i,o,a,c){return i||(i=o),l+=e.slice(u,c).replace(reUnescapedString,escapeStringChar),r&&(n=!0,l+="' +\n__e("+r+") +\n'"),a&&(s=!0,l+="';\n"+a+";\n__p += '"),i&&(l+="' +\n((__t = ("+i+")) == null ? '' : __t) +\n'"),u=c+t.length,t})),l+="';\n";var m=hasOwnProperty$1.call(t,"variable")&&t.variable;if(m){if(reForbiddenIdentifierChars.test(m))throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT)}else l="with (obj) {\n"+l+"\n}\n";l=(s?l.replace(reEmptyStringLeading,""):l).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),l="function("+(m||"obj")+") {\n"+(m?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(n?", __e = _.escape":"")+(s?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+l+"return __p\n}";var f=attempt$1((function(){return Function(a,p+"return "+l).apply(void 0,c)}));if(f.source=l,isError(f))throw f;return f}var FUNC_ERROR_TEXT="Expected a function";function throttle(e,t,r){var i=!0,n=!0;if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT);return isObject(r)&&(i="leading"in r?!!r.leading:i,n="trailing"in r?!!r.trailing:n),debounce(e,t,{leading:i,maxWait:t,trailing:n})}function thru(e,t){return t(e)}var MAX_SAFE_INTEGER$1=9007199254740991,MAX_ARRAY_LENGTH$1=4294967295,nativeMin$3=Math.min;function times(e,t){if((e=toInteger(e))<1||e>MAX_SAFE_INTEGER$1)return[];var r=MAX_ARRAY_LENGTH$1,i=nativeMin$3(e,MAX_ARRAY_LENGTH$1);t=castFunction(t),e-=MAX_ARRAY_LENGTH$1;for(var n=baseTimes(i,t);++r<e;)t(r);return n}function wrapperToIterator(){return this}function baseWrapperValue(e,t){var r=e;return r instanceof LazyWrapper&&(r=r.value()),arrayReduce(t,(function(e,t){return t.func.apply(t.thisArg,arrayPush([e],t.args))}),r)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function toLower(e){return toString$1(e).toLowerCase()}function toPath(e){return isArray$1(e)?arrayMap(e,toKey):isSymbol(e)?[e]:copyArray(stringToPath$1(toString$1(e)))}var MAX_SAFE_INTEGER=9007199254740991;function toSafeInteger(e){return e?baseClamp(toInteger(e),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER):0===e?e:0}function toUpper(e){return toString$1(e).toUpperCase()}function transform(e,t,r){var i=isArray$1(e),n=i||isBuffer$1(e)||isTypedArray$1(e);if(t=baseIteratee(t),null==r){var s=e&&e.constructor;r=n?i?new s:[]:isObject(e)&&isFunction$1(s)?baseCreate$1(getPrototype$1(e)):{}}return(n?arrayEach:baseForOwn)(e,(function(e,i,n){return t(r,e,i,n)})),r}function charsEndIndex(e,t){for(var r=e.length;r--&&baseIndexOf(t,e[r],0)>-1;);return r}function charsStartIndex(e,t){for(var r=-1,i=e.length;++r<i&&baseIndexOf(t,e[r],0)>-1;);return r}function trim(e,t,r){if((e=toString$1(e))&&(r||void 0===t))return baseTrim(e);if(!e||!(t=baseToString(t)))return e;var i=stringToArray(e),n=stringToArray(t);return castSlice(i,charsStartIndex(i,n),charsEndIndex(i,n)+1).join("")}function trimEnd(e,t,r){if((e=toString$1(e))&&(r||void 0===t))return e.slice(0,trimmedEndIndex(e)+1);if(!e||!(t=baseToString(t)))return e;var i=stringToArray(e);return castSlice(i,0,charsEndIndex(i,stringToArray(t))+1).join("")}var reTrimStart=/^\s+/;function trimStart(e,t,r){if((e=toString$1(e))&&(r||void 0===t))return e.replace(reTrimStart,"");if(!e||!(t=baseToString(t)))return e;var i=stringToArray(e);return castSlice(i,charsStartIndex(i,stringToArray(t))).join("")}var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",reFlags=/\w*$/;function truncate(e,t){var r=DEFAULT_TRUNC_LENGTH,i=DEFAULT_TRUNC_OMISSION;if(isObject(t)){var n="separator"in t?t.separator:n;r="length"in t?toInteger(t.length):r,i="omission"in t?baseToString(t.omission):i}var s=(e=toString$1(e)).length;if(hasUnicode(e)){var o=stringToArray(e);s=o.length}if(r>=s)return e;var a=r-stringSize(i);if(a<1)return i;var c=o?castSlice(o,0,a).join(""):e.slice(0,a);if(void 0===n)return c+i;if(o&&(a+=c.length-a),isRegExp$1(n)){if(e.slice(a).search(n)){var u,d=c;for(n.global||(n=RegExp(n.source,toString$1(reFlags.exec(n))+"g")),n.lastIndex=0;u=n.exec(d);)var l=u.index;c=c.slice(0,void 0===l?a:l)}}else if(e.indexOf(baseToString(n),a)!=a){var h=c.lastIndexOf(n);h>-1&&(c=c.slice(0,h))}return c+i}function unary(e){return ary(e,1)}var htmlUnescapes={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},unescapeHtmlChar=basePropertyOf(htmlUnescapes),unescapeHtmlChar$1=unescapeHtmlChar,reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reHasEscapedHtml=RegExp(reEscapedHtml.source);function unescape$1(e){return(e=toString$1(e))&&reHasEscapedHtml.test(e)?e.replace(reEscapedHtml,unescapeHtmlChar$1):e}var INFINITY=1/0,createSet=Set$2&&1/setToArray(new Set$2([,-0]))[1]==INFINITY?function(e){return new Set$2(e)}:noop$2,createSet$1=createSet,LARGE_ARRAY_SIZE=200;function baseUniq(e,t,r){var i=-1,n=arrayIncludes,s=e.length,o=!0,a=[],c=a;if(r)o=!1,n=arrayIncludesWith;else if(s>=LARGE_ARRAY_SIZE){var u=t?null:createSet$1(e);if(u)return setToArray(u);o=!1,n=cacheHas,c=new SetCache}else c=t?[]:a;e:for(;++i<s;){var d=e[i],l=t?t(d):d;if(d=r||0!==d?d:0,o&&l==l){for(var h=c.length;h--;)if(c[h]===l)continue e;t&&c.push(l),a.push(d)}else n(c,l,r)||(c!==a&&c.push(l),a.push(d))}return a}var union=baseRest((function(e){return baseUniq(baseFlatten(e,1,isArrayLikeObject,!0))})),union$1=union,unionBy=baseRest((function(e){var t=last(e);return isArrayLikeObject(t)&&(t=void 0),baseUniq(baseFlatten(e,1,isArrayLikeObject,!0),baseIteratee(t))})),unionBy$1=unionBy,unionWith=baseRest((function(e){var t=last(e);return t="function"==typeof t?t:void 0,baseUniq(baseFlatten(e,1,isArrayLikeObject,!0),void 0,t)})),unionWith$1=unionWith;function uniq(e){return e&&e.length?baseUniq(e):[]}function uniqBy(e,t){return e&&e.length?baseUniq(e,baseIteratee(t)):[]}function uniqWith(e,t){return t="function"==typeof t?t:void 0,e&&e.length?baseUniq(e,void 0,t):[]}var idCounter=0;function uniqueId(e){var t=++idCounter;return toString$1(e)+t}function unset(e,t){return null==e||baseUnset(e,t)}var nativeMax$2=Math.max;function unzip(e){if(!e||!e.length)return[];var t=0;return e=arrayFilter(e,(function(e){if(isArrayLikeObject(e))return t=nativeMax$2(e.length,t),!0})),baseTimes(t,(function(t){return arrayMap(e,baseProperty(t))}))}function unzipWith(e,t){if(!e||!e.length)return[];var r=unzip(e);return null==t?r:arrayMap(r,(function(e){return apply(t,void 0,e)}))}function baseUpdate(e,t,r,i){return baseSet(e,t,r(baseGet(e,t)),i)}function update(e,t,r){return null==e?e:baseUpdate(e,t,castFunction(r))}function updateWith(e,t,r,i){return i="function"==typeof i?i:void 0,null==e?e:baseUpdate(e,t,castFunction(r),i)}var upperCase=createCompounder((function(e,t,r){return e+(r?" ":"")+t.toUpperCase()})),upperCase$1=upperCase;function valuesIn(e){return null==e?[]:baseValues(e,keysIn(e))}var without=baseRest((function(e,t){return isArrayLikeObject(e)?baseDifference(e,t):[]})),without$1=without;function wrap(e,t){return partial$1(castFunction(t),e)}var wrapperAt=flatRest((function(e){var t=e.length,r=t?e[0]:0,i=this.__wrapped__,n=function(t){return baseAt(t,e)};return!(t>1||this.__actions__.length)&&i instanceof LazyWrapper&&isIndex(r)?((i=i.slice(r,+r+(t?1:0))).__actions__.push({func:thru,args:[n],thisArg:void 0}),new LodashWrapper(i,this.__chain__).thru((function(e){return t&&!e.length&&e.push(void 0),e}))):this.thru(n)})),at=wrapperAt;function wrapperChain(){return chain(this)}function wrapperReverse(){var e=this.__wrapped__;if(e instanceof LazyWrapper){var t=e;return this.__actions__.length&&(t=new LazyWrapper(this)),(t=t.reverse()).__actions__.push({func:thru,args:[reverse],thisArg:void 0}),new LodashWrapper(t,this.__chain__)}return this.thru(reverse)}function baseXor(e,t,r){var i=e.length;if(i<2)return i?baseUniq(e[0]):[];for(var n=-1,s=Array(i);++n<i;)for(var o=e[n],a=-1;++a<i;)a!=n&&(s[n]=baseDifference(s[n]||o,e[a],t,r));return baseUniq(baseFlatten(s,1),t,r)}var xor=baseRest((function(e){return baseXor(arrayFilter(e,isArrayLikeObject))})),xor$1=xor,xorBy=baseRest((function(e){var t=last(e);return isArrayLikeObject(t)&&(t=void 0),baseXor(arrayFilter(e,isArrayLikeObject),baseIteratee(t))})),xorBy$1=xorBy,xorWith=baseRest((function(e){var t=last(e);return t="function"==typeof t?t:void 0,baseXor(arrayFilter(e,isArrayLikeObject),void 0,t)})),xorWith$1=xorWith,zip=baseRest(unzip),zip$1=zip;function baseZipObject(e,t,r){for(var i=-1,n=e.length,s=t.length,o={};++i<n;){var a=i<s?t[i]:void 0;r(o,e[i],a)}return o}function zipObject(e,t){return baseZipObject(e||[],t||[],assignValue)}function zipObjectDeep(e,t){return baseZipObject(e||[],t||[],baseSet)}var zipWith=baseRest((function(e){var t=e.length,r=t>1?e[t-1]:void 0;return r="function"==typeof r?(e.pop(),r):void 0,unzipWith(e,r)})),zipWith$1=zipWith,array={chunk:chunk,compact:compact,concat:concat,difference:difference$1,differenceBy:differenceBy$1,differenceWith:differenceWith$1,drop:drop,dropRight:dropRight,dropRightWhile:dropRightWhile,dropWhile:dropWhile,fill:fill,findIndex:findIndex,findLastIndex:findLastIndex,first:head,flatten:flatten,flattenDeep:flattenDeep,flattenDepth:flattenDepth,fromPairs:fromPairs,head:head,indexOf:indexOf$2,initial:initial,intersection:intersection$1,intersectionBy:intersectionBy$1,intersectionWith:intersectionWith$1,join:join,last:last,lastIndexOf:lastIndexOf,nth:nth,pull:pull$1,pullAll:pullAll,pullAllBy:pullAllBy,pullAllWith:pullAllWith,pullAt:pullAt$1,remove:remove,reverse:reverse,slice:slice,sortedIndex:sortedIndex,sortedIndexBy:sortedIndexBy,sortedIndexOf:sortedIndexOf,sortedLastIndex:sortedLastIndex,sortedLastIndexBy:sortedLastIndexBy,sortedLastIndexOf:sortedLastIndexOf,sortedUniq:sortedUniq,sortedUniqBy:sortedUniqBy,tail:tail,take:take,takeRight:takeRight,takeRightWhile:takeRightWhile,takeWhile:takeWhile,union:union$1,unionBy:unionBy$1,unionWith:unionWith$1,uniq:uniq,uniqBy:uniqBy,uniqWith:uniqWith,unzip:unzip,unzipWith:unzipWith,without:without$1,xor:xor$1,xorBy:xorBy$1,xorWith:xorWith$1,zip:zip$1,zipObject:zipObject,zipObjectDeep:zipObjectDeep,zipWith:zipWith$1},collection={countBy:countBy$1,each:forEach,eachRight:forEachRight,every:every,filter:filter,find:find$1,findLast:findLast$1,flatMap:flatMap,flatMapDeep:flatMapDeep,flatMapDepth:flatMapDepth,forEach:forEach,forEachRight:forEachRight,groupBy:groupBy$1,includes:includes,invokeMap:invokeMap$1,keyBy:keyBy$1,map:map,orderBy:orderBy,partition:partition$1,reduce:reduce,reduceRight:reduceRight,reject:reject$1,sample:sample,sampleSize:sampleSize,shuffle:shuffle,size:size,some:some,sortBy:sortBy$1},date={now:now$1},func$1={after:after,ary:ary,before:before,bind:bind$2,bindKey:bindKey$1,curry:curry,curryRight:curryRight,debounce:debounce,defer:defer$1,delay:delay$1,flip:flip,memoize:memoize,negate:negate,once:once$1,overArgs:overArgs$1,partial:partial$1,partialRight:partialRight$1,rearg:rearg$1,rest:rest,spread:spread,throttle:throttle,unary:unary,wrap:wrap},lang={castArray:castArray,clone:clone,cloneDeep:cloneDeep,cloneDeepWith:cloneDeepWith,cloneWith:cloneWith,conformsTo:conformsTo,eq:eq,gt:gt$1,gte:gte$1,isArguments:isArguments$1,isArray:isArray$1,isArrayBuffer:isArrayBuffer$1,isArrayLike:isArrayLike,isArrayLikeObject:isArrayLikeObject,isBoolean:isBoolean,isBuffer:isBuffer$1,isDate:isDate$1,isElement:isElement,isEmpty:isEmpty,isEqual:isEqual,isEqualWith:isEqualWith,isError:isError,isFinite:isFinite$1,isFunction:isFunction$1,isInteger:isInteger,isLength:isLength,isMap:isMap$1,isMatch:isMatch,isMatchWith:isMatchWith,isNaN:isNaN$1,isNative:isNative$1,isNil:isNil,isNull:isNull,isNumber:isNumber,isObject:isObject,isObjectLike:isObjectLike,isPlainObject:isPlainObject,isRegExp:isRegExp$1,isSafeInteger:isSafeInteger,isSet:isSet$1,isString:isString,isSymbol:isSymbol,isTypedArray:isTypedArray$1,isUndefined:isUndefined,isWeakMap:isWeakMap,isWeakSet:isWeakSet,lt:lt$1,lte:lte$1,toArray:toArray,toFinite:toFinite,toInteger:toInteger,toLength:toLength,toNumber:toNumber,toPlainObject:toPlainObject,toSafeInteger:toSafeInteger,toString:toString$1},math={add:add$1,ceil:ceil$1,divide:divide$1,floor:floor$1,max:max,maxBy:maxBy,mean:mean,meanBy:meanBy,min:min,minBy:minBy,multiply:multiply$1,round:round$1,subtract:subtract$1,sum:sum,sumBy:sumBy},number={clamp:clamp,inRange:inRange,random:random},object={assign:assign$1,assignIn:extend,assignInWith:extendWith,assignWith:assignWith$1,at:at$2,create:create,defaults:defaults$1,defaultsDeep:defaultsDeep$1,entries:toPairs$1,entriesIn:toPairsIn$1,extend:extend,extendWith:extendWith,findKey:findKey,findLastKey:findLastKey,forIn:forIn,forInRight:forInRight,forOwn:forOwn,forOwnRight:forOwnRight,functions:functions,functionsIn:functionsIn,get:get,has:has$1,hasIn:hasIn,invert:invert$1,invertBy:invertBy$1,invoke:invoke$1,keys:keys,keysIn:keysIn,mapKeys:mapKeys,mapValues:mapValues,merge:merge$1,mergeWith:mergeWith$1,omit:omit$1,omitBy:omitBy,pick:pick$1,pickBy:pickBy,result:result,set:set,setWith:setWith,toPairs:toPairs$1,toPairsIn:toPairsIn$1,transform:transform,unset:unset,update:update,updateWith:updateWith,values:values,valuesIn:valuesIn},seq={at:at,chain:chain,commit:wrapperCommit,lodash:lodash$1,next:wrapperNext,plant:wrapperPlant,reverse:wrapperReverse,tap:tap,thru:thru,toIterator:wrapperToIterator,toJSON:wrapperValue,value:wrapperValue,valueOf:wrapperValue,wrapperChain:wrapperChain},string={camelCase:camelCase$1,capitalize:capitalize,deburr:deburr,endsWith:endsWith,escape:escape,escapeRegExp:escapeRegExp,kebabCase:kebabCase$1,lowerCase:lowerCase$1,lowerFirst:lowerFirst$1,pad:pad,padEnd:padEnd,padStart:padStart,parseInt:parseInt$1,repeat:repeat,replace:replace,snakeCase:snakeCase$1,split:split,startCase:startCase$1,startsWith:startsWith,template:template,templateSettings:templateSettings$1,toLower:toLower,toUpper:toUpper,trim:trim,trimEnd:trimEnd,trimStart:trimStart,truncate:truncate,unescape:unescape$1,upperCase:upperCase$1,upperFirst:upperFirst$1,words:words},util={attempt:attempt$1,bindAll:bindAll$1,cond:cond,conforms:conforms,constant:constant,defaultTo:defaultTo,flow:flow$1,flowRight:flowRight$1,identity:identity$1,iteratee:iteratee,matches:matches,matchesProperty:matchesProperty,method:method$1,methodOf:methodOf$1,mixin:mixin$1,noop:noop$2,nthArg:nthArg,over:over$1,overEvery:overEvery$1,overSome:overSome$1,property:property,propertyOf:propertyOf,range:range$1,rangeRight:rangeRight$1,stubArray:stubArray,stubFalse:stubFalse,stubObject:stubObject,stubString:stubString,stubTrue:stubTrue,times:times,toPath:toPath,uniqueId:uniqueId};function lazyClone(){var e=new LazyWrapper(this.__wrapped__);return e.__actions__=copyArray(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=copyArray(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=copyArray(this.__views__),e}function lazyReverse(){if(this.__filtered__){var e=new LazyWrapper(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e}var nativeMax$1=Math.max,nativeMin$2=Math.min;function getView(e,t,r){for(var i=-1,n=r.length;++i<n;){var s=r[i],o=s.size;switch(s.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=nativeMin$2(t,e+o);break;case"takeRight":e=nativeMax$1(e,t-o)}}return{start:e,end:t}}var LAZY_FILTER_FLAG$1=1,LAZY_MAP_FLAG=2,nativeMin$1=Math.min;function lazyValue(){var e=this.__wrapped__.value(),t=this.__dir__,r=isArray$1(e),i=t<0,n=r?e.length:0,s=getView(0,n,this.__views__),o=s.start,a=s.end,c=a-o,u=i?a:o-1,d=this.__iteratees__,l=d.length,h=0,p=nativeMin$1(c,this.__takeCount__);if(!r||!i&&n==c&&p==c)return baseWrapperValue(e,this.__actions__);var m=[];e:for(;c--&&h<p;){for(var f=-1,g=e[u+=t];++f<l;){var v=d[f],y=v.iteratee,_=v.type,b=y(g);if(_==LAZY_MAP_FLAG)g=b;else if(!b){if(_==LAZY_FILTER_FLAG$1)continue e;break e}}m[h++]=g}return m}
2
- /**
3
- * @license
4
- * Lodash (Custom Build) <https://lodash.com/>
5
- * Build: `lodash modularize exports="es" -o ./`
6
- * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
7
- * Released under MIT license <https://lodash.com/license>
8
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
9
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
10
- */var VERSION="4.17.21",WRAP_BIND_KEY_FLAG=2,LAZY_FILTER_FLAG=1,LAZY_WHILE_FLAG=3,MAX_ARRAY_LENGTH=4294967295,arrayProto=Array.prototype,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,symIterator=Symbol$2?Symbol$2.iterator:void 0,nativeMax=Math.max,nativeMin=Math.min,mixin=function(e){return function(t,r,i){if(null==i){var n=isObject(r),s=n&&keys(r),o=s&&s.length&&baseFunctions(r,s);(o?o.length:n)||(i=r,r=t,t=this)}return e(t,r,i)}}(mixin$1),source;lodash$1.after=func$1.after,lodash$1.ary=func$1.ary,lodash$1.assign=object.assign,lodash$1.assignIn=object.assignIn,lodash$1.assignInWith=object.assignInWith,lodash$1.assignWith=object.assignWith,lodash$1.at=object.at,lodash$1.before=func$1.before,lodash$1.bind=func$1.bind,lodash$1.bindAll=util.bindAll,lodash$1.bindKey=func$1.bindKey,lodash$1.castArray=lang.castArray,lodash$1.chain=seq.chain,lodash$1.chunk=array.chunk,lodash$1.compact=array.compact,lodash$1.concat=array.concat,lodash$1.cond=util.cond,lodash$1.conforms=util.conforms,lodash$1.constant=util.constant,lodash$1.countBy=collection.countBy,lodash$1.create=object.create,lodash$1.curry=func$1.curry,lodash$1.curryRight=func$1.curryRight,lodash$1.debounce=func$1.debounce,lodash$1.defaults=object.defaults,lodash$1.defaultsDeep=object.defaultsDeep,lodash$1.defer=func$1.defer,lodash$1.delay=func$1.delay,lodash$1.difference=array.difference,lodash$1.differenceBy=array.differenceBy,lodash$1.differenceWith=array.differenceWith,lodash$1.drop=array.drop,lodash$1.dropRight=array.dropRight,lodash$1.dropRightWhile=array.dropRightWhile,lodash$1.dropWhile=array.dropWhile,lodash$1.fill=array.fill,lodash$1.filter=collection.filter,lodash$1.flatMap=collection.flatMap,lodash$1.flatMapDeep=collection.flatMapDeep,lodash$1.flatMapDepth=collection.flatMapDepth,lodash$1.flatten=array.flatten,lodash$1.flattenDeep=array.flattenDeep,lodash$1.flattenDepth=array.flattenDepth,lodash$1.flip=func$1.flip,lodash$1.flow=util.flow,lodash$1.flowRight=util.flowRight,lodash$1.fromPairs=array.fromPairs,lodash$1.functions=object.functions,lodash$1.functionsIn=object.functionsIn,lodash$1.groupBy=collection.groupBy,lodash$1.initial=array.initial,lodash$1.intersection=array.intersection,lodash$1.intersectionBy=array.intersectionBy,lodash$1.intersectionWith=array.intersectionWith,lodash$1.invert=object.invert,lodash$1.invertBy=object.invertBy,lodash$1.invokeMap=collection.invokeMap,lodash$1.iteratee=util.iteratee,lodash$1.keyBy=collection.keyBy,lodash$1.keys=keys,lodash$1.keysIn=object.keysIn,lodash$1.map=collection.map,lodash$1.mapKeys=object.mapKeys,lodash$1.mapValues=object.mapValues,lodash$1.matches=util.matches,lodash$1.matchesProperty=util.matchesProperty,lodash$1.memoize=func$1.memoize,lodash$1.merge=object.merge,lodash$1.mergeWith=object.mergeWith,lodash$1.method=util.method,lodash$1.methodOf=util.methodOf,lodash$1.mixin=mixin,lodash$1.negate=negate,lodash$1.nthArg=util.nthArg,lodash$1.omit=object.omit,lodash$1.omitBy=object.omitBy,lodash$1.once=func$1.once,lodash$1.orderBy=collection.orderBy,lodash$1.over=util.over,lodash$1.overArgs=func$1.overArgs,lodash$1.overEvery=util.overEvery,lodash$1.overSome=util.overSome,lodash$1.partial=func$1.partial,lodash$1.partialRight=func$1.partialRight,lodash$1.partition=collection.partition,lodash$1.pick=object.pick,lodash$1.pickBy=object.pickBy,lodash$1.property=util.property,lodash$1.propertyOf=util.propertyOf,lodash$1.pull=array.pull,lodash$1.pullAll=array.pullAll,lodash$1.pullAllBy=array.pullAllBy,lodash$1.pullAllWith=array.pullAllWith,lodash$1.pullAt=array.pullAt,lodash$1.range=util.range,lodash$1.rangeRight=util.rangeRight,lodash$1.rearg=func$1.rearg,lodash$1.reject=collection.reject,lodash$1.remove=array.remove,lodash$1.rest=func$1.rest,lodash$1.reverse=array.reverse,lodash$1.sampleSize=collection.sampleSize,lodash$1.set=object.set,lodash$1.setWith=object.setWith,lodash$1.shuffle=collection.shuffle,lodash$1.slice=array.slice,lodash$1.sortBy=collection.sortBy,lodash$1.sortedUniq=array.sortedUniq,lodash$1.sortedUniqBy=array.sortedUniqBy,lodash$1.split=string.split,lodash$1.spread=func$1.spread,lodash$1.tail=array.tail,lodash$1.take=array.take,lodash$1.takeRight=array.takeRight,lodash$1.takeRightWhile=array.takeRightWhile,lodash$1.takeWhile=array.takeWhile,lodash$1.tap=seq.tap,lodash$1.throttle=func$1.throttle,lodash$1.thru=thru,lodash$1.toArray=lang.toArray,lodash$1.toPairs=object.toPairs,lodash$1.toPairsIn=object.toPairsIn,lodash$1.toPath=util.toPath,lodash$1.toPlainObject=lang.toPlainObject,lodash$1.transform=object.transform,lodash$1.unary=func$1.unary,lodash$1.union=array.union,lodash$1.unionBy=array.unionBy,lodash$1.unionWith=array.unionWith,lodash$1.uniq=array.uniq,lodash$1.uniqBy=array.uniqBy,lodash$1.uniqWith=array.uniqWith,lodash$1.unset=object.unset,lodash$1.unzip=array.unzip,lodash$1.unzipWith=array.unzipWith,lodash$1.update=object.update,lodash$1.updateWith=object.updateWith,lodash$1.values=object.values,lodash$1.valuesIn=object.valuesIn,lodash$1.without=array.without,lodash$1.words=string.words,lodash$1.wrap=func$1.wrap,lodash$1.xor=array.xor,lodash$1.xorBy=array.xorBy,lodash$1.xorWith=array.xorWith,lodash$1.zip=array.zip,lodash$1.zipObject=array.zipObject,lodash$1.zipObjectDeep=array.zipObjectDeep,lodash$1.zipWith=array.zipWith,lodash$1.entries=object.toPairs,lodash$1.entriesIn=object.toPairsIn,lodash$1.extend=object.assignIn,lodash$1.extendWith=object.assignInWith,mixin(lodash$1,lodash$1),lodash$1.add=math.add,lodash$1.attempt=util.attempt,lodash$1.camelCase=string.camelCase,lodash$1.capitalize=string.capitalize,lodash$1.ceil=math.ceil,lodash$1.clamp=number.clamp,lodash$1.clone=lang.clone,lodash$1.cloneDeep=lang.cloneDeep,lodash$1.cloneDeepWith=lang.cloneDeepWith,lodash$1.cloneWith=lang.cloneWith,lodash$1.conformsTo=lang.conformsTo,lodash$1.deburr=string.deburr,lodash$1.defaultTo=util.defaultTo,lodash$1.divide=math.divide,lodash$1.endsWith=string.endsWith,lodash$1.eq=lang.eq,lodash$1.escape=string.escape,lodash$1.escapeRegExp=string.escapeRegExp,lodash$1.every=collection.every,lodash$1.find=collection.find,lodash$1.findIndex=array.findIndex,lodash$1.findKey=object.findKey,lodash$1.findLast=collection.findLast,lodash$1.findLastIndex=array.findLastIndex,lodash$1.findLastKey=object.findLastKey,lodash$1.floor=math.floor,lodash$1.forEach=collection.forEach,lodash$1.forEachRight=collection.forEachRight,lodash$1.forIn=object.forIn,lodash$1.forInRight=object.forInRight,lodash$1.forOwn=object.forOwn,lodash$1.forOwnRight=object.forOwnRight,lodash$1.get=object.get,lodash$1.gt=lang.gt,lodash$1.gte=lang.gte,lodash$1.has=object.has,lodash$1.hasIn=object.hasIn,lodash$1.head=array.head,lodash$1.identity=identity$1,lodash$1.includes=collection.includes,lodash$1.indexOf=array.indexOf,lodash$1.inRange=number.inRange,lodash$1.invoke=object.invoke,lodash$1.isArguments=lang.isArguments,lodash$1.isArray=isArray$1,lodash$1.isArrayBuffer=lang.isArrayBuffer,lodash$1.isArrayLike=lang.isArrayLike,lodash$1.isArrayLikeObject=lang.isArrayLikeObject,lodash$1.isBoolean=lang.isBoolean,lodash$1.isBuffer=lang.isBuffer,lodash$1.isDate=lang.isDate,lodash$1.isElement=lang.isElement,lodash$1.isEmpty=lang.isEmpty,lodash$1.isEqual=lang.isEqual,lodash$1.isEqualWith=lang.isEqualWith,lodash$1.isError=lang.isError,lodash$1.isFinite=lang.isFinite,lodash$1.isFunction=lang.isFunction,lodash$1.isInteger=lang.isInteger,lodash$1.isLength=lang.isLength,lodash$1.isMap=lang.isMap,lodash$1.isMatch=lang.isMatch,lodash$1.isMatchWith=lang.isMatchWith,lodash$1.isNaN=lang.isNaN,lodash$1.isNative=lang.isNative,lodash$1.isNil=lang.isNil,lodash$1.isNull=lang.isNull,lodash$1.isNumber=lang.isNumber,lodash$1.isObject=isObject,lodash$1.isObjectLike=lang.isObjectLike,lodash$1.isPlainObject=lang.isPlainObject,lodash$1.isRegExp=lang.isRegExp,lodash$1.isSafeInteger=lang.isSafeInteger,lodash$1.isSet=lang.isSet,lodash$1.isString=lang.isString,lodash$1.isSymbol=lang.isSymbol,lodash$1.isTypedArray=lang.isTypedArray,lodash$1.isUndefined=lang.isUndefined,lodash$1.isWeakMap=lang.isWeakMap,lodash$1.isWeakSet=lang.isWeakSet,lodash$1.join=array.join,lodash$1.kebabCase=string.kebabCase,lodash$1.last=last,lodash$1.lastIndexOf=array.lastIndexOf,lodash$1.lowerCase=string.lowerCase,lodash$1.lowerFirst=string.lowerFirst,lodash$1.lt=lang.lt,lodash$1.lte=lang.lte,lodash$1.max=math.max,lodash$1.maxBy=math.maxBy,lodash$1.mean=math.mean,lodash$1.meanBy=math.meanBy,lodash$1.min=math.min,lodash$1.minBy=math.minBy,lodash$1.stubArray=util.stubArray,lodash$1.stubFalse=util.stubFalse,lodash$1.stubObject=util.stubObject,lodash$1.stubString=util.stubString,lodash$1.stubTrue=util.stubTrue,lodash$1.multiply=math.multiply,lodash$1.nth=array.nth,lodash$1.noop=util.noop,lodash$1.now=date.now,lodash$1.pad=string.pad,lodash$1.padEnd=string.padEnd,lodash$1.padStart=string.padStart,lodash$1.parseInt=string.parseInt,lodash$1.random=number.random,lodash$1.reduce=collection.reduce,lodash$1.reduceRight=collection.reduceRight,lodash$1.repeat=string.repeat,lodash$1.replace=string.replace,lodash$1.result=object.result,lodash$1.round=math.round,lodash$1.sample=collection.sample,lodash$1.size=collection.size,lodash$1.snakeCase=string.snakeCase,lodash$1.some=collection.some,lodash$1.sortedIndex=array.sortedIndex,lodash$1.sortedIndexBy=array.sortedIndexBy,lodash$1.sortedIndexOf=array.sortedIndexOf,lodash$1.sortedLastIndex=array.sortedLastIndex,lodash$1.sortedLastIndexBy=array.sortedLastIndexBy,lodash$1.sortedLastIndexOf=array.sortedLastIndexOf,lodash$1.startCase=string.startCase,lodash$1.startsWith=string.startsWith,lodash$1.subtract=math.subtract,lodash$1.sum=math.sum,lodash$1.sumBy=math.sumBy,lodash$1.template=string.template,lodash$1.times=util.times,lodash$1.toFinite=lang.toFinite,lodash$1.toInteger=toInteger,lodash$1.toLength=lang.toLength,lodash$1.toLower=string.toLower,lodash$1.toNumber=lang.toNumber,lodash$1.toSafeInteger=lang.toSafeInteger,lodash$1.toString=lang.toString,lodash$1.toUpper=string.toUpper,lodash$1.trim=string.trim,lodash$1.trimEnd=string.trimEnd,lodash$1.trimStart=string.trimStart,lodash$1.truncate=string.truncate,lodash$1.unescape=string.unescape,lodash$1.uniqueId=util.uniqueId,lodash$1.upperCase=string.upperCase,lodash$1.upperFirst=string.upperFirst,lodash$1.each=collection.forEach,lodash$1.eachRight=collection.forEachRight,lodash$1.first=array.head,mixin(lodash$1,(source={},baseForOwn(lodash$1,(function(e,t){hasOwnProperty.call(lodash$1.prototype,t)||(source[t]=e)})),source),{chain:!1}),lodash$1.VERSION=VERSION,(lodash$1.templateSettings=string.templateSettings).imports._=lodash$1,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){lodash$1[e].placeholder=lodash$1})),arrayEach(["drop","take"],(function(e,t){LazyWrapper.prototype[e]=function(r){r=void 0===r?1:nativeMax(toInteger(r),0);var i=this.__filtered__&&!t?new LazyWrapper(this):this.clone();return i.__filtered__?i.__takeCount__=nativeMin(r,i.__takeCount__):i.__views__.push({size:nativeMin(r,MAX_ARRAY_LENGTH),type:e+(i.__dir__<0?"Right":"")}),i},LazyWrapper.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),arrayEach(["filter","map","takeWhile"],(function(e,t){var r=t+1,i=r==LAZY_FILTER_FLAG||r==LAZY_WHILE_FLAG;LazyWrapper.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:baseIteratee(e),type:r}),t.__filtered__=t.__filtered__||i,t}})),arrayEach(["head","last"],(function(e,t){var r="take"+(t?"Right":"");LazyWrapper.prototype[e]=function(){return this[r](1).value()[0]}})),arrayEach(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");LazyWrapper.prototype[e]=function(){return this.__filtered__?new LazyWrapper(this):this[r](1)}})),LazyWrapper.prototype.compact=function(){return this.filter(identity$1)},LazyWrapper.prototype.find=function(e){return this.filter(e).head()},LazyWrapper.prototype.findLast=function(e){return this.reverse().find(e)},LazyWrapper.prototype.invokeMap=baseRest((function(e,t){return"function"==typeof e?new LazyWrapper(this):this.map((function(r){return baseInvoke(r,e,t)}))})),LazyWrapper.prototype.reject=function(e){return this.filter(negate(baseIteratee(e)))},LazyWrapper.prototype.slice=function(e,t){e=toInteger(e);var r=this;return r.__filtered__&&(e>0||t<0)?new LazyWrapper(r):(e<0?r=r.takeRight(-e):e&&(r=r.drop(e)),void 0!==t&&(r=(t=toInteger(t))<0?r.dropRight(-t):r.take(t-e)),r)},LazyWrapper.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,(function(e,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),i=/^(?:head|last)$/.test(t),n=lodash$1[i?"take"+("last"==t?"Right":""):t],s=i||/^find/.test(t);n&&(lodash$1.prototype[t]=function(){var t=this.__wrapped__,o=i?[1]:arguments,a=t instanceof LazyWrapper,c=o[0],u=a||isArray$1(t),d=function(e){var t=n.apply(lodash$1,arrayPush([e],o));return i&&l?t[0]:t};u&&r&&"function"==typeof c&&1!=c.length&&(a=u=!1);var l=this.__chain__,h=!!this.__actions__.length,p=s&&!l,m=a&&!h;if(!s&&u){t=m?t:new LazyWrapper(this);var f=e.apply(t,o);return f.__actions__.push({func:thru,args:[d],thisArg:void 0}),new LodashWrapper(f,l)}return p&&m?e.apply(this,o):(f=this.thru(d),p?i?f.value()[0]:f.value():f)})})),arrayEach(["pop","push","shift","sort","splice","unshift"],(function(e){var t=arrayProto[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",i=/^(?:pop|shift)$/.test(e);lodash$1.prototype[e]=function(){var e=arguments;if(i&&!this.__chain__){var n=this.value();return t.apply(isArray$1(n)?n:[],e)}return this[r]((function(r){return t.apply(isArray$1(r)?r:[],e)}))}})),baseForOwn(LazyWrapper.prototype,(function(e,t){var r=lodash$1[t];if(r){var i=r.name+"";hasOwnProperty.call(realNames$1,i)||(realNames$1[i]=[]),realNames$1[i].push({name:t,func:r})}})),realNames$1[createHybrid(void 0,WRAP_BIND_KEY_FLAG).name]=[{name:"wrapper",func:void 0}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash$1.prototype.at=seq.at,lodash$1.prototype.chain=seq.wrapperChain,lodash$1.prototype.commit=seq.commit,lodash$1.prototype.next=seq.next,lodash$1.prototype.plant=seq.plant,lodash$1.prototype.reverse=seq.reverse,lodash$1.prototype.toJSON=lodash$1.prototype.valueOf=lodash$1.prototype.value=seq.value,lodash$1.prototype.first=lodash$1.prototype.head,symIterator&&(lodash$1.prototype[symIterator]=seq.toIterator)
11
- /**
12
- * @license
13
- * Lodash (Custom Build) <https://lodash.com/>
14
- * Build: `lodash modularize exports="es" -o ./`
15
- * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
16
- * Released under MIT license <https://lodash.com/license>
17
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
18
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
19
- */;var lodash=Object.freeze({__proto__:null,add:add$1,after:after,ary:ary,assign:assign$1,assignIn:extend,assignInWith:extendWith,assignWith:assignWith$1,at:at$2,attempt:attempt$1,before:before,bind:bind$2,bindAll:bindAll$1,bindKey:bindKey$1,camelCase:camelCase$1,capitalize:capitalize,castArray:castArray,ceil:ceil$1,chain:chain,chunk:chunk,clamp:clamp,clone:clone,cloneDeep:cloneDeep,cloneDeepWith:cloneDeepWith,cloneWith:cloneWith,commit:wrapperCommit,compact:compact,concat:concat,cond:cond,conforms:conforms,conformsTo:conformsTo,constant:constant,countBy:countBy$1,create:create,curry:curry,curryRight:curryRight,debounce:debounce,deburr:deburr,defaultTo:defaultTo,defaults:defaults$1,defaultsDeep:defaultsDeep$1,defer:defer$1,delay:delay$1,difference:difference$1,differenceBy:differenceBy$1,differenceWith:differenceWith$1,divide:divide$1,drop:drop,dropRight:dropRight,dropRightWhile:dropRightWhile,dropWhile:dropWhile,each:forEach,eachRight:forEachRight,endsWith:endsWith,entries:toPairs$1,entriesIn:toPairsIn$1,eq:eq,escape:escape,escapeRegExp:escapeRegExp,every:every,extend:extend,extendWith:extendWith,fill:fill,filter:filter,find:find$1,findIndex:findIndex,findKey:findKey,findLast:findLast$1,findLastIndex:findLastIndex,findLastKey:findLastKey,first:head,flatMap:flatMap,flatMapDeep:flatMapDeep,flatMapDepth:flatMapDepth,flatten:flatten,flattenDeep:flattenDeep,flattenDepth:flattenDepth,flip:flip,floor:floor$1,flow:flow$1,flowRight:flowRight$1,forEach:forEach,forEachRight:forEachRight,forIn:forIn,forInRight:forInRight,forOwn:forOwn,forOwnRight:forOwnRight,fromPairs:fromPairs,functions:functions,functionsIn:functionsIn,get:get,groupBy:groupBy$1,gt:gt$1,gte:gte$1,has:has$1,hasIn:hasIn,head:head,identity:identity$1,inRange:inRange,includes:includes,indexOf:indexOf$2,initial:initial,intersection:intersection$1,intersectionBy:intersectionBy$1,intersectionWith:intersectionWith$1,invert:invert$1,invertBy:invertBy$1,invoke:invoke$1,invokeMap:invokeMap$1,isArguments:isArguments$1,isArray:isArray$1,isArrayBuffer:isArrayBuffer$1,isArrayLike:isArrayLike,isArrayLikeObject:isArrayLikeObject,isBoolean:isBoolean,isBuffer:isBuffer$1,isDate:isDate$1,isElement:isElement,isEmpty:isEmpty,isEqual:isEqual,isEqualWith:isEqualWith,isError:isError,isFinite:isFinite$1,isFunction:isFunction$1,isInteger:isInteger,isLength:isLength,isMap:isMap$1,isMatch:isMatch,isMatchWith:isMatchWith,isNaN:isNaN$1,isNative:isNative$1,isNil:isNil,isNull:isNull,isNumber:isNumber,isObject:isObject,isObjectLike:isObjectLike,isPlainObject:isPlainObject,isRegExp:isRegExp$1,isSafeInteger:isSafeInteger,isSet:isSet$1,isString:isString,isSymbol:isSymbol,isTypedArray:isTypedArray$1,isUndefined:isUndefined,isWeakMap:isWeakMap,isWeakSet:isWeakSet,iteratee:iteratee,join:join,kebabCase:kebabCase$1,keyBy:keyBy$1,keys:keys,keysIn:keysIn,last:last,lastIndexOf:lastIndexOf,lodash:lodash$1,lowerCase:lowerCase$1,lowerFirst:lowerFirst$1,lt:lt$1,lte:lte$1,map:map,mapKeys:mapKeys,mapValues:mapValues,matches:matches,matchesProperty:matchesProperty,max:max,maxBy:maxBy,mean:mean,meanBy:meanBy,memoize:memoize,merge:merge$1,mergeWith:mergeWith$1,method:method$1,methodOf:methodOf$1,min:min,minBy:minBy,mixin:mixin$1,multiply:multiply$1,negate:negate,next:wrapperNext,noop:noop$2,now:now$1,nth:nth,nthArg:nthArg,omit:omit$1,omitBy:omitBy,once:once$1,orderBy:orderBy,over:over$1,overArgs:overArgs$1,overEvery:overEvery$1,overSome:overSome$1,pad:pad,padEnd:padEnd,padStart:padStart,parseInt:parseInt$1,partial:partial$1,partialRight:partialRight$1,partition:partition$1,pick:pick$1,pickBy:pickBy,plant:wrapperPlant,property:property,propertyOf:propertyOf,pull:pull$1,pullAll:pullAll,pullAllBy:pullAllBy,pullAllWith:pullAllWith,pullAt:pullAt$1,random:random,range:range$1,rangeRight:rangeRight$1,rearg:rearg$1,reduce:reduce,reduceRight:reduceRight,reject:reject$1,remove:remove,repeat:repeat,replace:replace,rest:rest,result:result,reverse:reverse,round:round$1,sample:sample,sampleSize:sampleSize,set:set,setWith:setWith,shuffle:shuffle,size:size,slice:slice,snakeCase:snakeCase$1,some:some,sortBy:sortBy$1,sortedIndex:sortedIndex,sortedIndexBy:sortedIndexBy,sortedIndexOf:sortedIndexOf,sortedLastIndex:sortedLastIndex,sortedLastIndexBy:sortedLastIndexBy,sortedLastIndexOf:sortedLastIndexOf,sortedUniq:sortedUniq,sortedUniqBy:sortedUniqBy,split:split,spread:spread,startCase:startCase$1,startsWith:startsWith,stubArray:stubArray,stubFalse:stubFalse,stubObject:stubObject,stubString:stubString,stubTrue:stubTrue,subtract:subtract$1,sum:sum,sumBy:sumBy,tail:tail,take:take,takeRight:takeRight,takeRightWhile:takeRightWhile,takeWhile:takeWhile,tap:tap,template:template,templateSettings:templateSettings$1,throttle:throttle,thru:thru,times:times,toArray:toArray,toFinite:toFinite,toInteger:toInteger,toIterator:wrapperToIterator,toJSON:wrapperValue,toLength:toLength,toLower:toLower,toNumber:toNumber,toPairs:toPairs$1,toPairsIn:toPairsIn$1,toPath:toPath,toPlainObject:toPlainObject,toSafeInteger:toSafeInteger,toString:toString$1,toUpper:toUpper,transform:transform,trim:trim,trimEnd:trimEnd,trimStart:trimStart,truncate:truncate,unary:unary,unescape:unescape$1,union:union$1,unionBy:unionBy$1,unionWith:unionWith$1,uniq:uniq,uniqBy:uniqBy,uniqWith:uniqWith,uniqueId:uniqueId,unset:unset,unzip:unzip,unzipWith:unzipWith,update:update,updateWith:updateWith,upperCase:upperCase$1,upperFirst:upperFirst$1,value:wrapperValue,valueOf:wrapperValue,values:values,valuesIn:valuesIn,without:without$1,words:words,wrap:wrap,wrapperAt:at,wrapperChain:wrapperChain,wrapperCommit:wrapperCommit,wrapperLodash:lodash$1,wrapperNext:wrapperNext,wrapperPlant:wrapperPlant,wrapperReverse:wrapperReverse,wrapperToIterator:wrapperToIterator,wrapperValue:wrapperValue,xor:xor$1,xorBy:xorBy$1,xorWith:xorWith$1,zip:zip$1,zipObject:zipObject,zipObjectDeep:zipObjectDeep,zipWith:zipWith$1,default:lodash$1}),require$$1=getAugmentedNamespace(lodash);const BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Utils{static getFirstMatch(e,t){const r=t.match(e);return r&&r.length>0&&r[1]||""}static getSecondMatch(e,t){const r=t.match(e);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(e,t,r){if(e.test(t))return r}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,r=!1){const i=Utils.getVersionPrecision(e),n=Utils.getVersionPrecision(t);let s=Math.max(i,n),o=0;const a=Utils.map([e,t],(e=>{const t=s-Utils.getVersionPrecision(e),r=e+new Array(t+1).join(".0");return Utils.map(r.split("."),(e=>new Array(20-e.length).join("0")+e)).reverse()}));for(r&&(o=s-Math.min(i,n)),s-=1;s>=o;){if(a[0][s]>a[1][s])return 1;if(a[0][s]===a[1][s]){if(s===o)return 0;s-=1}else if(a[0][s]<a[1][s])return-1}}static map(e,t){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,t);for(i=0;i<e.length;i+=1)r.push(t(e[i]));return r}static find(e,t){let r,i;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,i=e.length;r<i;r+=1){const i=e[r];if(t(i,r))return i}}static assign(e,...t){const r=e;let i,n;if(Object.assign)return Object.assign(e,...t);for(i=0,n=t.length;i<n;i+=1){const e=t[i];if("object"==typeof e&&null!==e){Object.keys(e).forEach((t=>{r[t]=e[t]}))}}return e}static getBrowserAlias(e){return BROWSER_ALIASES_MAP[e]}static getBrowserTypeByAlias(e){return BROWSER_MAP[e]||""}}const commonVersionIdentifier=/version\/(\d+(\.?_?\d+)+)/i,browsersList=[{test:[/googlebot/i],describe(e){const t={name:"Googlebot"},r=Utils.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/opera/i],describe(e){const t={name:"Opera"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe(e){const t={name:"Opera"},r=Utils.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe(e){const t={name:"Samsung Internet for Android"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe(e){const t={name:"NAVER Whale Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe(e){const t={name:"MZ Browser"},r=Utils.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/focus/i],describe(e){const t={name:"Focus"},r=Utils.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/swing/i],describe(e){const t={name:"Swing"},r=Utils.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/coast/i],describe(e){const t={name:"Opera Coast"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(e){const t={name:"Opera Touch"},r=Utils.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe(e){const t={name:"Yandex Browser"},r=Utils.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe(e){const t={name:"UC Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe(e){const t={name:"Maxthon"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe(e){const t={name:"Epiphany"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe(e){const t={name:"Puffin"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe(e){const t={name:"Sleipnir"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe(e){const t={name:"K-Meleon"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe(e){const t={name:"WeChat"},r=Utils.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe(e){const t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=Utils.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe(e){const t={name:"Internet Explorer"},r=Utils.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe(e){const t={name:"Microsoft Edge"},r=Utils.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe(e){const t={name:"Microsoft Edge"},r=Utils.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe(e){const t={name:"Vivaldi"},r=Utils.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe(e){const t={name:"SeaMonkey"},r=Utils.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe(e){const t={name:"Sailfish"},r=Utils.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe(e){const t={name:"Amazon Silk"},r=Utils.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe(e){const t={name:"PhantomJS"},r=Utils.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe(e){const t={name:"SlimerJS"},r=Utils.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t={name:"BlackBerry"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe(e){const t={name:"WebOS Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe(e){const t={name:"Bada"},r=Utils.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe(e){const t={name:"Tizen"},r=Utils.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe(e){const t={name:"QupZilla"},r=Utils.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe(e){const t={name:"Firefox"},r=Utils.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe(e){const t={name:"Electron"},r=Utils.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe(e){const t={name:"Miui"},r=Utils.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe(e){const t={name:"Chromium"},r=Utils.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe(e){const t={name:"Chrome"},r=Utils.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe(e){const t={name:"Google Search"},r=Utils.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test(e){const t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe(e){const t={name:"Android Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe(e){const t={name:"PlayStation 4"},r=Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe(e){const t={name:"Safari"},r=Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/.*/i],describe(e){const t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:Utils.getFirstMatch(t,e),version:Utils.getSecondMatch(t,e)}}}];var osParsersList=[{test:[/Roku\/DVP/],describe(e){const t=Utils.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe(e){const t=Utils.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe(e){const t=Utils.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=Utils.getWindowsVersionName(t);return{name:OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(e){const t={name:OS_MAP.iOS},r=Utils.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe(e){const t=Utils.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=Utils.getMacOSVersionName(t),i={name:OS_MAP.MacOS,version:t};return r&&(i.versionName=r),i}},{test:[/(ipod|iphone|ipad)/i],describe(e){const t=Utils.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:OS_MAP.iOS,version:t}}},{test(e){const t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe(e){const t=Utils.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=Utils.getAndroidVersionName(t),i={name:OS_MAP.Android,version:t};return r&&(i.versionName=r),i}},{test:[/(web|hpw)[o0]s/i],describe(e){const t=Utils.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t=Utils.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||Utils.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||Utils.getFirstMatch(/\bbb(\d+)/i,e);return{name:OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe(e){const t=Utils.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe(e){const t=Utils.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:()=>({name:OS_MAP.Linux})},{test:[/CrOS/],describe:()=>({name:OS_MAP.ChromeOS})},{test:[/PlayStation 4/],describe(e){const t=Utils.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:OS_MAP.PlayStation4,version:t}}}],platformParsersList=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(e){const t=Utils.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:PLATFORMS_MAP.tablet})},{test(e){const t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe(e){const t=Utils.getFirstMatch(/(ipod|iphone)/i,e);return{type:PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"blackberry"===e.getBrowserName(!0),describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"BlackBerry"})},{test:e=>"bada"===e.getBrowserName(!0),describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"windows phone"===e.getBrowserName(),describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"Microsoft"})},{test(e){const t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:()=>({type:PLATFORMS_MAP.tablet})},{test:e=>"android"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"macos"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop,vendor:"Apple"})},{test:e=>"windows"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop})},{test:e=>"linux"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop})},{test:e=>"playstation 4"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.tv})},{test:e=>"roku"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.tv})}],enginesParsersList=[{test:e=>"microsoft edge"===e.getBrowserName(!0),describe(e){if(/\sedg\//i.test(e))return{name:ENGINE_MAP.Blink};const t=Utils.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe(e){const t={name:ENGINE_MAP.Trident},r=Utils.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:e=>e.test(/presto/i),describe(e){const t={name:ENGINE_MAP.Presto},r=Utils.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test(e){const t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe(e){const t={name:ENGINE_MAP.Gecko},r=Utils.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:ENGINE_MAP.Blink})},{test:[/(apple)?webkit/i],describe(e){const t={name:ENGINE_MAP.WebKit},r=Utils.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];class Parser{constructor(e,t=!1){if(null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=Utils.find(browsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=Utils.find(osParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||"":t||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||"":t||""}parsePlatform(){this.parsedResult.platform={};const e=Utils.find(platformParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=Utils.find(enginesParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return Utils.assign({},this.parsedResult)}satisfies(e){const t={};let r=0;const i={};let n=0;if(Object.keys(e).forEach((s=>{const o=e[s];"string"==typeof o?(i[s]=o,n+=1):"object"==typeof o&&(t[s]=o,r+=1)})),r>0){const e=Object.keys(t),r=Utils.find(e,(e=>this.isOS(e)));if(r){const e=this.satisfies(t[r]);if(void 0!==e)return e}const i=Utils.find(e,(e=>this.isPlatform(e)));if(i){const e=this.satisfies(t[i]);if(void 0!==e)return e}}if(n>0){const e=Object.keys(i),t=Utils.find(e,(e=>this.isBrowser(e,!0)));if(void 0!==t)return this.compareVersion(i[t])}}isBrowser(e,t=!1){const r=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const n=Utils.getBrowserTypeByAlias(i);return t&&n&&(i=n.toLowerCase()),i===r}compareVersion(e){let t=[0],r=e,i=!1;const n=this.getBrowserVersion();if("string"==typeof n)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(i=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(i=!0,r=e.substr(1)),t.indexOf(Utils.compareVersions(n,r,i))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some((e=>this.is(e)))}}
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("events")):"function"==typeof define&&define.amd?define(["exports","events"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BoomMeeting={},e.events)}(this,(function(exports,events){"use strict";var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function __awaiter(e,t,r,i){return new(r||(r=Promise))((function(s,o){function n(e){try{d(i.next(e))}catch(e){o(e)}}function a(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}d((i=i.apply(e,t||[])).next())}))}function __values(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,s,o=r.call(e),n=[];try{for(;(void 0===t||t-- >0)&&!(i=o.next()).done;)n.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(s)throw s.error}}return n}function __spreadArray(e,t,r){if(r||2===arguments.length)for(var i,s=0,o=t.length;s<o;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}var ee$2=Object.defineProperty,D$2=(e,t)=>{for(var r in t)ee$2(e,r,{get:t[r],enumerable:!0})},s=class extends Error{constructor(e,t,r){let i;super(),this.boom_error_flag_="__BOOM_ERROR___",this.code=e,i="string"==typeof t?t:JSON.stringify(t),this.message=i,r&&(this.name=r)}toString(){return JSON.stringify({code:this.code,message:this.message})}getCode(){return this.code}getMessage(){return this.message}},ne=(i=ne||{},i[i.BloudLock=28]="BloudLock",i[i.ShareScreenNoPermission=100]="ShareScreenNoPermission",i[i.ShareScreenCanceled=101]="ShareScreenCanceled",i[i.ShareScreenOtherError=102]="ShareScreenOtherError",i[i.ShareScreenContentHintError=103]="ShareScreenContentHintError",i[i.ShareScreenClientJoinedError=104]="ShareScreenClientJoinedError",i[i.BrtcShareSigError=105]="BrtcShareSigError",i[i.ToggleShareScreenError=106]="ToggleShareScreenError",i[i.BrtcCreateStreamError=107]="BrtcCreateStreamError",i[i.BrtcSubscribeError=108]="BrtcSubscribeError",i[i.BrtcPublishError=109]="BrtcPublishError",i[i.BrtcUnsubscribeError=110]="BrtcUnsubscribeError",i[i.BrtcUnPublishError=111]="BrtcUnPublishError",i[i.RepeatJoinError=112]="RepeatJoinError",i[i.ProxiesUrlTypeError=113]="ProxiesUrlTypeError",i[i.getBloudProxiesUrlError=114]="getBloudProxiesUrlError",i[i.JoinUserInfoError=115]="JoinUserInfoError",i[i.JoinTypeError=116]="JoinTypeError",i[i.JoinBrtcError=117]="JoinBrtcError",i[i.JoinBloudError=118]="JoinBloudError",i[i.UpdateCustomStatsError=119]="UpdateCustomStatsError",i[i.CreateBloudError=120]="CreateBloudError",i),Rn=new s(100,"没有打开共享屏幕录制权限","no share permission"),On=new s(101,"取消共享屏幕","cancel share"),yn=e=>new s(102,e),i;new s(103,"设置 共享屏幕视频流的 contentHint 失效","set share video contentHint failed");var Un=new s(104,"共享屏幕brtc client入会失败","share client join failed"),Bn=new s(105,"brtcShareSig为空","brtc share sig is empty"),Dn=e=>new s(106,e,"toggle share has error"),vn=new s(112,"正在 join,请勿重复调用","repeat join error"),_n=new s(113,"proxies url 必须为字符串","get bloud proxies param error"),Ln=e=>new s(114,e,"get bloud proxies error"),In=new s(115,"userinfo传递错误,请检查"),wn=new s(116,"type传递错误,请检查"),Pn=e=>new s(117,e,"join brtc error"),Mn=e=>new s(107,"brtc 创建本地流失败"),kn=e=>new s(109,e,"brtc pub failed"),Jn=e=>new s(110,e,"brtc sub failed"),jn=e=>new s(110,e,"brtc unpub failed"),Vn=e=>new s(119,e,"bloud updateCustomStats failed"),re$1=(a=re$1||{},a[a.BmJoinError=200]="BmJoinError",a[a.BMLeaveError=201]="BMLeaveError",a[a.BmSetRemoteVideoEnable=202]="BmSetRemoteVideoEnable",a[a.BmSetRemoteAudioEnable=203]="BmSetRemoteAudioEnable",a[a.BmSetLocalVideoEnable=204]="BmSetLocalVideoEnable",a[a.BmSetLocalAudioEnable=205]="BmSetLocalAudioEnable",a[a.BmSetLocalSpeakerEnable=206]="BmSetLocalSpeakerEnable",a[a.BmChangeMasterError=207]="BmChangeMasterError",a[a.BmUpdateManagerError=208]="BmUpdateManagerError",a[a.BmEvictUserError=209]="BmEvictUserError",a[a.BmUpdateUserError=210]="BmUpdateUserError",a[a.BmSetAudioOffError=211]="BmSetAudioOffError",a[a.BmSetVideoOffError=212]="BmSetVideoOffError",a[a.BmSetMsgOffError=213]="BmSetMsgOffError",a[a.BmUpdateCustomStatsError=214]="BmUpdateCustomStatsError",a[a.BmChangeVideoProfileError=215]="BmChangeVideoProfileError",a[a.BmChangeAudioProfileError=216]="BmChangeAudioProfileError",a[a.BmCheckDeviceError=217]="BmCheckDeviceError",a),Hn=e=>new s(201,e,"boommeeting leave failed"),Gn=e=>new s(202,e,"开关对端摄像头失败"),$n=e=>new s(203,e,"开关对端麦克风发生失败"),zn=e=>new s(204,e,"开关本地摄像头失败"),Kn=e=>new s(205,e,"开关本地麦克风失败"),Xn=e=>new s(206,e,"开关扬声器失败"),qn=e=>new s(207,e,"转移主持人发生错误"),Qn=e=>new s(208,e,"改变联席主持人发生错误"),Zn=e=>new s(209,e,"踢出用户发生错误"),tr=e=>new s(210,e,"更新用户信息发生错误"),er=e=>new s(211,e,"全员静音发生错误"),nr$1=e=>new s(212,e,"全员禁用摄像头发生错误"),rr=e=>new s(213,e,"全员禁用聊天发生错误"),or=e=>new s(214,e,"更新房间自定义属性状态发生错误"),sr$1=e=>new s(215,e,"远程调节对方视频发生错误"),ir=e=>new s(216,e,"远程调节对方音频发生错误"),cr=e=>new s(217,e,"远程检测对方设备发生错误"),oe$1=(c=oe$1||{},c[c.createStream=1302]="createStream",c[c.noCameraDevice=1303]="noCameraDevice",c[c.noMicroDevice=1304]="noMicroDevice",c[c.noSpeakerDevice=1305]="noSpeakerDevice",c[c.openCamera=1301]="openCamera",c[c.cameraNotAuth=1314]="cameraNotAuth",c[c.cameraOccupy=1315]="cameraOccupy",c[c.openMicro=1302]="openMicro",c[c.micNotAuth=1317]="micNotAuth",c[c.micOccupy=1319]="micOccupy",c[c.streamDisconnected=1320]="streamDisconnected",c[c.syncFail=1321]="syncFail",c[c.getStreamFail=1322]="getStreamFail",c[c.streamConnectError=1323]="streamConnectError",c[c.streamReconnectSuccess=1324]="streamReconnectSuccess",c[c.streamReconnectFailed=1325]="streamReconnectFailed",c[c.shareStreamConnectError=1326]="shareStreamConnectError",c[c.shareStreamConnectSuccess=1327]="shareStreamConnectSuccess",c[c.shareStreamConnectFailed=1328]="shareStreamConnectFailed",c),ar=e=>new s(1302,`采集${e}流失败,请重试`),pr$1=e=>new s(1322,`当前${e}不可用, 请确保您的${e}连接正确, 或更换其他${e}`),mr$1=()=>new s(1301,"打开摄像头失败"),Er$1=()=>new s(1314,"摄像头设备未授权, 无法开启视频, 启动摄像头失败, 请在系统或浏览器“设置-隐私”中允许使用摄像头"),gr$1=()=>new s(1315,"当前摄像头被占用, 请检查或切换其他摄像头"),xr$1=()=>new s(1302,"打开麦克风失败"),Sr$1=()=>new s(1317,"麦克风设备未授权, 无法开启麦克风, 启动麦克风失败, 请在系统或浏览器“设置-隐私”中允许使用麦克风"),Tr$1=()=>new s(1319,"当前麦克风被占用, 请检查或切换其他麦克风"),hr=e=>new s(1320,`${e}连接已断开,正在重试,请稍后`),dr=()=>new s(1321,"状态同步异常,请重试, 麦克风和摄像头已自动关闭"),Nr$1=()=>new s(1323,"网络连接异常,正在重试"),br=()=>new s(1326,"共享屏幕网络连接异常,正在重试"),Rr$1=(e,t)=>{let r="";return e&&t?r="麦克风和摄像头":e?r="麦克风":t&&(r="摄像头"),new s(1324,`网络连接成功, ${r}已自动打开`)},Or$1=()=>new s(1327,"共享屏幕网络连接成功, 已自动打开"),yr$1=()=>new s(1325,"网络连接失败,请检查网络,麦克风和摄像头已自动关闭"),Ar=()=>new s(1325,"共享屏幕网络连接失败,请检查网络,共享屏幕已自动关闭"),c,a;function tt$1(e,t,r,i){let s=[];return r&&s.push(r),i&&s.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${s.join("|")}] ${t}`}var se=(r=se||{},r[r.INFO=0]="INFO",r[r.WARN=1]="WARN",r[r.ERROR=2]="ERROR",r[r.CLOSE=3]="CLOSE",r),m$1=class e{static setStorageCallBack(t){e.storageCallBack=t}static setEnableUpload(t){e.enableUpload=t}static setLogLevel(t){e.logLevel=t}static setNamespace(t){e.namespace=t}static info(t,r,i,s=[]){e.logLevel<=0&&(s.unshift(tt$1("INFO",t,r,i)),console.info(...s),e.storageCallBack&&e.storageCallBack(s.join(""),1))}static warn(t,r,i,s=[]){e.logLevel<=1&&(s.unshift(tt$1("WARN",t,r,i)),console.warn(...s),e.storageCallBack&&e.storageCallBack(s.join(""),2))}static error(t,r,i,s=[]){e.logLevel<=2&&(s.unshift(tt$1("ERROR",t,r,i)),console.error(...s),e.storageCallBack&&e.storageCallBack(s.join(""),3))}},r;m$1.enableUpload=!1,m$1.logLevel=0,m$1.namespace="boom-core";var kt$1=m$1,H$1={};D$2(H$1,{CHANGE_MASTER:()=>ct$1,CUSTOM_MESSAGE:()=>ft$2,ERROR:()=>ot$1,EVICTED:()=>gt$2,LEAVE_USERS:()=>St$2,MOVE_USER_ROOM:()=>mt$2,PARTICIPANT_JOINED:()=>et$1,PARTICIPANT_LEFT:()=>nt$1,RECONNECTED:()=>ce,RECONNECTING:()=>ae$1,ROOM_CLOSED:()=>rt$1,ROOM_CONNECTED:()=>me$1,ROOM_SYNCED:()=>Ee$1,SEND_MESSAGE:()=>ut$1,SESSION_CLOED:()=>fe$1,STATE_NOTIFY:()=>le$1,STREAM_PUBLISHED:()=>at$1,STREAM_REMOVED:()=>pt$2,STREAM_UPDATE:()=>Et$1,SYNC_FAILED:()=>ge$1,TIMEOUT:()=>ie$1,TOKEN_EXPIRE:()=>ue$1,TOKEN_WILL_EXPIRE:()=>pe$1,UPDATE_CUSTOM_STATS:()=>lt$1,UPDATE_STATS:()=>st$1,UPDATE_STREAM:()=>Tt,UPDATE_USER:()=>it$1,USER_REJOINED:()=>xt$1});var et$1="participant-joined",nt$1="participant-left",rt$1="room-closed",ot$1="room-error",ie$1="network-error",ce="room-reconnected",ae$1="room-reconnecting",st$1="update-stats",it$1="participant-update",ct$1="change-master",at$1="participant-published",pt$2="participant-unpublished",ut$1="new-message",ft$2="custom-message",lt$1="update-custom-stats",mt$2="move-user-room",Et$1="stream-update",gt$2="participant-evicted",xt$1="user-rejoined",pe$1="token-will-expire",ue$1="token-expire",fe$1="session-close",le$1="state-notify",St$2="leaveUsers",Tt="update-stream",me$1="room-connected",Ee$1="room-synced",ge$1="sync-failed",xe$1={joinUser:et$1,leaveUser:nt$1,roomClosed:rt$1,roomError:ot$1,updateStats:st$1,updateUser:it$1,changeMaster:ct$1,publishStream:at$1,unpublishStream:pt$2,sendMessage:ut$1,customMessage:ft$2,updateCustomStats:lt$1,moveUserRoom:mt$2,streamUpdate:Et$1,evicted:gt$2,userRejoined:xt$1,leaveUsers:St$2,updateStream:Tt},ht$1={};D$2(ht$1,{PLAYER_STATE_CHANGED:()=>Se});var Se="player-state-changed",dt$1={};D$2(dt$1,{BRTC_ROOM_RECONNECTED:()=>ye$1,BRTC_ROOM_ROCONNECTING:()=>Oe$1,BRTC_SYNC_ROOM_COMPLETED:()=>Re$1,CLIENT_BANNED:()=>de$1,ERROR:()=>Te$1,ROOM_CLOSED:()=>be$1,STREAM_PUBLISHED:()=>he,USER_KICKED:()=>Ne$1});var Te$1="error",he="stream-published",de$1="client-banned",Ne$1="user-kicked",be$1="room-closed",Re$1="sync-room-completed",Oe$1="brtc-room-reconnecting",ye$1="brtc-room-reconnected",Nt$1={};D$2(Nt$1,{BRTC_SHARE_SYNC_ROOM_COMPLETED:()=>Ue,JOIN_READY:()=>Ae$1});var Ae$1="join-ready",Ue="brtc-share-sync-room-completed",O$2={};D$2(O$2,{array:()=>N$2,arrayBuffer:()=>Je$1,boolean:()=>We$1,func:()=>h$1,isPlainObject:()=>K$2,number:()=>z$2,numeric:()=>Ot$1,object:()=>S$1,range:()=>ke$1,string:()=>b$2});var g={};D$2(g,{DOCUMENT:()=>Ce$1,EMPTY_ARRAY:()=>bt$1,EMPTY_FUNCTION:()=>$$1,EMPTY_OBJECT:()=>Me$1,EMPTY_STRING:()=>U$1,FALSE:()=>f$1,GLOBAL:()=>G$2,KEYPATH_CURRENT:()=>Fe$1,KEYPATH_PARENT:()=>Pe,MINUS_ONE:()=>I$1,NULL:()=>R$1,RAW_DOT:()=>M$1,RAW_FALSE:()=>De$1,RAW_FUNCTION:()=>P$2,RAW_LENGTH:()=>Le$1,RAW_NULL:()=>ve$1,RAW_SLASH:()=>Ie$1,RAW_TAG:()=>we$1,RAW_THIS:()=>Jt,RAW_TRUE:()=>Be$1,RAW_UNDEFINED:()=>w$2,RAW_VALUE:()=>_e$1,RAW_WILDCARD:()=>jt$1,TRUE:()=>T$2,UNDEFINED:()=>l$1,WINDOW:()=>W$1});var T$2=!0,f$1=!1,R$1=null,l$1=void 0,I$1=-1,Be$1="true",De$1="false",ve$1="null",w$2="undefined",Jt="this",_e$1="value",Le$1="length",P$2="function",jt$1="*",M$1=".",Ie$1="/",we$1="tag",Pe="..",Fe$1=Jt,W$1=typeof window!==w$2?window:void 0,Ce$1=typeof document!==w$2?document:void 0,G$2=typeof global!==w$2?global:W$1,$$1=function(){},Me$1=Object.freeze({}),bt$1=Object.freeze([]),U$1="";function h$1(e){return typeof e===P$2}function N$2(e){return Array.isArray(e)}function S$1(e){return null!==e&&"object"==typeof e}function b$2(e){return"string"==typeof e}function z$2(e){return"number"==typeof e&&!isNaN(e)}function We$1(e){return"boolean"==typeof e}function Ot$1(e){return z$2(e)||b$2(e)&&!isNaN(parseFloat(e))&&isFinite(+e)}var Rt$1={}.hasOwnProperty;function K$2(e){if(!S$1(e)||e.nodeType||e===e.window||e.constructor&&!Rt$1.call(e,"constructor")&&!Rt$1.call(e.constructor.prototype||{},"isPrototypeOf"))return!1;let t;for(t in e);return void 0===t||Rt$1.call(e,t)}function ke$1(e,t,r){return e>=t&&e<=r}function Je$1(e){return e instanceof ArrayBuffer}function Vt(e){if(b$2(e))return e;if(S$1(e)){if(b$2(e.message))return e.message;if(b$2(e.msg))return e.msg;if(h$1(e.toString))return e.toString()}return"unknow"}var J$1={};function k$2(e,t,r){if(h$1(e))return N$2(r)?e.apply(t,r):void 0!==t?e.call(t,r):void 0!==r?e(r):e()}function d$1(e,t,r){if(!e)return;let{length:i}=e;if(i)if(r)for(let r=i-1;r>=0&&!1!==t(e[r],r);r--);else for(let r=0;r<i&&!1!==t(e[r],r);r++);}function je$1(e,t){e[e.length]=t}function Ve$1(e,t){e.unshift(t)}function Yt$1(e,t,r){N$2(t)?d$1(t,(function(t){r(e,t)})):r(e,t)}function yt$2(e,t){Yt$1(e,t,je$1)}function Ye$1(e,t){Yt$1(e,t,Ve$1)}function Ht(e,t,r){let i=-1;return d$1(e,(function(e,s){if(!1===r?e==t:e===t)return i=s,!1})),i}function He$1(e){let{length:t}=e;if(t>0)return e[t-1]}function Ge$1(e){let{length:t}=e;if(t>0)return e.pop()}function $e(e,t,r){let i=0;return d$1(e,(function(s,o){(!1===r?s==t:s===t)&&(e.splice(o,1),i++)}),!0),i}function At$1(e,t,r){return Ht(e,t,r)>=0}function ze$1(e){return N$2(e)?e:k$2(bt$1.slice,e)}function Ke$1(e,t,r){let i={};return d$1(e,(function(e){i[t?e[t]:e]=r||e})),i}function Xe$1(e,t){return e.join(t)}function qe$1(e){return!N$2(e)||!e.length}D$2(J$1,{each:()=>d$1,falsy:()=>qe$1,has:()=>At$1,indexOf:()=>Ht,join:()=>Xe$1,last:()=>He$1,pop:()=>Ge$1,push:()=>yt$2,remove:()=>$e,toArray:()=>ze$1,toObject:()=>Ke$1,unshift:()=>Ye$1});var F$1=class e{constructor(t,r){this.type=t,this.phase=e.PHASE_CURRENT,r&&(this.originalEvent=r)}preventDefault(){let e=this;if(!e.isPrevented){let{originalEvent:t}=e;t&&t.preventDefault(),e.isPrevented=!0}return e}stopPropagation(){let e=this;if(!e.isStoped){let{originalEvent:t}=e;t&&t.stopPropagation(),e.isStoped=!0}return e}prevent(){return this.preventDefault()}stop(){return this.stopPropagation()}};F$1.PHASE_CURRENT=0,F$1.PHASE_UPWARD=1,F$1.PHASE_DOWNWARD=-1;var j$2=F$1,X$2={};function C$2(e,t){return null!=e&&e.toString?e.toString():void 0!==t?t:U$1}function Ut$1(e,t,r){return z$2(r)?t===r?U$1:e.slice(t,r):e.slice(t)}function Bt$1(e,t,r){return e.indexOf(t,void 0!==r?r:0)}function Dt$1(e,t){return Bt$1(e,t)>=0}D$2(X$2,{clear:()=>nn,copy:()=>V$2,diff:()=>$t$1,each:()=>y$1,extend:()=>wt$1,falsy:()=>an,get:()=>on$1,has:()=>cn,keys:()=>Pt$1,merge:()=>rn,param:()=>pn,set:()=>sn,sort:()=>en,toArray:()=>un,update:()=>zt});var _t$1={};function Lt$1(e,t){let r=_t$1.hasOwnProperty(e)?_t$1[e]:_t$1[e]=e.split(M$1);for(let e=0,i=r.length-1;e<=i&&!1!==t(r[e],e===i);e++);}function It$1(e){return void 0!==e}function Pt$1(e){return It$1(e)?Object.keys(e):[]}function Ze$1(e,t){return e.length-t.length}function tn(e,t){return t.length-e.length}function en(e,t){return Pt$1(e).sort(t?tn:Ze$1)}function y$1(e,t){for(let r in e)if(!1===t(e[r],r))break}function nn(e){y$1(e,(function(t,r){delete e[r]}))}function Gt$1(e,t){return S$1(e)?S$1(t)?(y$1(t,(function(t,r){e[r]=t})),e):e:t}function wt$1(e,t,r){return Gt$1(Gt$1(e,t),r)}function rn(e,t){return e&&t?wt$1(wt$1({},e),t):e||t}function V$2(e,t){let r=e;return N$2(e)?t?(r=[],d$1(e,(function(e,i){r[i]=V$2(e,t)}))):r=e.slice():S$1(e)&&(r={},y$1(e,(function(e,i){r[i]=t?V$2(e,t):e}))),r}function on$1(e,t,r){let i;return Lt$1(t,(function(t,r){if(null==e)return i=void 0,!1;{let s=e[t];r?i=void 0!==s?s:void 0:e=s}})),void 0===i&&(i=r),i}function sn(e,t,r,i){Lt$1(t,(function(t,s){if(s)e[t]=r;else if(e[t])e=e[t];else{if(!i)return!1;e=e[t]={}}}))}function cn(e,t){return void 0!==e[t]}function an(e){return!S$1(e)||N$2(e)||!Pt$1(e).length}function $t$1(e,t){let r=[];return y$1(e,((e,i)=>{N$2(e)||K$2(e)?(null==t[i]||$t$1(e,t[i]).length>0)&&r.push(i):e!==t[i]&&r.push(i)})),r}function pn(e){let t=[],r=(e,r)=>{r=h$1(r)?r():null==r?"":r,t[t.length]=encodeURIComponent(e)+"="+encodeURIComponent(r)};return(N$2(e)||K$2(e))&&(N$2(e)?d$1(e,((e,t)=>{r(t,e)})):y$1(e,((e,t)=>{r(t,e)}))),t.join("&").replace(/%20/g,"+")}function un(e){let t=[];return y$1(e,(e=>{t.push(e)})),t}function zt(e,t){if(S$1(e)&&S$1(t))return y$1(t,((r,i)=>{S$1(r)&&S$1(e[i])?zt(e[i],r):e[i]=t[i]})),e}var fn=1,ln=2,Kt=3,Xt$1=5,Y$1=typeof console!==w$2?console:null,mn=/yox/.test(C$2($$1))?ln:Kt,Ft$1=W$1&&/edge|msie|trident/i.test(W$1.navigator.userAgent)?U$1:"%c",En=Y$1?Ft$1?function(e,t,r,i){i?Y$1.log(Ft$1+e,r,t,i):Y$1.log(Ft$1+e,r,t)}:function(e,t,r){r?Y$1.log(e,t,r):Y$1.log(e,t)}:$$1;function qt$1(){if(G$2){let e=G$2.YOX_LOG_LEVEL;if(e>=fn&&e<=Xt$1)return e}return mn}function gn(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function Ct$1(e,t){qt$1()<=Kt&&En(t||"bjy warn",e,gn("#f90"))}function Qt$1(e,t){if(qt$1()<=Xt$1)throw new Error(`[${t||"bjy fatal"}]: ${e}`)}var q$1=class{constructor(e){this.ns=e||!1,this.listeners={}}fire(e,t,r){let i=this,s=b$2(e)?i.parse(e):e,o=i.listeners[s.type],n=!0;if(o){o=V$2(o);let e=t&&t[0]instanceof j$2?t[0]:void 0;d$1(o,(function(a){if(!Mt$1(s.ns,a,!0)||!At$1(o,a)||r&&!r(s,t,a))return;e&&(e.listener=a.fn);let d=k$2(a.fn,a.ctx,t);return e&&(e.listener=void 0),a.num=a.num?a.num+1:1,a.num===a.max&&i.off(s,a.fn),e&&(!1===d?e.prevent().stop():e.isStoped&&(d=!1)),!1===d?n=!1:void 0}))}return n}on(e,t){let r=this,i=r.listeners,s=h$1(t)?{fn:t}:t;if(S$1(s)&&h$1(s.fn)){let t=b$2(e)?r.parse(e):e;s.ns=t.ns,yt$2(i[t.type]||(i[t.type]=[]),s)}else"development"===process.env.NODE_ENV&&Qt$1('emitter.on(types, listener) invoke failed:\n\n"listener" is expected to be a Function or an EmitterOptions.\n');return this}one(e,t){return h$1(t)?t={fn:t,max:1}:t.max=1,this.on(e,t)}off(e,t){let r=this,i=r.listeners;if(e){let s=b$2(e)?r.parse(e):e,o=s.type,n=s.ns,a=Zt(t),d=function(e,t){d$1(e,(function(t,r){a(t)&&e.splice(r,1)}),!0),e.length||delete i[t]};o?i[o]&&d(i[o],o):n&&y$1(i,(function(e,t){d$1(e,(function(t,r){Mt$1(n,t)&&e.splice(r,1)}),!0),e.length||delete i[t]})),"development"===process.env.NODE_ENV&&arguments.length>1&&null==t&&Ct$1(`emitter.off(type, listener) is invoked, but "listener" is ${t}.`)}else r.listeners={},"development"===process.env.NODE_ENV&&arguments.length>0&&Ct$1(`emitter.off(type) is invoked, but "type" is ${e}.`)}has(e,t){let r=this.listeners,i=b$2(e)?this.parse(e):e,s=i.type,o=i.ns,n=!0,a=Zt(t);return s?r[s]&&function(e){d$1(e,(function(e){if(a(e))return n=!1}))}(r[s]):o&&y$1(r,(function(e){return d$1(e,(function(e){if(Mt$1(o,e))return n=!1})),n})),!n}parse(e){let t={type:e,ns:U$1};if(this.ns){let r=Bt$1(e,M$1);r>=0&&(t.type=Ut$1(e,0,r),t.ns=Ut$1(e,r+1))}return t}},Q$2;function Sn(){return!0}function Zt(e){return h$1(e)?function(t){return e===t.fn}:Sn}function Mt$1(e,t,r){let{ns:i}=t;return i&&e?i===e:!!r}function te$2(){return Date.now()}function Tn(e,t){return Ot$1(e)?+e:void 0!==t?t:0}function Wt(e){return h$1(e)&&Dt$1(C$2(e),"[native code]")}typeof setImmediate===P$2&&Wt(setImmediate)&&(Q$2=setImmediate),Q$2=typeof MessageChannel===P$2&&Wt(MessageChannel)?function(e){let t=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(1)}:setTimeout;var hn=Q$2,global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeGlobal$1=freeGlobal,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal$1||freeSelf||Function("return this")(),root$1=root,Symbol$1=root$1.Symbol,Symbol$2=Symbol$1,objectProto$7=Object.prototype,hasOwnProperty$5=objectProto$7.hasOwnProperty,nativeObjectToString$1=objectProto$7.toString,symToStringTag$1=Symbol$2?Symbol$2.toStringTag:void 0;function getRawTag(e){var t=hasOwnProperty$5.call(e,symToStringTag$1),r=e[symToStringTag$1];try{e[symToStringTag$1]=void 0;var i=!0}catch(e){}var s=nativeObjectToString$1.call(e);return i&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),s}var objectProto$6=Object.prototype,nativeObjectToString=objectProto$6.toString;function objectToString(e){return nativeObjectToString.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$2?Symbol$2.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}var symbolTag="[object Symbol]";function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag}var isArray=Array.isArray,isArray$1=isArray,reWhitespace=/\s/;function trimmedEndIndex(e){for(var t=e.length;t--&&reWhitespace.test(e.charAt(t)););return t}var reTrimStart=/^\s+/;function baseTrim(e){return e?e.slice(0,trimmedEndIndex(e)+1).replace(reTrimStart,""):e}function isObject(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var NAN=NaN,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt;function toNumber(e){if("number"==typeof e)return e;if(isSymbol(e))return NAN;if(isObject(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=isObject(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=baseTrim(e);var r=reIsBinary.test(e);return r||reIsOctal.test(e)?freeParseInt(e.slice(2),r?2:8):reIsBadHex.test(e)?NAN:+e}function identity$1(e){return e}var asyncTag="[object AsyncFunction]",funcTag$1="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction$1(e){if(!isObject(e))return!1;var t=baseGetTag(e);return t==funcTag$1||t==genTag||t==asyncTag||t==proxyTag}var coreJsData=root$1["__core-js_shared__"],coreJsData$1=coreJsData,maskSrcKey=(uid=/[^.]+$/.exec(coreJsData$1&&coreJsData$1.keys&&coreJsData$1.keys.IE_PROTO||""),uid?"Symbol(src)_1."+uid:""),uid;function isMasked(e){return!!maskSrcKey&&maskSrcKey in e}var funcProto$1=Function.prototype,funcToString$1=funcProto$1.toString;function toSource(e){if(null!=e){try{return funcToString$1.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,funcProto=Function.prototype,objectProto$5=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$4=objectProto$5.hasOwnProperty,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty$4).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function baseIsNative(e){return!(!isObject(e)||isMasked(e))&&(isFunction$1(e)?reIsNative:reIsHostCtor).test(toSource(e))}function getValue(e,t){return null==e?void 0:e[t]}function getNative(e,t){var r=getValue(e,t);return baseIsNative(r)?r:void 0}function apply(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var HOT_COUNT=800,HOT_SPAN=16,nativeNow=Date.now;function shortOut(e){var t=0,r=0;return function(){var i=nativeNow(),s=HOT_SPAN-(i-r);if(r=i,s>0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function constant(e){return function(){return e}}var defineProperty=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),defineProperty$1=defineProperty,baseSetToString=defineProperty$1?function(e,t){return defineProperty$1(e,"toString",{configurable:!0,enumerable:!1,value:constant(t),writable:!0})}:identity$1,baseSetToString$1=baseSetToString,setToString=shortOut(baseSetToString$1),setToString$1=setToString,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/;function isIndex(e,t){var r=typeof e;return!!(t=null==t?MAX_SAFE_INTEGER$1:t)&&("number"==r||"symbol"!=r&&reIsUint.test(e))&&e>-1&&e%1==0&&e<t}function eq(e,t){return e===t||e!=e&&t!=t}var nativeMax$1=Math.max;function overRest(e,t,r){return t=nativeMax$1(void 0===t?e.length-1:t,0),function(){for(var i=arguments,s=-1,o=nativeMax$1(i.length-t,0),n=Array(o);++s<o;)n[s]=i[t+s];s=-1;for(var a=Array(t+1);++s<t;)a[s]=i[s];return a[t]=r(n),apply(e,this,a)}}function baseRest(e,t){return setToString$1(overRest(e,t,identity$1),e+"")}var MAX_SAFE_INTEGER=9007199254740991;function isLength(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=MAX_SAFE_INTEGER}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction$1(e)}function isIterateeCall(e,t,r){if(!isObject(r))return!1;var i=typeof t;return!!("number"==i?isArrayLike(r)&&isIndex(t,r.length):"string"==i&&t in r)&&eq(r[t],e)}var objectProto$4=Object.prototype;function isPrototype(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||objectProto$4)}function baseTimes(e,t){for(var r=-1,i=Array(e);++r<e;)i[r]=t(r);return i}var argsTag$1="[object Arguments]";function baseIsArguments(e){return isObjectLike(e)&&baseGetTag(e)==argsTag$1}var objectProto$3=Object.prototype,hasOwnProperty$3=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(e){return isObjectLike(e)&&hasOwnProperty$3.call(e,"callee")&&!propertyIsEnumerable.call(e,"callee")},isArguments$1=isArguments;function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer=moduleExports$1?root$1.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,isBuffer$1=isBuffer,argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag$1="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(t){return e(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag$1]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal$1.process,nodeUtil=function(){try{var e=freeModule&&freeModule.require&&freeModule.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeUtil$1=nodeUtil,nodeIsTypedArray=nodeUtil$1&&nodeUtil$1.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,isTypedArray$1=isTypedArray,objectProto$2=Object.prototype,hasOwnProperty$2=objectProto$2.hasOwnProperty;function arrayLikeKeys(e,t){var r=isArray$1(e),i=!r&&isArguments$1(e),s=!r&&!i&&isBuffer$1(e),o=!r&&!i&&!s&&isTypedArray$1(e),n=r||i||s||o,a=n?baseTimes(e.length,String):[],d=a.length;for(var u in e)!t&&!hasOwnProperty$2.call(e,u)||n&&("length"==u||s&&("offset"==u||"parent"==u)||o&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||isIndex(u,d))||a.push(u);return a}function nativeKeysIn(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}var objectProto$1=Object.prototype,hasOwnProperty$1=objectProto$1.hasOwnProperty;function baseKeysIn(e){if(!isObject(e))return nativeKeysIn(e);var t=isPrototype(e),r=[];for(var i in e)("constructor"!=i||!t&&hasOwnProperty$1.call(e,i))&&r.push(i);return r}function keysIn(e){return isArrayLike(e)?arrayLikeKeys(e,!0):baseKeysIn(e)}var now=function(){return root$1.Date.now()},now$1=now,FUNC_ERROR_TEXT="Expected a function",nativeMax=Math.max,nativeMin=Math.min;function debounce(e,t,r){var i,s,o,n,a,d,u=0,l=!1,c=!1,h=!0;if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT);function m(t){var r=i,o=s;return i=s=void 0,u=t,n=e.apply(o,r)}function p(e){return u=e,a=setTimeout(v,t),l?m(e):n}function f(e){var r=e-d;return void 0===d||r>=t||r<0||c&&e-u>=o}function v(){var e=now$1();if(f(e))return g(e);a=setTimeout(v,function(e){var r=t-(e-d);return c?nativeMin(r,o-(e-u)):r}(e))}function g(e){return a=void 0,h&&i?m(e):(i=s=void 0,n)}function S(){var e=now$1(),r=f(e);if(i=arguments,s=this,d=e,r){if(void 0===a)return p(d);if(c)return clearTimeout(a),a=setTimeout(v,t),m(d)}return void 0===a&&(a=setTimeout(v,t)),n}return t=toNumber(t)||0,isObject(r)&&(l=!!r.leading,o=(c="maxWait"in r)?nativeMax(toNumber(r.maxWait)||0,t):o,h="trailing"in r?!!r.trailing:h),S.cancel=function(){void 0!==a&&clearTimeout(a),u=0,i=d=s=a=void 0},S.flush=function(){return void 0===a?n:g(now$1())},S}var objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,defaults=baseRest((function(e,t){e=Object(e);var r=-1,i=t.length,s=i>2?t[2]:void 0;for(s&&isIterateeCall(t[0],t[1],s)&&(i=1);++r<i;)for(var o=t[r],n=keysIn(o),a=-1,d=n.length;++a<d;){var u=n[a],l=e[u];(void 0===l||eq(l,objectProto[u])&&!hasOwnProperty.call(e,u))&&(e[u]=o[u])}return e})),pr=defaults,numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}const BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Utils{static getFirstMatch(e,t){const r=t.match(e);return r&&r.length>0&&r[1]||""}static getSecondMatch(e,t){const r=t.match(e);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(e,t,r){if(e.test(t))return r}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,r=!1){const i=Utils.getVersionPrecision(e),s=Utils.getVersionPrecision(t);let o=Math.max(i,s),n=0;const a=Utils.map([e,t],(e=>{const t=o-Utils.getVersionPrecision(e),r=e+new Array(t+1).join(".0");return Utils.map(r.split("."),(e=>new Array(20-e.length).join("0")+e)).reverse()}));for(r&&(n=o-Math.min(i,s)),o-=1;o>=n;){if(a[0][o]>a[1][o])return 1;if(a[0][o]===a[1][o]){if(o===n)return 0;o-=1}else if(a[0][o]<a[1][o])return-1}}static map(e,t){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,t);for(i=0;i<e.length;i+=1)r.push(t(e[i]));return r}static find(e,t){let r,i;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,i=e.length;r<i;r+=1){const i=e[r];if(t(i,r))return i}}static assign(e,...t){const r=e;let i,s;if(Object.assign)return Object.assign(e,...t);for(i=0,s=t.length;i<s;i+=1){const e=t[i];if("object"==typeof e&&null!==e){Object.keys(e).forEach((t=>{r[t]=e[t]}))}}return e}static getBrowserAlias(e){return BROWSER_ALIASES_MAP[e]}static getBrowserTypeByAlias(e){return BROWSER_MAP[e]||""}}const commonVersionIdentifier=/version\/(\d+(\.?_?\d+)+)/i,browsersList=[{test:[/googlebot/i],describe(e){const t={name:"Googlebot"},r=Utils.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/opera/i],describe(e){const t={name:"Opera"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe(e){const t={name:"Opera"},r=Utils.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe(e){const t={name:"Samsung Internet for Android"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe(e){const t={name:"NAVER Whale Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe(e){const t={name:"MZ Browser"},r=Utils.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/focus/i],describe(e){const t={name:"Focus"},r=Utils.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/swing/i],describe(e){const t={name:"Swing"},r=Utils.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/coast/i],describe(e){const t={name:"Opera Coast"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(e){const t={name:"Opera Touch"},r=Utils.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe(e){const t={name:"Yandex Browser"},r=Utils.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe(e){const t={name:"UC Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe(e){const t={name:"Maxthon"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe(e){const t={name:"Epiphany"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe(e){const t={name:"Puffin"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe(e){const t={name:"Sleipnir"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe(e){const t={name:"K-Meleon"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe(e){const t={name:"WeChat"},r=Utils.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe(e){const t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=Utils.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe(e){const t={name:"Internet Explorer"},r=Utils.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe(e){const t={name:"Microsoft Edge"},r=Utils.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe(e){const t={name:"Microsoft Edge"},r=Utils.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe(e){const t={name:"Vivaldi"},r=Utils.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe(e){const t={name:"SeaMonkey"},r=Utils.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe(e){const t={name:"Sailfish"},r=Utils.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe(e){const t={name:"Amazon Silk"},r=Utils.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe(e){const t={name:"PhantomJS"},r=Utils.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe(e){const t={name:"SlimerJS"},r=Utils.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t={name:"BlackBerry"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe(e){const t={name:"WebOS Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe(e){const t={name:"Bada"},r=Utils.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe(e){const t={name:"Tizen"},r=Utils.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe(e){const t={name:"QupZilla"},r=Utils.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe(e){const t={name:"Firefox"},r=Utils.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe(e){const t={name:"Electron"},r=Utils.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe(e){const t={name:"Miui"},r=Utils.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe(e){const t={name:"Chromium"},r=Utils.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe(e){const t={name:"Chrome"},r=Utils.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe(e){const t={name:"Google Search"},r=Utils.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test(e){const t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe(e){const t={name:"Android Browser"},r=Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe(e){const t={name:"PlayStation 4"},r=Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe(e){const t={name:"Safari"},r=Utils.getFirstMatch(commonVersionIdentifier,e);return r&&(t.version=r),t}},{test:[/.*/i],describe(e){const t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:Utils.getFirstMatch(t,e),version:Utils.getSecondMatch(t,e)}}}];var osParsersList=[{test:[/Roku\/DVP/],describe(e){const t=Utils.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe(e){const t=Utils.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe(e){const t=Utils.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=Utils.getWindowsVersionName(t);return{name:OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(e){const t={name:OS_MAP.iOS},r=Utils.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe(e){const t=Utils.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=Utils.getMacOSVersionName(t),i={name:OS_MAP.MacOS,version:t};return r&&(i.versionName=r),i}},{test:[/(ipod|iphone|ipad)/i],describe(e){const t=Utils.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:OS_MAP.iOS,version:t}}},{test(e){const t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe(e){const t=Utils.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=Utils.getAndroidVersionName(t),i={name:OS_MAP.Android,version:t};return r&&(i.versionName=r),i}},{test:[/(web|hpw)[o0]s/i],describe(e){const t=Utils.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t=Utils.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||Utils.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||Utils.getFirstMatch(/\bbb(\d+)/i,e);return{name:OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe(e){const t=Utils.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe(e){const t=Utils.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:()=>({name:OS_MAP.Linux})},{test:[/CrOS/],describe:()=>({name:OS_MAP.ChromeOS})},{test:[/PlayStation 4/],describe(e){const t=Utils.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:OS_MAP.PlayStation4,version:t}}}],platformParsersList=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(e){const t=Utils.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:PLATFORMS_MAP.tablet})},{test(e){const t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe(e){const t=Utils.getFirstMatch(/(ipod|iphone)/i,e);return{type:PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"blackberry"===e.getBrowserName(!0),describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"BlackBerry"})},{test:e=>"bada"===e.getBrowserName(!0),describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"windows phone"===e.getBrowserName(),describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"Microsoft"})},{test(e){const t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:()=>({type:PLATFORMS_MAP.tablet})},{test:e=>"android"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"macos"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop,vendor:"Apple"})},{test:e=>"windows"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop})},{test:e=>"linux"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop})},{test:e=>"playstation 4"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.tv})},{test:e=>"roku"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.tv})}],enginesParsersList=[{test:e=>"microsoft edge"===e.getBrowserName(!0),describe(e){if(/\sedg\//i.test(e))return{name:ENGINE_MAP.Blink};const t=Utils.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe(e){const t={name:ENGINE_MAP.Trident},r=Utils.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:e=>e.test(/presto/i),describe(e){const t={name:ENGINE_MAP.Presto},r=Utils.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test(e){const t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe(e){const t={name:ENGINE_MAP.Gecko},r=Utils.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:ENGINE_MAP.Blink})},{test:[/(apple)?webkit/i],describe(e){const t={name:ENGINE_MAP.WebKit},r=Utils.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];class Parser{constructor(e,t=!1){if(null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=Utils.find(browsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=Utils.find(osParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||"":t||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||"":t||""}parsePlatform(){this.parsedResult.platform={};const e=Utils.find(platformParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=Utils.find(enginesParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return Utils.assign({},this.parsedResult)}satisfies(e){const t={};let r=0;const i={};let s=0;if(Object.keys(e).forEach((o=>{const n=e[o];"string"==typeof n?(i[o]=n,s+=1):"object"==typeof n&&(t[o]=n,r+=1)})),r>0){const e=Object.keys(t),r=Utils.find(e,(e=>this.isOS(e)));if(r){const e=this.satisfies(t[r]);if(void 0!==e)return e}const i=Utils.find(e,(e=>this.isPlatform(e)));if(i){const e=this.satisfies(t[i]);if(void 0!==e)return e}}if(s>0){const e=Object.keys(i),t=Utils.find(e,(e=>this.isBrowser(e,!0)));if(void 0!==t)return this.compareVersion(i[t])}}isBrowser(e,t=!1){const r=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=Utils.getBrowserTypeByAlias(i);return t&&s&&(i=s.toLowerCase()),i===r}compareVersion(e){let t=[0],r=e,i=!1;const s=this.getBrowserVersion();if("string"==typeof s)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(i=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(i=!0,r=e.substr(1)),t.indexOf(Utils.compareVersions(s,r,i))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some((e=>this.is(e)))}}
20
2
  /*!
21
3
  * Bowser - a browser detector
22
4
  * https://github.com/lancedikson/bowser
23
5
  * MIT License | (c) Dustin Diaz 2012-2015
24
6
  * MIT License | (c) Denis Demchenko 2015-2019
25
- */class Bowser{static getParser(e,t=!1){if("string"!=typeof e)throw new Error("UserAgent should be a string");return new Parser(e,t)}static parse(e){return new Parser(e).getResult()}static get BROWSER_MAP(){return BROWSER_MAP}static get ENGINE_MAP(){return ENGINE_MAP}static get OS_MAP(){return OS_MAP}static get PLATFORMS_MAP(){return PLATFORMS_MAP}}var bowser=Object.freeze({__proto__:null,default:Bowser}),require$$2=getAugmentedNamespace(bowser),specialChar="~",safeSpecialChar="\\x"+("0"+specialChar.charCodeAt(0).toString(16)).slice(-2),escapedSafeSpecialChar="\\"+safeSpecialChar,specialCharRG=new RegExp(safeSpecialChar,"g"),safeSpecialCharRG=new RegExp(escapedSafeSpecialChar,"g"),safeStartWithSpecialCharRG=new RegExp("(?:^|([^\\\\]))"+escapedSafeSpecialChar),indexOf$1=[].indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},$String=String;function generateReplacer(e,t,r){var i,n,s=!1,o=!!t,a=[],c=[e],u=[e],d=[r?specialChar:"[Circular]"],l=e,h=1;return o&&(n="object"==typeof t?function(e,r){return""!==e&&t.indexOf(e)<0?void 0:r}:t),function(e,t){return o&&(t=n.call(this,e,t)),s?(l!==this&&(i=h-indexOf$1.call(c,this)-1,h-=i,c.splice(h,c.length),a.splice(h-1,a.length),l=this),"object"==typeof t&&t?(indexOf$1.call(c,t)<0&&c.push(l=t),h=c.length,(i=indexOf$1.call(u,t))<0?(i=u.push(t)-1,r?(a.push((""+e).replace(specialCharRG,safeSpecialChar)),d[i]=specialChar+a.join(specialChar)):d[i]=d[0]):t=d[i]):"string"==typeof t&&r&&(t=t.replace(safeSpecialChar,escapedSafeSpecialChar).replace(specialChar,safeSpecialChar))):s=!0,t}}function retrieveFromPath(e,t){for(var r=0,i=t.length;r<i;e=e[t[r++].replace(safeSpecialCharRG,specialChar)]);return e}function generateReviver(e){return function(t,r){var i="string"==typeof r;return i&&r.charAt(0)===specialChar?new $String(r.slice(1)):(""===t&&(r=regenerate(r,r,{})),i&&(r=r.replace(safeStartWithSpecialCharRG,"$1"+specialChar).replace(escapedSafeSpecialChar,safeSpecialChar)),e?e.call(this,t,r):r)}}function regenerateArray(e,t,r){for(var i=0,n=t.length;i<n;i++)t[i]=regenerate(e,t[i],r);return t}function regenerateObject(e,t,r){for(var i in t)t.hasOwnProperty(i)&&(t[i]=regenerate(e,t[i],r));return t}function regenerate(e,t,r){return t instanceof Array?regenerateArray(e,t,r):t instanceof $String?t.length?r.hasOwnProperty(t)?r[t]:r[t]=retrieveFromPath(e,t.split(specialChar)):e:t instanceof Object?regenerateObject(e,t,r):t}var CircularJSON={stringify:function(e,t,r,i){return CircularJSON.parser.stringify(e,generateReplacer(e,t,!i),r)},parse:function(e,t){return CircularJSON.parser.parse(e,generateReviver(t))},parser:JSON},circularJson_node=CircularJSON;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex<t;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,t=queue.length}currentQueue=null,draining=!1,runClearTimeout(e)}}function nextTick(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];queue.push(new Item(e,t)),1!==queue.length||draining||runTimeout(drainQueue)}function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)};var title="browser",platform="browser",browser=!0,env={},argv=[],version$1="",versions={},release={},config$1={};function noop$1(){}var on=noop$1,addListener=noop$1,once=noop$1,off=noop$1,removeListener=noop$1,removeAllListeners=noop$1,emit=noop$1;function binding(e){throw new Error("process.binding is not supported")}function cwd(){return"/"}function chdir(e){throw new Error("process.chdir is not supported")}function umask(){return 0}var performance$1=global$1.performance||{},performanceNow=performance$1.now||performance$1.mozNow||performance$1.msNow||performance$1.oNow||performance$1.webkitNow||function(){return(new Date).getTime()};function hrtime(e){var t=.001*performanceNow.call(performance$1),r=Math.floor(t),i=Math.floor(t%1*1e9);return e&&(r-=e[0],(i-=e[1])<0&&(r--,i+=1e9)),[r,i]}var startTime=new Date;function uptime(){return(new Date-startTime)/1e3}var process={nextTick:nextTick,title:title,browser:browser,env:env,argv:argv,version:version$1,versions:versions,on:on,addListener:addListener,once:once,off:off,removeListener:removeListener,removeAllListeners:removeAllListeners,emit:emit,binding:binding,cwd:cwd,chdir:chdir,umask:umask,hrtime:hrtime,platform:platform,release:release,config:config$1,uptime:uptime},md5={exports:{}};(function(module){(function(){var ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self,NODE_JS=!root.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;NODE_JS?root=commonjsGlobal:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&module.exports,ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}!root.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!ARRAY_BUFFER||!root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var createOutputMethod=function(e){return function(t){return new Md5(!0).update(t)[e]()}},createMethod=function(){var e=createOutputMethod("hex");NODE_JS&&(e=nodeWrap(e)),e.create=function(){return new Md5},e.update=function(t){return e.create().update(t)};for(var t=0;t<OUTPUT_TYPES.length;++t){var r=OUTPUT_TYPES[t];e[r]=createOutputMethod(r)}return e},nodeWrap=function(method){var crypto=eval("require('crypto')"),Buffer=eval("require('buffer').Buffer"),nodeMethod=function(e){if("string"==typeof e)return crypto.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw ERROR;return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),Array.isArray(e)||ArrayBuffer.isView(e)||e.constructor===Buffer?crypto.createHash("md5").update(new Buffer(e)).digest("hex"):method(e)};return nodeMethod};function Md5(e){if(e)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Md5.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if("string"!==r){if("object"!==r)throw ERROR;if(null===e)throw ERROR;if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||ARRAY_BUFFER&&ArrayBuffer.isView(e)))throw ERROR;t=!0}for(var i,n,s=0,o=e.length,a=this.blocks,c=this.buffer8;s<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),t)if(ARRAY_BUFFER)for(n=this.start;s<o&&n<64;++s)c[n++]=e[s];else for(n=this.start;s<o&&n<64;++s)a[n>>2]|=e[s]<<SHIFT[3&n++];else if(ARRAY_BUFFER)for(n=this.start;s<o&&n<64;++s)(i=e.charCodeAt(s))<128?c[n++]=i:i<2048?(c[n++]=192|i>>6,c[n++]=128|63&i):i<55296||i>=57344?(c[n++]=224|i>>12,c[n++]=128|i>>6&63,c[n++]=128|63&i):(i=65536+((1023&i)<<10|1023&e.charCodeAt(++s)),c[n++]=240|i>>18,c[n++]=128|i>>12&63,c[n++]=128|i>>6&63,c[n++]=128|63&i);else for(n=this.start;s<o&&n<64;++s)(i=e.charCodeAt(s))<128?a[n>>2]|=i<<SHIFT[3&n++]:i<2048?(a[n>>2]|=(192|i>>6)<<SHIFT[3&n++],a[n>>2]|=(128|63&i)<<SHIFT[3&n++]):i<55296||i>=57344?(a[n>>2]|=(224|i>>12)<<SHIFT[3&n++],a[n>>2]|=(128|i>>6&63)<<SHIFT[3&n++],a[n>>2]|=(128|63&i)<<SHIFT[3&n++]):(i=65536+((1023&i)<<10|1023&e.charCodeAt(++s)),a[n>>2]|=(240|i>>18)<<SHIFT[3&n++],a[n>>2]|=(128|i>>12&63)<<SHIFT[3&n++],a[n>>2]|=(128|i>>6&63)<<SHIFT[3&n++],a[n>>2]|=(128|63&i)<<SHIFT[3&n++]);this.lastByteIndex=n,this.bytes+=n-this.start,n>=64?(this.start=n-64,this.hash(),this.hashed=!0):this.start=n}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>2]|=EXTRA[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var e,t,r,i,n,s,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879<<0)^(r=((r=(-271733879^(i=((i=(-1732584194^2004318071&e)+o[1]-117830708)<<12|i>>>20)+e<<0)&(-271733879^e))+o[2]-1126478375)<<17|r>>>15)+i<<0)&(i^e))+o[3]-1316259209)<<22|t>>>10)+r<<0:(e=this.h0,t=this.h1,r=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(r^i))+o[0]-680876936)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+o[1]-389564586)<<12|i>>>20)+e<<0)&(e^t))+o[2]+606105819)<<17|r>>>15)+i<<0)&(i^e))+o[3]-1044525330)<<22|t>>>10)+r<<0),t=((t+=((e=((e+=(i^t&(r^i))+o[4]-176418897)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+o[5]+1200080426)<<12|i>>>20)+e<<0)&(e^t))+o[6]-1473231341)<<17|r>>>15)+i<<0)&(i^e))+o[7]-45705983)<<22|t>>>10)+r<<0,t=((t+=((e=((e+=(i^t&(r^i))+o[8]+1770035416)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+o[9]-1958414417)<<12|i>>>20)+e<<0)&(e^t))+o[10]-42063)<<17|r>>>15)+i<<0)&(i^e))+o[11]-1990404162)<<22|t>>>10)+r<<0,t=((t+=((e=((e+=(i^t&(r^i))+o[12]+1804603682)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+o[13]-40341101)<<12|i>>>20)+e<<0)&(e^t))+o[14]-1502002290)<<17|r>>>15)+i<<0)&(i^e))+o[15]+1236535329)<<22|t>>>10)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+o[1]-165796510)<<5|e>>>27)+t<<0)^t))+o[6]-1069501632)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+o[11]+643717713)<<14|r>>>18)+i<<0)^i))+o[0]-373897302)<<20|t>>>12)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+o[5]-701558691)<<5|e>>>27)+t<<0)^t))+o[10]+38016083)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+o[15]-660478335)<<14|r>>>18)+i<<0)^i))+o[4]-405537848)<<20|t>>>12)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+o[9]+568446438)<<5|e>>>27)+t<<0)^t))+o[14]-1019803690)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+o[3]-187363961)<<14|r>>>18)+i<<0)^i))+o[8]+1163531501)<<20|t>>>12)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+o[13]-1444681467)<<5|e>>>27)+t<<0)^t))+o[2]-51403784)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+o[7]+1735328473)<<14|r>>>18)+i<<0)^i))+o[12]-1926607734)<<20|t>>>12)+r<<0,t=((t+=((s=(i=((i+=((n=t^r)^(e=((e+=(n^i)+o[5]-378558)<<4|e>>>28)+t<<0))+o[8]-2022574463)<<11|i>>>21)+e<<0)^e)^(r=((r+=(s^t)+o[11]+1839030562)<<16|r>>>16)+i<<0))+o[14]-35309556)<<23|t>>>9)+r<<0,t=((t+=((s=(i=((i+=((n=t^r)^(e=((e+=(n^i)+o[1]-1530992060)<<4|e>>>28)+t<<0))+o[4]+1272893353)<<11|i>>>21)+e<<0)^e)^(r=((r+=(s^t)+o[7]-155497632)<<16|r>>>16)+i<<0))+o[10]-1094730640)<<23|t>>>9)+r<<0,t=((t+=((s=(i=((i+=((n=t^r)^(e=((e+=(n^i)+o[13]+681279174)<<4|e>>>28)+t<<0))+o[0]-358537222)<<11|i>>>21)+e<<0)^e)^(r=((r+=(s^t)+o[3]-722521979)<<16|r>>>16)+i<<0))+o[6]+76029189)<<23|t>>>9)+r<<0,t=((t+=((s=(i=((i+=((n=t^r)^(e=((e+=(n^i)+o[9]-640364487)<<4|e>>>28)+t<<0))+o[12]-421815835)<<11|i>>>21)+e<<0)^e)^(r=((r+=(s^t)+o[15]+530742520)<<16|r>>>16)+i<<0))+o[2]-995338651)<<23|t>>>9)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+o[0]-198630844)<<6|e>>>26)+t<<0)|~r))+o[7]+1126891415)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+o[14]-1416354905)<<15|r>>>17)+i<<0)|~e))+o[5]-57434055)<<21|t>>>11)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+o[12]+1700485571)<<6|e>>>26)+t<<0)|~r))+o[3]-1894986606)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+o[10]-1051523)<<15|r>>>17)+i<<0)|~e))+o[1]-2054922799)<<21|t>>>11)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+o[8]+1873313359)<<6|e>>>26)+t<<0)|~r))+o[15]-30611744)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+o[6]-1560198380)<<15|r>>>17)+i<<0)|~e))+o[13]+1309151649)<<21|t>>>11)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+o[4]-145523070)<<6|e>>>26)+t<<0)|~r))+o[11]-1120210379)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+o[2]+718787259)<<15|r>>>17)+i<<0)|~e))+o[9]-343485551)<<21|t>>>11)+r<<0,this.first?(this.h0=e+1732584193<<0,this.h1=t-271733879<<0,this.h2=r-1732584194<<0,this.h3=i+271733878<<0,this.first=!1):(this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+i<<0)},Md5.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,i=this.h3;return HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[15&r]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]+HEX_CHARS[i>>4&15]+HEX_CHARS[15&i]+HEX_CHARS[i>>12&15]+HEX_CHARS[i>>8&15]+HEX_CHARS[i>>20&15]+HEX_CHARS[i>>16&15]+HEX_CHARS[i>>28&15]+HEX_CHARS[i>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,i=this.h3;return[255&e,e>>8&255,e>>16&255,e>>24&255,255&t,t>>8&255,t>>16&255,t>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var e,t,r,i="",n=this.array(),s=0;s<15;)e=n[s++],t=n[s++],r=n[s++],i+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[63&(e<<4|t>>>4)]+BASE64_ENCODE_CHAR[63&(t<<2|r>>>6)]+BASE64_ENCODE_CHAR[63&r];return e=n[s],i+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[e<<4&63]+"=="};var exports=createMethod();COMMON_JS?module.exports=exports:root.md5=exports})()})(md5),function(e){var t,r=Object.create,i=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,o=Object.getOwnPropertySymbols,a=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,u=Object.prototype.propertyIsEnumerable,d=Reflect.get,l=(e,t,r)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,h=(e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})},p=(e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of s(t))!c.call(e,a)&&a!==r&&i(e,a,{get:()=>t[a],enumerable:!(o=n(t,a))||o.enumerable});return e},m=(e,t,n)=>(n=null!=e?r(a(e)):{},p(!t&&e&&e.__esModule?n:i(n,"default",{value:e,enumerable:!0}),e)),f=(e,t,r)=>new Promise(((i,n)=>{var s=e=>{try{a(r.next(e))}catch(e){n(e)}},o=e=>{try{a(r.throw(e))}catch(e){n(e)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(s,o);a((r=r.apply(e,t)).next())})),g={};h(g,{BloudStream:()=>Ke,Room:()=>vt,getUserMedia:()=>yt}),e.exports=(t=g,p(i({},"__esModule",{value:!0}),t));var v="reconnected",y="connected",_="close",b="error",S="timeout",I="reconnecting",E="binary",T="notify",R="request",w=require$$0__default.default,A="boom-bloud ",k=typeof console!==w.constant.RAW_UNDEFINED?console:w.constant.NULL,C=/bjy/.test((0,w.toString)(w.constant.EMPTY_FUNCTION))?2:3,M=w.constant.WINDOW&&/edge|msie|trident/i.test(w.constant.WINDOW.navigator.userAgent)?w.constant.EMPTY_STRING:"%c",O=k?M?function(e,t,r,i){i?k.log(M+e,r,t,i):k.log(M+e,r,t)}:function(e,t,r){r?k.log(e,t,r):k.log(e,t)}:w.constant.EMPTY_FUNCTION;function P(){if(w.constant.GLOBAL){let e=w.constant.GLOBAL.BJY_LOG_LEVEL;if(e>=0&&e<=5)return e}return C}function L(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}var x=require$$0__default.default,D=class e{constructor(e={}){this.TRACE=0,this.DEBUG=1,this.INFO=2,this.WARN=3,this.ERROR=4,this.FATAL=5,this.options=x.object.extend({uploadLevel:3},e),this.canUpload=!0}static Log(){return this.instance||(this.instance=new e),this.instance}enableUploadLog(){this.canUpload=!0}disableUploadLog(){this.canUpload=!1}setUploadLevel(e){this.options.uploadLevel=e}fatal(e,t,r=!1){(5>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&this.options.onUpload(e,5,t),function(e,t){if(P()<=5)throw new Error(`[${t||A} fatal]: ${e}`)}(e,t)}error(e,t,r=!1){(function(e,t){P()<=4&&O(`${t||A} error`,e,L("#ed4014"))})(e,t),(4>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&this.options.onUpload(e,4,t)}warn(e,t,r=!1){(function(e,t){P()<=3&&O(`${t||A} warn`,e,L("#f90"))})(e,t),(3>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&this.options.onUpload(e,3,t)}info(e,t,r=!1){(function(e,t){P()<=2&&O(`${t||A} info`,e,L("#2db7f5"))})(e,t),(2>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&this.options.onUpload(e,2,t)}call(e,t,r=!1){(function(e,t,r){P()<=2&&O(`${t||A} info`,e,L("#66cdaa"),r)})(e,t),(2>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&this.options.onUpload(e,2,t)}debug(e,t,r=!1,i=!1){(function(e,t){P()<=1&&O(`${t||A} debug`,e,L("#999"))})(e,t),!i&&(1>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&this.options.onUpload(e,1,t)}trace(e,t,r=!1){(function(e,t){P()<=0&&O(`${t||A} trace`,e,L("#999"))})(e,t),0>=this.options.uploadLevel&&r&&this.canUpload&&this.options.onUpload&&this.options.onUpload(e,0,t)}log(e,t,r,i=!1){switch(t){case 0:this.trace(e,r,i);break;case 1:default:this.debug(e,r,i);break;case 2:this.info(e,r,i);break;case 3:this.warn(e,r,i);break;case 4:this.error(e,r,i);break;case 5:this.fatal(e,r,i)}}},N=require$$0__default.default,{extend:$}=N.object,{func:U,string:B}=N.is,V="RpcBuilder",F={maxRetry:0,requestTimeout:5e3,responseTimeout:5e3,duplicatesTimeout:5e3};function j(...e){let t="";for(let r=0;r<e.length;r++)e[r]&&(t+=e[r]);return t}var W=class extends N.Emitter{constructor(e,t,r={},i){super(!1),this.packer=e,this.options=$({},F,r),this.requestID=0,this.notifyId=0,this.reqMap=new Map,this.resMap=new Map,this.reqKeyMap=new Map,this.logger=i||new D,this.onmessageHandler=e=>{this.onmessage(e)},t&&this.handlTransport(t)}handlTransport(e){this.transport&&(U(this.transport.removeListener)?this.transport.removeListener(this.onmessageHandler):U(this.transport.removeEventListener)?this.transport.removeEventListener(this.onmessageHandler):U(this.transport.onmessage)&&(this.transport.onmessage=null)),e&&(U(e.addListener)?e.addListener("onmessage",this.onmessageHandler):U(e.addEventListener)?e.addEventListener("onmessage",this.onmessageHandler):e.onmessage=this.onmessageHandler,this.transport=e)}send(e){U(this.transport.send)?this.transport.send(e):U(this.transport.write)?this.transport.write(e):U(this.transport.postMessage)&&this.transport.postMessage(e)}request(e){return f(this,arguments,(function*(e,t={},r={}){if(!this.transport)throw new Error(`request ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);return new Promise(((i,n)=>{var s,o;if(r.key&&this.reqKeyMap.has(r.key)){let i=this.reqKeyMap.get(r.key);clearTimeout(i.timer),this.logger.warn(`request ${e}, params: ${JSON.stringify(t)} canceled because there is call new request whoes key is same as before`),i.reject(new Error("request canceled because there is call new request which key is same as before")),this.reqMap.delete(j(i.id)),this.reqKeyMap.delete(r.key)}let a=this.requestID++;r.dest&&(t.dest=r.dest),this.options.peerId&&(t.from=this.options.peerId);let c={resolve:i,reject:n,id:a,dest:r.dest,timer:null,retryCount:0,maxRetry:null!=(s=r.maxRetry)?s:this.options.maxRetry,errorRetry:null!=(o=r.errorRetry)&&o,method:e,params:t,message:this.packer.pack({method:e,params:t},a),timestamp:(0,N.getTimestamp)(),key:r.key,timeout:r.timeout,timeoutFn:()=>{if(c.retryCount>=c.maxRetry){if(this.reqMap.delete(j(c.id)),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key),this.logger.error(`request ${e}, params: ${JSON.stringify(t)} timeout`),this.sessionId!==t.sessionId)return void this.logger.warn(`sessionId is not same, ignore this time out fn: ${this.sessionId}`);n(new Error("request timeout"))}else c.retryCount++,c.timer=setTimeout(c.timeoutFn,r.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${e}, params: ${JSON.stringify(t)}, count: ${c.retryCount}`),this.send(c.message)},needRetry:r.needRetry};c.timer=setTimeout(c.timeoutFn,r.timeout||this.options.requestTimeout*(c.retryCount+1)),this.reqMap.set(j(c.id),c),c.key&&this.reqKeyMap.set(c.key,c),this.send(c.message)}))}))}reply(e,t,r){var i;this.options.peerId&&(t&&(t.from=this.options.peerId),r&&(r.from=this.options.peerId));let n=this.packer.pack({result:t,error:r},e.id),s={id:e.id,message:n,timer:null},o=j(e.id,null==(i=e.params)?void 0:i.from);this.options.responseTimeout&&(s.timer=setTimeout((()=>{this.resMap.delete(o)}),this.options.responseTimeout),this.resMap.set(o,s)),this.send(s.message)}notify(e,t={},r){if(!this.transport)throw new Error(`notify ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);let i=this.notifyId++;r&&(t.dest=r),this.options.peerId&&(t.from=this.options.peerId),this.send(this.packer.pack({method:e,params:t,seq:i}))}onmessage(e){var t;if(this.transport)if((0,N.isDef)(e))if(B(e)){let r;try{r=this.packer.unpack(e)}catch(t){return void this.logger.error(`unpack message error, message: ${e}, error: ${(0,N.getErrorMessage)(t)}`,V)}let i=r.id,n=r.method,s=null!=(t=r.params)?t:{},o=s.dest;if(s.dest,(0,N.isDef)(this.options.peerId)&&this.options.peerId===o)return void this.logger.warn(`ignored the message which send from me, message: ${e}`);if((0,N.isDef)(i))if(n){let t=this.resMap.get(j(i,o));t?(this.logger.warn(`request: ${e} has replyed in ${this.options.responseTimeout}ms, send same again`),this.send(t.message)):this.fire(R,[r])}else{let t=r.error,o=r.result;if((null==t?void 0:t.dest)!==this.options.peerId||(null==o?void 0:o.dest)!==this.options.peerId)return void this.logger.warn(`ignored the message which not sent for me, message: ${e}`);let a=j(i),c=this.reqMap.get(a);if(c){if(clearTimeout(c.timer),t){if(this.logger.error(`[request error] request: ${c.message}, response: ${e}, consume: ${(0,N.getTimestamp)()-c.timestamp}`),c.errorRetry&&c.retryCount<c.maxRetry&&(!c.needRetry||c.needRetry(t)))return c.retryCount++,c.timer=setTimeout(c.timeoutFn,c.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${c.method}, params: ${JSON.stringify(c.params)}, count: ${c.retryCount}`),c.id=this.requestID++,c.message=this.packer.pack({method:n,params:s},c.id),void this.send(c.message);c.reject(t)}else this.logger.debug(`[request success] method: ${c.method}, id: ${c.id}, consume: ${(0,N.getTimestamp)()-c.timestamp}`),c.resolve(o);this.reqMap.delete(a),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key)}else this.logger.warn(`no request for the response: ${e}`)}else this.fire(T,[n,s,r.seq])}else this.fire(E,[e]);else this.logger.warn("message is not defined",V)}destroy(){this.off(),this.handlTransport(),this.reqMap&&(this.reqMap.forEach((e=>{clearTimeout(e.timer),e.reject("transport closed")})),this.reqMap.clear(),this.reqMap=null),this.reqKeyMap&&(this.reqKeyMap.clear(),this.reqKeyMap=null),this.resMap&&(this.resMap.forEach((e=>{clearTimeout(e.timer)})),this.resMap.clear(),this.resMap=null),this.packer=null,this.transport=null}getPacker(){return this.packer}getTransport(){return this.transport}setTransport(e){this.handlTransport(e)}resetRequest(){this.reqMap&&this.reqMap.forEach((e=>{clearTimeout(e.timer),e.timer=setTimeout(e.timeoutFn,e.timeout||this.options.requestTimeout*(e.retryCount+1)),this.send(e.message)}))}},q=require$$0__default.default,G="open",H="close",z="error",J="send",Y="message",K="timeout",Q="reconnecting",X=class extends q.Emitter{constructor(e){var t;super(!0),q.object.extend(this,e),this.status=0,this.queue=[],this.isReconnect=!1,e.retryCount&&e.retryCount>0&&(this.retryIndex=0),this.logger=D.Log(),this.logLevel=null!=(t=this.logLevel)?t:this.logger.TRACE,this.connectCount=0}isOpen(){return 1===this.status}isConnecting(){return 6===this.status}getStatus(){return this.status}connect(e,t){let r=this;if(this.server=e,this.proxys=t,this.connectCount=0,1===r.status||6===r.status||4===r.status)return;let i=[e];t&&t.length&&(i=i.concat(t));let n=-1,s=function(){r.nextStartTimer=null,6===r.status?function(e,t){r.connectCount++;let i=r.nativeOptions;r.native===WebSocket&&(i=r.nativeOptions.protocols),r.logger.debug(`${r.tag||"Transport"} connecting url: ${e.url}`);let n,s=(0,q.getTimestamp)(),o=new r.native(e.url,i),a=function(r){n&&clearTimeout(n),o.onopen=o.onerror=null,t(o,e,r)};o.onopen=function(e){var t;r.consume=null!=(t=null==e?void 0:e.consume)?t:(0,q.getTimestamp)()-s,a(1)},o.onerror=function(){a(2)},r.timeout>0&&(n=setTimeout((function(){n=null,o.onerror=null,o.onopen=null,q.is.func(o.close)&&o.close(),a(5)}),r.timeout))}(i[++n],(function(e,s,a){if(6===r.status)if(1===a){if(r.url=s.url,r.socket=e,r.status=1,e.onmessage=function(e){1===r.status&&(r.logger.log(`${r.tag||"Transport"} Received: ${q.is.string(e.data)?e.data:"binary"}`,r.logLevel),r.onReceive&&q.is.string(e.data)&&r.onReceive(JSON.parse(e.data)),r.onmessage&&r.onmessage(e.data),r.fire(Y,[e.data]))},e.onclose=function(i){if(r.logger.error("bloud socket closed"),q.Logger.error("bloud socket closed"),1===r.status)if(r.connectOnClose&&r.retryCount>0){if(r.status=0,r.onReconnecting&&(r.onReconnecting(),4===r.status||3===r.status))return;r.fire(Q),r.isReconnect=!0,r.logger.warn(`${r.tag||"Transport"} reconnecting`),q.Logger.warn(`${r.tag||"Transport"} reconnecting`),e.clear&&e.clear(),r.connect(s,t)}else r.onClose&&r.onClose(i),r.fire(H,[i])},r.retryCount>0&&(r.retryIndex=0),r.onOpen&&(r.logger.debug(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} success`),q.Logger.info(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} success`),r.onOpen({server:s,reconnect:r.isReconnect})),r.fire(G,[{server:s,reconnect:r.isReconnect}]),r.queue.length)for(;r.queue.length;){let t=r.queue.shift(),i=q.is.string(t)||q.is.arrayBuffer(t)?t:JSON.stringify(t);e.send(i),r.logger.log(`${r.tag||"Transport"} Sent: ${q.is.arrayBuffer(t)?"binary":i}`,r.logLevel),r.onSend&&r.onSend(i),r.fire(J,[i])}}else if(n===i.length-1){if(r.retryCount>0&&r.retryIndex++<r.retryCount-1)return n=-1,void o();switch(r.status=a){case 2:r.logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} error`),q.Logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} error`),r.onError&&r.onError({server:s}),r.fire(z,[{server:s}]);break;case 5:r.logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} timeout`),q.Logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} timeout`),r.onTimeout&&r.onTimeout({server:s}),r.fire(K,[{server:s}])}}else o();else if(4===r.status){let t=!1;if(1===a&&r.refreshQueueOnClose&&r.queue.length){for(;r.queue.length;){let t=r.queue.shift(),i=q.is.string(t)||q.is.arrayBuffer(t)?t:JSON.stringify(t);e.send(i),r.logger.log(`${r.tag||"Transport"} Sent: ${q.is.arrayBuffer(t)?"binary":i}`,r.logLevel),r.onSend&&r.onSend(i),r.fire(J,[i])}t=!0}t?setTimeout((()=>{e.close(),r.status=3}),1e3):(e.close(),r.status=3)}})):4===r.status&&(r.status=3)},o=function(){r.interval>0?r.nextStartTimer=setTimeout(s,r.interval):s()};r.status=6,s()}send(e){if(1!==this.status&&4!==this.status)return this.queueMax>0&&this.queue.length===this.queueMax&&this.queue.shift(),void this.queue.push(e);let t=this.socket;if(t){let r=q.is.string(e)||q.is.arrayBuffer(e)?e:JSON.stringify(e);t.send(r),this.logger.log(`${this.tag||"Transport"} Sent: ${q.is.arrayBuffer(e)?"binary":r}`,this.logLevel),this.onSend&&this.onSend(r),this.fire(J,[r])}}close(){let e=this.socket;if(this.socket=null,this.status=4,e){let t=!1;if(this.refreshQueueOnClose&&this.queue.length){for(;this.queue.length;)this.send(this.queue.shift());t=!0}e.onmessage=e.onclose=null,t?setTimeout((()=>{e.close(),this.status=3}),1e3):(e.close(),this.status=3)}this.nextStartTimer&&(clearTimeout(this.nextStartTimer),this.nextStartTimer=null)}reconnect(){6!==this.status&&(this.close(),4===this.status?setTimeout((()=>{this.status=3,this.connect(this.server,this.proxys)}),1e3):this.connect(this.server,this.proxys))}getSocket(){return this.socket}getConsume(){return Math.max(this.consume||0,0)}getConnectCount(){return this.connectCount}},Z=X,ee=require$$0__default.default,te=require$$0__default.default,{extend:re}=te.object,ie={heartbeat:15e3,requestTimeout:15e3,maxRetry:3,packer:class extends class{constructor(){}}{constructor(){super()}pack(e,t){let r={jsonrpc:"2.0"};if(e.method)r.method=e.method,e.params&&(r.params=e.params),(0,ee.isDef)(t)&&(r.id=t),e.seq&&(r.seq=e.seq);else if((0,ee.isDef)(t)){if(e.error){if(e.result)throw new TypeError("Both result and error are defined");r.error=e.error}else{if(!e.result)throw new TypeError("No result or error is defined");r.result=e.result}r.id=t}return JSON.stringify(r)}unpack(e){let t=JSON.parse(e);if("2.0"!==t.jsonrpc)throw new TypeError(`Invalid JsonRPC version ${t.jsonrpc}: ${e}`);if(!(0,ee.isDef)(t.method)){if(!(0,ee.isDef)(t.id))throw new TypeError(`Invalid message: ${e}`);let r=(0,ee.isDef)(t.error),i=(0,ee.isDef)(t.result);if(i&&r)throw new TypeError(`Both result and error are defined: ${e}`);if(!i&&!r)throw new TypeError(`No result or error is defined: ${e}`)}return t}},retryInterval:500,connectTimeout:1e4,connectOnClose:!0,requestMaxRetry:0},ne=class extends te.Emitter{constructor(e,t,r,i){var n,s;super(!0),this.server=e,this.proxys=r,this.options=re({},ie,t),this.logger=D.Log(),this.heartbeatTimer=new class{constructor(e,t,r){this.task=e,this.timeout=t,this.interval=r}start(){let e=this;e.stop();let t=e.timeout,r=e.interval,i=function(){!1!==e.task()&&e.timer?e.timer=setTimeout(i,e.interval):e.stop()};null==t&&(t=r),e.timer=setTimeout(i,t)}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null)}updateInterval(e){this.interval=e}isStarted(){return!!this.timer}destroy(){this.stop(),this.task=this.timeout=this.interval=null}}((()=>{this.heartbeat()}),this.options.heartbeat,this.options.heartbeat),this.packer=new this.options.packer,this.transport=new Z({native:null!=(n=this.options.transport)?n:WebSocket,onSend:e=>{this.fire("onsend",[e])},onReceive:e=>{this.fire("onreceive",[e])},onOpen:e=>{this.fire(e.reconnect?v:y),this.heartbeatTimer&&this.heartbeatTimer.start()},onClose:()=>{this.fire(_),this.heartbeatTimer&&this.heartbeatTimer.stop()},onError:()=>{this.fire(b),this.heartbeatTimer&&this.heartbeatTimer.stop()},onTimeout:()=>{this.fire(S),this.heartbeatTimer&&this.heartbeatTimer.stop()},onReconnecting:()=>{this.fire(I),this.heartbeatTimer&&this.heartbeatTimer.stop()},connectOnClose:this.options.connectOnClose,retryCount:this.options.maxRetry,nativeOptions:null!=(s=this.options.transportOptions)?s:{},tag:this.options.tag,interval:this.options.retryInterval,timeout:this.options.connectTimeout,logLevel:this.options.logLevel}),this.rpc=new W(this.packer,this.transport,{requestTimeout:this.options.requestTimeout,responseTimeout:this.options.requestTimeout,peerId:this.options.peerId,maxRetry:this.options.requestMaxRetry},this.logger),this.rpc.on(E,(e=>{this.fire(E,[e])})),this.rpc.on(T,((e,t,r)=>{this.fire(T,[e,t,r])})),this.rpc.on(R,(e=>{this.fire(R,[e])})),(0,te.nextTick)((()=>{this.transport&&this.transport.connect(this.server,this.proxys)}))}setRPCSessionId(e){this.rpc.sessionId=e}request(e){return f(this,arguments,(function*(e,t={},r){return this.rpc.request(e,t,r)}))}reply(e,t,r){return this.rpc.reply(e,t,r)}notify(e,t={}){return this.rpc.notify(e,t)}sendBinary(e){let t=this.transport.getSocket();t&&t.send(e)}getConsume(){return this.transport?this.transport.getConsume():0}getTransportConnectCount(){return this.transport?this.transport.getConnectCount():0}getTransportStatus(){return this.transport?this.transport.getStatus():0}destroy(){this.off(),this.rpc&&this.rpc.destroy(),this.transport&&this.transport.close(),this.transport=null,this.rpc=null,this.packer=null,this.heartbeatTimer&&this.heartbeatTimer.destroy(),this.heartbeatTimer=null}resetRequest(){this.rpc&&this.rpc.resetRequest()}},se=require$$0__default.default,oe=class e extends ne{constructor(e,t,r,i){super({url:e},t,void 0,i),this.notified=-1,this.seq=0,this.sessionId=null,this.syncRoomLock=!1,this.retryQueue=[],this.proxy=r}resetTimeout(){this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout((()=>{this.resetTimer=void 0,this.fire(S),this.destroy()}),4*this.options.heartbeat)}syncNotify(){return f(this,null,(function*(){}))}request(t,r,i){return f(this,null,(function*(){let n=this.seq++;return this.syncRoomLock&&"syncRoom"!==t?(this.logger.warn(`session closed, waiting for sync room, method: ${t}, params: ${JSON.stringify(r)}`),new Promise(((e,i)=>{this.retryQueue.push({method:t,params:r,resolve:e,reject:i,id:n})}))):(!this.syncRoomLock&&"syncRoom"===t&&(this.syncRoomLock=!0),r&&"syncRoom"!==t&&!r.sessinId&&(r.sessionId=this.sessionId),r&&"syncRoom"===t&&(r.sid=this.sessionId),((e,t,r)=>d(a(e),r,t))(e.prototype,this,"request").call(this,t,r,i).then((e=>(this.resetTimeout(),(!this.sessionId&&e.sessionId||this.sessionId!==e.sessionId)&&e.sessionId&&(this.sessionId=e.sessionId,this.setRPCSessionId(this.sessionId)),"syncRoom"===t&&(this.syncRoomLock=!1,this.retryQueue.length&&(this.retryQueue=this.retryQueue.filter((e=>"recover"!==e.method)),this.retryQueue.sort(((e,t)=>e.id-t.id)),se.array.each(this.retryQueue,(e=>{e.params.sessionId=this.sessionId,this.logger.info(`retry the retryQueue request, ${e.method}, params: ${JSON.stringify(e.params)}`),this.request(e.method,e.params).then((t=>{e.resolve(t)})).catch((t=>{e.reject(t)}))})),this.retryQueue=[])),e))).catch((e=>{var i;if("request timeout"!==(0,se.getErrorMessage)(e)&&this.resetTimeout(),99===(null==e?void 0:e.code))return this.sessionId&&this.sessionId!==r.sessionId?(this.logger.warn(`the request session has closed but the seesion is update after sync room, retry request again, ${t}, params: ${JSON.stringify(r)}`),r.sessionId=this.sessionId,this.request(t,r)):(this.syncRoomLock||(this.sessionId=null,this.syncRoomLock=!0,this.fire(se.BloudEvents.SESSION_CLOED)),this.logger.warn(`the session has closed, push the request into retry queue, ${t}, params: ${JSON.stringify(r)}`),se.Logger.warn("session closed, close socket to retry reconnect ws, and sync room"),null==(i=this.transport.socket)||i.close(),new Promise(((e,i)=>{this.retryQueue.push({method:t,params:r,resolve:e,reject:i,id:n})})));throw e})))}))}heartbeat(){this.request("ping",{sessionId:this.sessionId}).then((e=>{this.resetTimeout()})).catch((e=>{this.logger.error(`channel heartbeat error: ${JSON.stringify(e)}`)}))}destroy(){this.seq=null,this.notified=null,this.sessionId=null,this.retryQueue=null,this.syncRoomLock=null,this.resetTimer&&(clearTimeout(this.resetTimer),this.resetTimer=null),super.destroy()}getProxy(){return this.proxy}},ae=require$$0__default.default,ce={enableRace:!0,forceWS:!1,forceDC:!1,forceWT:!1},ue=class extends ae.Emitter{constructor(e,t,r={},i){super(!1),this.options=ae.object.extend({},ce,t),this.closed=!1,this.icefull=!1,this.isConnecting=!1,this.connectCount=0,this.isLeaving=!1,this.rpc=r,this.proxies=e,this.logger=i||new D}getUrl(e){return e.activeUrl=e.url||e.dcurl||e.wturl,this.options.token&&(e.activeUrl+=`?token=${this.options.token}`),e.activeUrl}raceConnect(){return f(this,null,(function*(){let e=this.proxies;if(this.options.forceWS){let t=e.filter((e=>!!e.url));t.length&&(e=t)}this.connectingTimers={};let t=`.connecting${Math.random()}`;return new Promise(((r,i)=>{let n=!1;this.connectCount=0;let s=(e,s)=>{n?e.destroy():this.closed?(ae.object.each(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.warn("signal open after call close function, reject"),i("signal has already closed")):(n=!0,ae.object.each(this.connectingTimers,((e,t)=>{clearTimeout(e.timer),e.channel&&t!=s&&e.channel.destroy()})),this.connectingTimers={},e.off(t),this.connectCount=e.getTransportConnectCount(),r(e))},o=0,a=()=>{++o===e.length&&(ae.object.each(this.connectingTimers,(e=>{e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.error("connect all proxies failed"),i("connect all proxies failed"))},c=(e,r)=>{let i=new oe(e,{maxRetry:5,transport:void 0,transportOptions:{},tag:"Client",logLevel:1},r,this.logger);i.one(y+t,(()=>{r.consume=i.getConsume(),this.connectCount=i.getTransportConnectCount(),s(i,e)})).one(v+t,(()=>{r.consume=i.getConsume(),this.connectCount=i.getTransportConnectCount(),s(i,e)})).one(b+t,(()=>{this.connectCount=i.getTransportConnectCount(),a()})).one(S+t,(()=>{this.connectCount=i.getTransportConnectCount(),a()})),this.connectingTimers[e].channel=i};ae.array.each(e,(e=>{let t=e.delay?(0,ae.toNumber)(e.delay):0,r=this.getUrl(e);r&&(this.connectingTimers[r]={timer:setTimeout((()=>{c(r,e)}),t)})}))}))}))}queueConnect(){return f(this,null,(function*(){let e=this.proxies;if(this.options.forceWS){let t=e.filter((e=>!!e.url));t.length&&(e=t)}let t=`.connecting${Math.random()}`;return new Promise(((r,i)=>{let n=0;this.connectCount=0;let s=()=>{this.closed&&i("signal has closed");let o=e[n],a=this.getUrl(o);a||i("url can not be empty!");let c=this.connectingChannel=new oe(a,{maxRetry:3,transport:void 0,transportOptions:{},tag:"Client",logLevel:1},o,this.logger);c.one(y+t,(()=>{c.off(t),this.connectingChannel=void 0,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),r(c)})).one(v+t,(()=>{c.off(t),this.connectingChannel=void 0,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),r(c)})).one(b+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=void 0,this.logger.error(`queue connect proxy: ${n} ${a} error`),this.fire(ae.BloudEvents.STATE_NOTIFY,[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} error`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,i("connect all proxies failed")):setTimeout((()=>{s()}),1e3)})).one(S+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=void 0,this.logger.error(`queue connect proxy: ${n} ${a} timeout`),this.fire(ae.BloudEvents.STATE_NOTIFY,[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} timeout`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,i("connect all proxies failed")):setTimeout((()=>{s()}),1e3)}))};s()}))}))}connect(){return f(this,null,(function*(){if(!this.proxies.length)return new Error("not has any proxy to connect");this.isConnecting=!0,this.options.enableRace?this.channel=yield this.raceConnect():this.channel=yield this.queueConnect(),this.channel.on(b,(()=>{this.logger.error(`proxy connect error, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(b)})).on(_,(()=>{this.logger.error(`proxy connect close, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(_)})).on(S,(()=>{this.logger.error(`proxy connect timeout, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(S)})).on(y,(()=>{this.fire(y)})).on(I,(()=>{this.fire(I)})).on(v,(()=>{if(this.isLeaving)return;this.fire(v),this.channel.syncNotify();let e=this.channel.getProxy();e&&(e.consume=this.channel.getConsume())})).on(T,((e,t,r)=>{this.channel.notified=r,this.channel.resetTimeout(),ae.BloudEventMap[e]?this.fire(ae.BloudEventMap[e],[t]):this.fire(T,[{method:e,params:t}])})).on(R,(e=>f(this,null,(function*(){if(e.method&&this.rpc[e.method]){this.channel.resetTimeout();let{error:t,result:r}=yield this.rpc[e.method](e);this.channel.reply(e,r,t)}})))).on(ae.BloudEvents.SESSION_CLOED,(()=>{this.fire(ae.BloudEvents.SESSION_CLOED)})),this.isConnecting=!1,this.logger.info(`connect proxy success, proxy: ${JSON.stringify(this.channel.getProxy())}`)}))}request(e,t){return f(this,null,(function*(){return this.channel.request(e,t)}))}join(e){return f(this,null,(function*(){return this.channel.request("joinRoom",e).then((e=>(this.channel.resetTimeout(),this.isLeaving=!1,e)))}))}leave(e){return f(this,null,(function*(){return this.isLeaving=!0,this.channel.request("leaveRoom",e,{timeout:3e3}).then((e=>(this.isLeaving=!1,e)))}))}syncRoom(e,t,r){return f(this,null,(function*(){return this.channel.request("syncRoom",{roomId:e,userId:t,info:r})}))}updateCustomStats(e,t,r,i){return f(this,null,(function*(){return this.channel.request("updateCustomStats",{roomId:e,userId:t,options:r.customStats,replace:i})}))}updateStream(e,t,r){return f(this,null,(function*(){return this.channel.request("updateStream",((e,t)=>{for(var r in t||(t={}))c.call(t,r)&&l(e,r,t[r]);if(o)for(var r of o(t))u.call(t,r)&&l(e,r,t[r]);return e})({userId:e,streamId:t},r))}))}releaseRoom(e,t){return f(this,null,(function*(){return this.channel.request("releaseRoom",{roomId:e,userId:t})}))}updateRoom(e,t,r){return f(this,null,(function*(){return this.channel.request("updateRoom",{roomId:e,userId:t,options:r})}))}updateUser(e,t,r){return f(this,null,(function*(){return this.channel.request("updateUser",{roomId:e,userId:t,info:r})}))}evictUser(e,t,r,i){return f(this,null,(function*(){return this.channel.request("evictUser",{roomId:e,userId:t,evictId:r,withoutBlack:i})}))}changeMaster(e,t,r,i){return f(this,null,(function*(){return this.channel.request("changeMaster",{roomId:e,userId:t,master:r,isKeep:i})}))}leaveRoom(e,t,r){return f(this,null,(function*(){return this.channel.request("leaveRoom",{roomId:e,userId:t,desc:r})}))}getUsers(e,t,r,i,n,s){return f(this,null,(function*(){return this.channel.request("getUsers",{roomId:e,userId:t,pagesize:r,index:i,permission:n,waitRoom:s})}))}getUsersList(e,t,r,i){return f(this,null,(function*(){return this.channel.request("getUserList",{pagesize:t,index:e,permission:r,waitRoom:i})}))}queryUsers(e){return f(this,null,(function*(){return this.channel.request("queryUsers",{userIds:e})}))}publishStream(e,t,r,i){return f(this,null,(function*(){return this.channel.request("publishStream",{roomId:e,userId:t,streamId:r,options:i})}))}controlStream(e,t,r,i){return f(this,null,(function*(){return this.channel.request("controlStream",{roomId:e,userId:t,streamId:r,options:i})}))}resetStream(e,t,r,i){return f(this,null,(function*(){return this.channel.request("resetStream",{roomId:e,userId:t,streamId:r,options:i})}))}unpublishStream(e,t,r){return f(this,null,(function*(){return this.channel.request("unpublishStream",{roomId:e,userId:t,streamId:r})}))}getMessages(e,t,r){return f(this,null,(function*(){return this.channel.request("getMessages",{roomId:e,userId:t})}))}sendMessage(e,t,r,i){return f(this,null,(function*(){return this.channel.request("sendMessage",{roomId:e,userId:t,to:r,msg:i})}))}customMessage(e,t,r,i){return f(this,null,(function*(){return this.channel.request("customMessage",{roomId:e,userId:t,to:r,msg:i})}))}startRecord(e,t,r){return f(this,null,(function*(){return this.channel.request("startRecord",{roomId:e,streamId:t,options:r})}))}stopRecord(e,t){return f(this,null,(function*(){return this.channel.request("stopRecord",{roomId:e,streamId:t})}))}searchUsers(e,t,r){return f(this,null,(function*(){return this.channel.request("searchUsers",{nickname:e,pageSize:t,waitRoom:r})}))}syncUser(e){return f(this,null,(function*(){return this.channel.request("syncUser",{pageSize:e})}))}moveUserRoom(e,t,r){return f(this,null,(function*(){return this.channel.request("moveUserRoom",{target:e,toWait:t,autoJoin:r})}))}close(){this.connectingChannel&&this.connectingChannel.destroy(),ae.object.keys(this.connectingTimers).length&&(ae.object.each(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={}),this.channel&&this.channel.destroy(),this.closed=!0,this.off()}getSessionId(){var e;return null==(e=this.channel)?void 0:e.sessionId}getProxy(){var e;return null==(e=this.channel)?void 0:e.getProxy()}getConnectCount(){return this.connectCount}getConnectedProxyConsume(){var e;return null==(e=this.channel)?void 0:e.getConsume()}},de=require$$0__default.default,le=()=>{let e=he(),t="none";return null!==e.match("fake")?t="fake":null!==e.match("ios")?t="ios":null!==e.match("android")?t="android":null!==e.match("Firefox")?t="mozilla":null!==e.match("Chrome")?(t="chrome-stable",null!==e.match("Electron")&&(t="electron")):(null!==e.match("Safari")||null!==e.match("AppleWebKit"))&&(t="safari"),t},he=()=>window.navigator.userAgent,pe=class e{constructor(t){this.permission=t||e.default}getRead(){return this.permission.indexOf("R")>=0}getWrite(){return this.permission.indexOf("W")>=0}getPublish(){return this.permission.indexOf("P")>=0}getSubscribe(){return this.permission.indexOf("S")>=0}getManage(){return this.permission.indexOf("M")>=0}getAudio(){return this.permission.indexOf("A")>=0}getVideo(){return this.permission.indexOf("V")>=0}getOwn(){return this.permission.indexOf("O")>=0}setManage(e){this._update("M",e)}setSubscribe(e){this._update("S",e)}setPublish(e){this._update("P",e)}setWrite(e){this._update("W",e)}setRead(e){this._update("R",e)}setAudio(e){this._update("A",e)}setVideo(e){this._update("V",e)}setOwn(e){this._update("O",e)}set(e){this.permission=e}get(){return this.permission}_update(e,t){t?this.permission.indexOf(e)<0&&(this.permission+=e):this.permission=this.permission.replace(e,"")}};pe.default="RWPSAV";var me=pe,fe=require$$1,ge=class{constructor(e,t,r){this.streams=new Map,this.local=e,this.userId=t,this.params=r;let i=r.permission;!i&&r.info&&(i=r.info.permission),i||(i=me.default),this.permission=new me(i)}setID(e){this.userId=e}getID(){return this.userId}getPermission(){return this.permission}getUserInfo(){var e,t;return null!=(t=null!=(e=this.params.userinfo)?e:this.params.info.userinfo)?t:{}}update(e){e.permission&&this.permission.set(e.permission),this.params=(0,fe.defaults)(e,this.params)}getNickName(){var e,t;return null!=(t=null!=(e=this.params.nickname)?e:this.params.info.nickname)?t:""}getStreams(){return this.streams}getStream(e){return this.streams.get(e)}addStream(e){this.streams.set(e.getID(),e)}removeStream(e){this.streams.delete(e)}},ve=m(require$$2),ye={userAgent:()=>{let t;try{t=require("react-native").Platform}catch(e){}let r="none";return e.exports?t?"ios"===t.OS?r="ios":"android"===t.OS&&(r="android"):r="fake":r=window.navigator.userAgent,r},isMobile:()=>{let t;try{t=require("react-native").Platform}catch(e){}let r=!1;return e.exports&&t&&("ios"===t.OS||"android"===t.OS)&&(r=!0),r},isElectron:()=>!1},_e=ye,be=m(require$$2),Se={};h(Se,{CHROME:()=>Ie,ELECTRON:()=>ke,FIREFOX:()=>Te,INTERNET_EXPLORER:()=>Re,NWJS:()=>Ae,OPERA:()=>Ee,REACT_NATIVE:()=>Ce,SAFARI:()=>we,UNKNOWN:()=>Me,WECHAT:()=>Oe});var Ie="chrome",Ee="opera",Te="firefox",Re="iexplorer",we="safari",Ae="nwjs",ke="electron",Ce="react-native",Me="unknown",Oe="wechat",Pe={Chrome:Ie,Chromium:Ie,Opera:Ee,Firefox:Te,"Internet Explorer":Re,Safari:we,WeChat:Oe},Le=navigator.userAgent;function xe(){let e=Le;if(e.match(/Electron/)){let t=e.match(/Electron\/([\d.]+)/)[1];return{name:ke,version:t}}}function De(){let e=Le;if(e.match(/JitsiMeetNW/)){let t=e.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Ae,version:t}}}function Ne(){let e=Le;if(e.match(/MicroMessenger/)){let t=e.match(/MicroMessenger\/([\d.]+)/)[1];return{name:Oe,version:t}}}function $e(){let e,t=Le.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);if(t||"ReactNative"===navigator.product)return t&&t.length>2&&(e=t[2]),e||(e="unknown"),{name:Ce,version:e}}function Ue(e){let t,r=[$e,xe,De,Ne];for(let e=0;e<r.length;e++)if(t=r[e](),t)return t;let i=e.getBrowserName();return i in Pe?{name:Pe[i],version:e.getBrowserVersion()}:(t=function(){let e=Le,t={name:Me,version:void 0};if(e.match(/Chrome/)&&!e.match(/Edge/))if(e.match(/Edg/)){let r=e.match(/Edg\/([\d.]+)/)[1];Number.parseInt(r,10)>72&&(t.name=Ie,t.version=r)}else t.name=Ie,t.version=e.match(/Chrome\/([\d.]+)/)[1];return t}(),t||{name:Me,version:void 0})}navigator.userAgent||(Le=navigator.product);var Be=class{constructor(e){let t,r;if(this.browsers=Se,this._bowser=be.default.getParser(Le),void 0===e){let e=Ue(this._bowser);t=e.name,r=e.version}else e.name in Pe?(t=Pe[e.name],r=e.version):(t=Me,r=void 0);this._name=t,this._version=r}getName(){return this._name}isChrome(){return this._name===Ie}isOpera(){return this._name===Ee}isFirefox(){return this._name===Te}isIExplorer(){return this._name===Re}isSafari(){return this._name===we}isNWJS(){return this._name===Ae}isElectron(){return this._name===ke}isReactNative(){return this._name===Ce}getVersion(){return this._version}_checkCondition(e){if(this._version)return this._bowser.satisfies(e)}isVersionGreaterThan(e){return this._checkCondition({[this._name]:`>${e}`})}isVersionLessThan(e){return this._checkCondition({[this._name]:`<${e}`})}isVersionEqualTo(e){return this._checkCondition({[this._name]:`~${e}`})}},Ve={mediaDevices:()=>{let e;try{e=require("react-native-webrtc").mediaDevices}catch(t){e=navigator.mediaDevices}return e},PRTCPeerConnection:()=>{let e;try{e=require("react-native-webrtc").RTCPeerConnection}catch(t){e=RTCPeerConnection}return e}},Fe=Ve,je=D.Log(),We=()=>{let e="none";return null!==_e.userAgent().match("fake")?e="fake":null!==_e.userAgent().match("ios")?e="ios":null!==_e.userAgent().match("android")?e="android":null!==_e.userAgent().match("Firefox")?e="mozilla":null!==_e.userAgent().match("Chrome")?(e="chrome-stable",null!==_e.userAgent().match("Electron")&&(e="electron")):(null!==_e.userAgent().match("Safari")||null!==_e.userAgent().match("AppleWebKit"))&&(e="safari"),e};var qe,Ge={GetUserMedia:e=>new Promise(((t,r)=>{((e,t=(()=>{}),r=(()=>{}))=>{let i,n=Fe.mediaDevices(),s=(e,t,r)=>{n.getUserMedia(e).then(t).catch(r)};e.screen?(()=>{switch(je.debug("Screen access requested"),We()){case"electron":je.debug("Screen sharing in Electron"),i={},i.video=e.video||{},i.video.mandatory=e.video.mandatory||{},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=e.desktopStreamId,s(i,t,r);break;case"mozilla":case"mozilla":je.debug("Screen sharing in Firefox"),i={},void 0!==e.video?(i.video=e.video,i.video.mediaSource||(i.video.mediaSource="window")):i={audio:e.audio,video:{mediaSource:"window"}},s(i,t,r);break;case"chrome-stable":je.debug("Screen sharing in Chrome"),i={},e.desktopStreamId&&(i.video=e.video||{mandatory:{}},i.video.mandatory=i.video.mandatory||{},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=e.desktopStreamId,s(i,t,r));break;case"chrome-stable":if(je.debug("Screen sharing in Chrome"),i={},e.desktopStreamId)i.video=e.video||{mandatory:{}},i.video.mandatory=i.video.mandatory||{},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=e.desktopStreamId,s(i,t,r);else{let n="jbglfdfehfdcpnbhfnciaiokkfocjcjk";e.extensionId&&(je.debug(`extensionId supplied, using ${e.extensionId}`),n=e.extensionId),je.debug("Screen access on chrome stable, looking for extension");try{chrome.runtime.sendMessage(n,{getStream:!0},(n=>{if(void 0===n)return je.error("Access to screen denied"),void r({code:"Access to screen denied"});let o=n.streamId;void 0!==e.video.mandatory?(i.video=e.video||{mandatory:{}},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=o):i={video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:o}}},s(i,t,r)}))}catch(e){je.debug("Screensharing plugin is not accessible "),r({code:"no_plugin_present"})}}break;default:je.error("This browser does not support ScreenSharing")}})():(je.debug("Calling getUserMedia with config",e),s(e,t,r))})(e,(r=>{(new Be).isReactNative()&&t(r),e.fps&&r.clone?t(function(e,t){if(!t)return e;let r=e.getVideoTracks()[0];if(!r||"function"!=typeof r.getCapabilities)return e;let i=r.getConstraints(),n=e.clone();return r=n.getVideoTracks()[0],r?(e.getTracks().forEach((e=>e.stop())),i.width,i.height,i.frameRate=t||i.frameRate,r.applyConstraints(i),n):(n.getTracks().forEach((e=>e.stop())),e)}(r,e.fps)):t(r)}),(e=>{r(e)}))})),getBrowser:We,getUserAgent:()=>window.navigator.userAgent},He=Ge,ze={ERR_NOT_INSTALLED:1,ERR_NOT_FOUND:10,ERR_TIMEOUT:11,ERR_STATS:12,ERR_NO_SERVICE:13,ERR_AUTH:14,ERR_INVALID_REQUEST:15,ERR_METHOD:16,ERR_NOT_STARTUP:17,ERR_CUSTOM_AUTH_FAILED:18,ERR_USER_LIMIT:19,ERR_QDTLS:20,ERR_OVEVLOAD:21,ERR_EVICTED:22,ERR_PERMISSION:23,ERR_SENSITIVE_WORD:24,ERR_NOT_AT_ROOM:25,ERR_MEDIA_PIPELINE:26,ERR_NO_STREAM:27,ERR_LOCKED:28,ERR_UNKNOWN:33},Je=class{static create(){if(qe)return qe;let e;e=_e.isMobile()?_e.userAgent():navigator.userAgent;let t,r=e,i=ve.default.getParser(r),n=i.getEngine();try{t=n.name.toLowerCase()}catch(e){}return(new Be).isElectron()?(console.log("===========Client============="),qe=new class{constructor(){this._stream=null}start(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=this._toConstraints(t),i="boolean"==typeof t.audio&&t.audio;"boolean"==typeof t.isRecord&&t.isRecord,"boolean"==typeof t.isLocalProjection&&t.isLocalProjection;try{e=window.require("electron")}catch(t){e=window.parent.require("electron")}let n,s={types:["window","screen"]};if(e)n=e.desktopCapturer?e.desktopCapturer.getSources(s):e.ipcRenderer.invoke("desktopCapturer:getSources",s);else{let e;e=window.electronAPI?window.electronAPI.desktopCapturerGetSources(s):window.parent.electronAPI.desktopCapturerGetSources(s),n=e}let o=e=>{e.id.startsWith("window");let t=!!i&&{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id,echoCancellation:!0}};return navigator.mediaDevices.getUserMedia({audio:t,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id,minWidth:r.video.mandatory.minWidth,maxWidth:r.video.mandatory.maxWidth,minHeight:r.video.mandatory.minHeight,maxHeight:r.video.mandatory.maxHeight,minFrameRate:r.video.mandatory.minFrameRate,maxFrameRate:r.video.mandatory.maxFrameRate}}}).then((t=>(console.log("ElectronScreenShare:",e.id),this._stream=t,t)))};return n.then((e=>f(this,null,(function*(){console.log("---share name selected:"+t.source_name,t.chromeMediaSourceId);let r=e.find((e=>e.id===t.chromeMediaSourceId));if(r)return o(r);for(let r of e)if(t.source_name===r.name){try{return o(r)}catch(e){console.log("ElectronScreenShare.start.error:",e)}break}if(t.chromeMediaSourceId){let e={id:t.chromeMediaSourceId};return o(e)}return null})))).catch((e=>(console.error("ElectronScreenShare:error",e),Promise.reject(e))))}stop(){this._stream instanceof MediaStream&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){let t={video:{frameRate:e.fps,mandatory:{maxWidth:e.width,minWidth:e.width,maxHeight:e.height,minHeight:e.height}},audio:!1};return D.Log().log("====fps:",e.fps),isFinite(e.width)&&(t.video.mandatory.maxWidth=e.width,t.video.mandatory.minWidth=e.width),isFinite(e.height)&&(t.video.mandatory.minHeight=e.height,t.video.mandatory.maxHeight=e.height),isFinite(e.fps)&&(t.video.mandatory.minFrameRate=e.fps,t.video.mandatory.maxFrameRate=e.fps),void 0===e.width&&(t.video.mandatory.maxWidth=1920,t.video.mandatory.minWidth=1920),void 0===e.height&&(t.video.mandatory.maxHeight=1080,t.video.mandatory.minHeight=1080),void 0===e.fps&&(t.video.mandatory.minFrameRate=15,t.video.mandatory.maxFrameRate=15),t}},qe):(console.log("===========Browser============="),i.satisfies({chrome:">=72",chromium:">=72"})?qe=new class{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this._toConstraints(e);return navigator.mediaDevices.getDisplayMedia(t).then((e=>(this._stream=e,Promise.resolve(this._stream))))}stop(){this._stream instanceof MediaStream&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){return{video:{frameRate:e.fps},audio:e.audio||!1}}}:i.satisfies({chrome:">=55",chromium:">=55"})&&(qe=new class{constructor(){this._stream=null,this.avaliable=!0}check(){return new Promise(((e,t)=>{chrome.runtime.sendMessage({check:!0},(r=>{""!=r.id&&null!=r.id?e(r.id):t("not plugin")}))}))}detect(e){return new Promise(((t,r)=>{var i=document.createElement("img");i.src="chrome-extension://"+e+"/icon.png",i.onload=function(){t()},i.onerror=function(){r({code:ze.ERR_NOT_INSTALLED,error:"not-installed"})}}))}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this,r=e.extensionId||"jbglfdfehfdcpnbhfnciaiokkfocjcjk";return this.detect(r).then((()=>new Promise(((i,n)=>{chrome.runtime.sendMessage(r,{getStream:!0},(r=>{if(void 0===r)return D.Log().error("Access to screen denied"),void error({code:"Access to screen denied"});let s=t._toConstraints(e,r.streamId);He.GetUserMedia(s).then((e=>{t._stream=e,i(t._stream)})).catch((e=>{n(e)}))}))})))).catch((e=>{D.Log().warn("onerror plugin"),reject(e)}))}stop(){this._stream instanceof MediaStream&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return this.avaliable}needExtension(){return!this.avaliable}_toConstraints(e,t){let r={video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t},optional:[{googTemporalLayeredScreencast:!0}]},audio:!1};return isFinite(e.width)&&(r.video.mandatory.maxWidth=e.width,r.video.mandatory.minWidth=e.width),isFinite(e.height)&&(r.video.mandatory.maxHeight=e.height,r.video.mandatory.minHeight=e.height),isFinite(e.frameRate)&&(r.video.mandatory.maxFrameRate=e.frameRate,r.video.mandatory.minFrameRate=e.frameRate),r}}),qe)}},Ye=Je.create();D.Log();var Ke=class{constructor(e,t,r,i,n){this.published=!1,this.audio=n.audio,this.video=n.video,this.audio_enable=n.audio_enable,this.video_enable=n.video_enable,this.screen=n.screen,this.client=e,this.room=t,this.participant=r,this.local=i,this.options=n,this.id=n.id,this.customInfo=n.customInfo,this.roomId=t.getID(),this.userId=r.getID()}audioEnabled(){return this.audio_enable}videoEnabled(){return this.video_enable}setAudioEnabled(e){return this.client.controlStream(this.roomId,this.userId,this.id,{audio_enable:e}).then((()=>{this.audio_enable=e}))}setVideoEnabled(e){return this.client.controlStream(this.roomId,this.userId,this.id,{video_enable:e}).then((()=>{this.video_enable=e}))}isLocal(){return this.local}getID(){return this.id}getParticipant(){return this.participant}publish(e){return f(this,null,(function*(){var t,r;this.audio_enable=null!=(t=e.audio_enable)?t:this.audio_enable,this.video_enable=null!=(r=e.video_enable)?r:this.video_enable,yield this.client.publishStream(this.roomId,this.userId,this.id,{audio_enable:this.audio_enable,video_enable:this.video_enable,video:this.video,audio:this.audio}),this.participant.addStream(this),this.published=!0}))}unpublish(){return f(this,null,(function*(){yield this.client.unpublishStream(this.roomId,this.userId,this.id),this.participant.removeStream(this.getID()),this.published=!1}))}static sharing(){return Ye}},Qe=m(circularJson_node),Xe=m(md5.exports),Ze=require$$5__default.default,et=127,tt=1e-10,rt=`.speakerDetector${Math.random()}`;function it(e,t,r){let i=t.length,n=Math.floor(e.length/i),s=!1;for(let o=0,a=0;o<i;o++){let i=0;for(let t=a+n;a<t;a++)e[a]>r&&i++;t[o]!=i&&(t[o]=i,s=!0)}return s}function nt(e,t,r,i){let n=Math.log(function(e,t){let r=e-t;t<r&&(t=r);let i=1;for(let r=e,n=1;r>t;r--,n++)i=Math.floor(i*r/n);return i}(t,e))+e*Math.log(r)+(t-e)*Math.log(1-r)-Math.log(i)+i*e;return n<tt&&(n=tt),n}var st=class extends Ze.EventEmitter{constructor(){super(),this.decisionMaker=void 0,this.dominant=void 0,this.lastDecisionTime=0,this.lastLevelChangedTime=0,this.lastLevelIdleTime=0,this.relativeSpeechActivities=[0,0,0],this.speakers=new Map}addStream(e){e&&e.stream?e.stream.on("audio-level"+rt,this.levelChanged.bind(this,e)):console.warn("add stream error")}removeStream(e){e&&e.stream&&e.stream.off(rt),this.speakers.delete(e.getID())}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new class{constructor(e){this.algorithm=e}run(){let e=this.algorithm.runInDecisionMaker(this);e<0?this.algorithm.decisionMakerExited(this):setTimeout((()=>{this.run()}),e)}}(this),this.decisionMaker.run())}decisionMakerExited(e){e==this.decisionMaker&&(this.decisionMaker=void 0)}getDominantSpeaker(){let e=this.speakers.get(this.dominant);if(e)return e.getStream()}getOrCreateSpeaker(e){let t=e.getID(),r=this.speakers.get(t);return r||(r=new class{constructor(e){this.stream=e,this.immediates=new Array(25),this.immediateSpeechActivityScore=tt,this.lastLevelChangedTime=(new Date).getTime(),this.levels=new Array(this.immediates.length),this.longs=new Array(1),this.longSpeechActivityScore=tt,this.mediums=new Array(5),this.mediumSpeechActivityScore=tt,this.minLevel=0,this.nextMinLevel=0,this.nextMinLevelWindowLength=void 0,this.lastActiveTime=this.lastLevelChangedTime-2e3-1}getStream(){return this.stream}getID(){return this.stream.getID()}computeImmediates(){let e=this.immediates,t=this.levels,r=Math.floor(this.minLevel+9.4),i=!1;for(let n=0;n<e.length;++n){let s=t[n];s<r&&(s=0);let o=Math.floor(s/9.4);e[n]!=o&&(e[n]=o,i=!0)}return i}computeLongs(){return it(this.mediums,this.longs,2)}computeMediums(){return it(this.immediates,this.mediums,3)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=nt(this.immediates[0],15,.5,.78)}evaluateLongSpeechActivityScore(){this.longSpeechActivityScore=nt(this.longs[0],5,.5,47)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=nt(this.mediums[0],5,.5,24)}evaluateSpeechActivityScores(){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore()))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){let e=this.levels,t=new Array(e.length);for(let r=e.length-1,i=0;i<t.length;--r,++i)t[i]=e[r];return t}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;default:return this.longSpeechActivityScore}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){let r;this.lastLevelChangedTime=t,r=e<0?0:e>et?et:e;for(let e=this.levels.length-1;e>0;--e)this.levels[e]=this.levels[e-1];this.levels[0]=r,this.updateMinLevel(r)}e>10&&(this.lastActiveTime=(new Date).getTime())}levelTimeout(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!=e){if(0==this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0==this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=75){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>et&&(e=et),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}getSilent(){return(new Date).getTime()-this.lastActiveTime>2e3}}(e),this.speakers.set(t,r),this.maybeStartDecisionMaker()),r}levelChanged(e,t){t=Math.min(t*et*2,et);let r=this.getOrCreateSpeaker(e),i=(new Date).getTime();this.lastLevelChangedTime<i&&(this.lastLevelChangedTime=i,this.maybeStartDecisionMaker()),r.levelChanged(t,i)}decisionChoice(){let e=this.speakers.get(this.dominant),t="";e||(e=this.speakers.entries().next().value[1],t=e.getID()),e.evaluateSpeechActivityScores();let r=this.relativeSpeechActivities,i=1;for(let[n,s]of this.speakers){if(s==e)continue;s.evaluateSpeechActivityScores();for(let t=0;t<r.length;++t)r[t]=Math.log(s.getSpeechActivityScore(t)/e.getSpeechActivityScore(t));let o=r[0],a=r[1],c=r[2];o>2&&a>1&&c>0&&a>i&&(i=a,t=n)}return t}makeDecision(){let e;if(0!=this.speakers.size&&(e=this.decisionChoice()),e&&e!=this.dominant){this.dominant=e;let t=this.speakers.get(this.dominant);t&&!t.getSilent()?this.emit("speaker",t.getStream()):(this.emit("speaker"),this.dominant=void 0)}else if(this.dominant){let e=this.speakers.get(this.dominant);(e&&e.getSilent()||!e)&&(this.dominant=void 0,this.emit("speaker"))}}runInDecisionMaker(e){if(e&&e!=this.decisionMaker||0<this.lastDecisionTime&&this.lastDecisionTime-this.lastLevelChangedTime>=15e3)return-1;let t=(new Date).getTime(),r=400-(t-this.lastLevelIdleTime),i=0;r<=0?(0!=this.lastLevelIdleTime&&this.timeoutIdleLevels(t),this.lastLevelIdleTime=t):i=r;let n=400-(t-this.lastDecisionTime);return n<=0&&(this.lastDecisionTime=t,this.makeDecision(),n=400-((new Date).getTime()-t)),n>0&&i>n&&(i=n),i}timeoutIdleLevels(e){for(let[t,r]of this.speakers){let i=e-r.getLastLevelChangedTime();36e5<i&&(!this.dominant||r.getID()!=this.dominant)?this.speakers.delete(t):400<i&&r.levelTimeout()}}},ot=st,at=require$$5__default.default,ct=require$$5__default.default,ut=class extends ct.EventEmitter{constructor(){super(),this._recording=!1}start(e,t){}stop(){}exportRecordedData(){}setMuted(e){}setMicDevice(e){}_getAudioStream(){return navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}isRecording(){return this._recording}},dt=m(circularJson_node),lt=Je.create(),ht=class extends ut{constructor(){super(),this._trackSources=new Map,this._stream=null,this._recordedData=[]}start(e,t){return this._createDesktopStream(t.capture).then((r=>f(this,null,(function*(){try{return this._getMixedAudioTrack(e).then((e=>{e&&(r.addTrack(e),this._stream=r,this._mediaRecorder=this._newMediaRecorder(r,t.record),this._mediaRecorder.ondataavailable=e=>this._saveMediaData(e.data),this._mediaRecorder.start(1e3),this._recording=!0,this.emit("started"))}))}catch(e){throw D.Log().error(dt.default.stringify(e)),this._localAudioTrack&&this._localAudioTrack.stop(),r.getTracks().forEach((e=>e.stop())),e}}))))}stop(){return new Promise(((e,t)=>{this._mediaRecorder?(this._mediaRecorder.onstop=e,this._mediaRecorder.stop(),this._mediaRecorder=null,this._localAudioTrack&&(this._localAudioTrack.stop(),this._localAudioStream=null),this._stream&&this._stream.getTracks().forEach((e=>e.stop())),this._trackSources&&(this._trackSources.forEach((e=>e.disconnect(this._audioContextDest))),this._trackSources.clear()),this._recording=!1,this.emit("stopped")):t()}))}exportRecordedData(){return this._recordedData?Promise.resolve({data:this._recordedData,format:"mp4"}):Promise.reject("No video data recorded.")}setMuted(e){this._localAudioTrack&&(this._localAudioTrack.enabled=!e)}setMicDevice(e){return f(this,null,(function*(){if(this._localAudioTrack)try{return this.disconnectTrack(this._localAudioTrack),this._localAudioTrack.stop(),this._getLocalAudioTrack(e).then((e=>{this.connectTrack(e)}))}catch(e){return Promise.reject()}return Promise.reject()}))}_saveMediaData(e){console.log("save media data..., size:",e.size),this._recordedData.push(e)}_createDesktopStream(e){return lt.start(e).then((e=>{let t=e.getVideoTracks()[0];return t&&(t.onended=()=>{this.emit("track-ended")}),e}))}_newMediaRecorder(e,t){let r={bitsPerSecond:(t=t||{}).bitrate?t.bitrate:3e6};if(MediaRecorder.isTypeSupported(t.format))r.mimeType=t.format;else{let e=["video/mp4;codecs=h264","video/mp4;codecs=vp9","video/mp4;codecs=vp8"];for(let t of e)if(MediaRecorder.isTypeSupported(t)){r.mimeType=t;break}}return new MediaRecorder(e,r)}_getLocalAudioTrack(e){return this._getAudioStream().then((e=>{this._localAudioStream=e;let t=this._localAudioStream.getAudioTracks()[0];return this._localAudioTrack=t,t}))}_getMixedAudioTrack(e){return this._getLocalAudioTrack(e).then((()=>{if(this._localAudioStream){let e=new AudioContext,t=e.createMediaStreamSource(this._localAudioStream),r=e.createMediaStreamDestination();return t.connect(r),this._audioContext=e,this._audioContextDest=r,this._trackSources.set(this._localAudioTrack,t),r.stream.getAudioTracks()[0]}}))}connectTrack(e){let t=this._audioContext.createMediaStreamSource(new MediaStream([e]));null==t||t.connect(this._audioContextDest),this._trackSources.set(e,t)}disconnectTrack(e){let t=this._trackSources.get(e);t&&(t.disconnect(this._audioContextDest),this._trackSources.delete(e))}},pt=class extends at.EventEmitter{constructor(e){super(),this._opts=e,this._filename=e.filename,this._adapter=new ht,this._adapter.on("started",this.emit.bind(this,"started")),this._adapter.on("stopped",this.emit.bind(this,"stopped")),this._adapter.on("track-ended",this.emit.bind(this,"track-ended"))}downloadBlob(e,t="recording.webm"){let r=new Blob(e),i=window.URL.createObjectURL(r),n=document.createElement("a");n.style.display="none",n.href=i,n.download=t,document.body.appendChild(n),console.log("a tag to save recorded data..."),n.click(),setTimeout((function(){document.body.removeChild(n),window.URL.revokeObjectURL(i)}),1e3)}start(){return this._adapter.start("0",this._opts)}stop(){return this._adapter.stop().then((()=>(console.log("export recorded data..."),this._adapter.exportRecordedData()))).then((e=>{let{data:t,format:r}=e;console.log("download recorded data..."),this.downloadBlob(t,this._filename)}))}muteAudio(e){this._adapter.isRecording()&&this._adapter.setMuted(e)}addStream(e){let t=e&&e.getAudioTrack();t&&this._adapter.isRecording()&&this._adapter.connectTrack(t)}removeStream(e){let t=e.getAudioTrack();t&&this._adapter.isRecording()&&this._adapter.disconnectTrack(t)}addEventListener(e,t){this.addListener(e,t)}on(e,t){return this.addListener(e,t),this}},mt=pt,ft=require$$0__default.default,gt={enableRace:!1},vt=class extends ft.Emitter{constructor(e){var t;super(!0),this.switch=!1,this.audiooff=!1,this.selfopenaudio=!0,this.videooff=!1,this.msgoff=!1,this.creator="",this.master="",this.lock=!1,this.getUsersList=(e,t,r,i)=>this.client.getUsersList(e,t,r,i).then((e=>{let t=e.value;return{participants:this.parseGetUser(t),total:e.total,pageIndex:e.index}})),this.searchUsers=(e,t,r)=>this.client.searchUsers(e,t,r).then((e=>{let t=e.value;return{participants:this.parseGetUser(t)}})),this.queryUsers=e=>this.client.queryUsers(e).then((e=>{let t=e.value;return{participants:this.parseGetUser(t)}})),this.options=ft.object.extend({},gt,e),this.joined=!1,this.logger=D.Log(),this.roomId=e.room,this.userId=e.user,this.hasSecret=!!this.options.secret,this.connectopts={nickname:this.options.nickname,custom_token:this.options.custom_token,userinfo:this.options.userinfo},this.create=null==(t=e.create)||t,this.nickname=e.nickname,this.localParticipant=new ge(!0,this.userId,e)}connect(){return f(this,null,(function*(){this.client=new ue(this.options.proxies,{forceWS:this.options.forceWS,enableRace:this.options.enableRace,token:this.options.token},this.getRpc(),this.logger),this.handleEvents(),yield this.client.connect();try{let e=yield this.client.join({roomId:this.roomId,userId:this.userId,info:this.getJoinUserInfo(this.options.userinfo)});this.joined=!0,this.logger.info(`joined: sessionId: ${e.sessionId}, callId: ${e.raw.callId}`);let t=this.parseJoinResponse(e);this.fire(de.BloudEvents.ROOM_CONNECTED,[t])}catch(e){throw this.logger.error(`join room failed: ${(0,ft.getErrorMessage)(e)}, proxy: ${JSON.stringify(this.getActiveProxy())}`),this.client.close(),e}}))}leave(){return f(this,null,(function*(){var e;this.client&&(this.logger.info(`leaved: sessionId: ${(null==(e=this.client)?void 0:e.getSessionId())||""}`),yield this.client.leave({roomId:this.roomId,userId:this.userId,sessionId:this.client.getSessionId()||""}),this.client.close(),this.client=void 0,this.joined=!1)}))}request(e,t){return f(this,null,(function*(){var r;return null==(r=this.client)?void 0:r.request(e,t)}))}handleEvents(){this.client.on(b,(()=>{this.logger.error("client error"),this.fire(de.BloudEvents.ERROR)})).on(_,(()=>{this.logger.error("client close"),this.fire(de.BloudEvents.ERROR)})).on(S,(()=>{this.logger.error("client timeout"),this.fire(de.BloudEvents.TIMEOUT,[{msg:"timeout"}])})).on(v,(()=>{this.logger.info("client reconnected"),this.fire(de.BloudEvents.RECONNECTED)})).on(I,(()=>{this.fire(de.BloudEvents.RECONNECTING)})).on(ft.BloudEventMap.joinUser,(e=>{this.logger.debug("participant joined");let t=new ge(!1,e.userId,e);this.fire(ft.BloudEventMap.joinUser,[{participant:t,mode:e.mode,data:e}])})).on(ft.BloudEventMap.leaveUser,(e=>{e.userId!==this.userId&&this.fire(ft.BloudEventMap.leaveUser,[{userId:e.userId,mode:e.mode,data:e}])})).on(ft.BloudEventMap.leaveUsers,(e=>{this.fire(ft.BloudEventMap.leaveUsers,[e])})).on(ft.BloudEventMap.roomClosed,(e=>{this.logger.error("room closed"),this.fire(ft.BloudEventMap.roomClosed,[e]),this.destroy()})).on(ft.BloudEventMap.roomError,(()=>{this.logger.error("room error"),this.fire(ft.BloudEventMap.roomError),this.destroy()})).on(ft.BloudEventMap.publishStream,(e=>{if(e.userId===this.userId)return;let t=e.userId,r=e.streamId,i=r.endsWith("_screen"),n=e.customInfo;this.fire(ft.BloudEventMap.publishStream,[{userId:t,streamId:r,video:e.params.video_enable,audio:e.params.audio_enable,isScreen:i,customInfo:n}])})).on(ft.BloudEventMap.updateStream,(e=>{this.fire(ft.BloudEventMap.updateStream,[e])})).on(ft.BloudEventMap.streamUpdate,(e=>{if(e.userId===this.userId)return;let t=e.userId,r=e.streamId,i=r.endsWith("_screen");this.fire(ft.BloudEventMap.streamUpdate,[{userId:t,streamId:r,video:e.params.video_enable,audio:e.params.audio_enable,isScreen:i}])})).on(ft.BloudEventMap.unpublishStream,(e=>{if(e.userId===this.userId)return;let t=e.userId,r=e.streams[0],i=r.endsWith("_screen");this.fire(ft.BloudEventMap.unpublishStream,[{userId:t,streamId:r,isScreen:i}])})).on(ft.BloudEventMap.sendMessage,(e=>{let t={room:e.roomId,user:e.userId,message:e.msg,to:e.to,seq:e.seq};this.fire(ft.BloudEventMap.sendMessage,[t])})).on(ft.BloudEventMap.customMessage,(e=>{let t={room:e.roomId,user:e.userId,message:e.msg,to:e.to};this.fire(ft.BloudEventMap.customMessage,[t])})).on(ft.BloudEventMap.moveUserRoom,(e=>{var t,r;null!=(t=e.info)&&t.master&&(this.master=e.info.master),null!=(r=e.info)&&r.customStats&&(this.customStats=e.info.customStats),this.fire(ft.BloudEventMap.moveUserRoom,[e])})).on(ft.BloudEventMap.evicted,(e=>{this.fire(ft.BloudEventMap.evicted,[{userId:e.userId}])})).on(ft.BloudEventMap.updateStats,(e=>{this.switch=e.stats.switch,this.hasSecret=e.stats.secret,this.audiooff=e.stats.audiooff,this.selfopenaudio=e.stats.selfopenaudio,this.videooff=e.stats.videooff,this.msgoff=e.stats.msgoff,this.lock=e.stats.lock,this.creator=e.stats.creator,this.master=e.stats.master;let t=e.stats.updates,r=Object.keys(t);this.fire(ft.BloudEventMap.updateStats,[{room:this,options:r,stats:e.stats}])})).on(ft.BloudEventMap.updateCustomStats,(e=>{this.customStats=e.customStats||{},this.fire(ft.BloudEventMap.updateCustomStats,[{room:this,customStats:this.customStats,updateKeys:e.updateKeys}])})).on(ft.BloudEventMap.changeMaster,(e=>{this.master=e.master,this.fire(ft.BloudEventMap.changeMaster,[{master:this.master,oldMaster:e.oldmaster,isKeep:e.isKeep,type:e.type,data:e}])})).on(ft.BloudEventMap.updateUser,(e=>{if(e.user===this.getLocalParticipant().getID())this.getLocalParticipant().update(e.info),this.fire(ft.BloudEventMap.updateUser,[{participant:this.getLocalParticipant()}]);else{let t=new ge(!1,e.user,e.info);this.fire(ft.BloudEventMap.updateUser,[{participant:t}])}})).on(ft.BloudEventMap.userRejoined,(e=>{this.fire(ft.BloudEventMap.userRejoined,[{userId:e.userId,info:e.info}])}))}getRpc(){return{}}getActiveProxy(){return this.client.getProxy()}destroy(){this.client&&(this.client.close(),this.client=void 0),this.joined=!1,this.off()}getJoinUserInfo(e,t=!1){let r={};return r.ua=e.ua?e.ua:he(),r.device=e.device?e.device:le(),r.platform=e.platform?e.platform:"Web",r.network=e.network?e.network:"unknown",r.role=e.role?e.role:"anchor",r.create=this.options.create,r.secret=this.options.secret?(0,Xe.default)(`${this.roomId}.${this.options.secret}`):void 0,r.nickname=this.options.nickname,r.userinfo=this.options.userinfo,r.hasWaitRoom=!0,r.permission=t?this.permission:this.options.permission,r.custom_token=this.options.custom_token,r.prefer=this.options.prefer,r.name=this.options.name,r.userinfo.jointime||(r.userinfo.jointime=Math.floor(Date.now()/1e3)),r}getLocalParticipant(){return this.localParticipant}getID(){return this.roomId}getAudioOff(){return this.audiooff}getSelfOpenAudio(){return this.selfopenaudio}getVideoOff(){return this.videooff}getMsgOff(){return this.msgoff}getLock(){return this.lock}setAudioOff(e,t){return this.update({audiooff:e,selfopenaudio:t})}setVideoOff(e){return this.update({videooff:e})}setMsgOff(e){return this.update({msgoff:e})}setSwitch(e){return this.update({switch:e})}setLock(e){return this.update({lock:e})}getSwitch(){return this.switch}setSecret(e){return this.update({secret:e})}getLimits(){return this.limit}getMaster(){return this.master}getCreator(){return this.creator}getName(){return this.name}getMsgSeq(){return this.msgSeq}changeMaster(e,t){if(e!=this.getMaster())return this.client.changeMaster(this.roomId,this.userId,e,t).then((()=>{this.master=e})).catch((e=>{D.Log().error(Qe.default.stringify(e))}))}syncUser(e){return this.client.syncUser(e).then((e=>(D.Log().info("syncUser success"),e))).catch((e=>{D.Log().error("syncUser error",e)}))}evictUser(e){return this.client.evictUser(this.roomId,this.userId,e)}evictUser2(e,t,r){return e!=this.getMaster()?Promise.reject("not master."):this.client.evictUser(this.roomId,this.userId,t,r)}updateUser(e,t){return this.localParticipant.getID()==this.getMaster()||this.localParticipant.getPermission().getManage()||!t.permission&&e==this.localParticipant.getID()?this.client.updateUser(this.roomId,this.localParticipant.getID(),{info:t,target:e}).then((()=>{e==this.localParticipant.getID()&&this.localParticipant.update(t)})).catch((e=>{D.Log().error(e)})):Promise.reject({code:ze.ERR_PERMISSION,error:"permission denied."})}parseStreams(e,t){let r=[];if(t.streams)for(let i=0;i<t.streams.length;i++){let n=t.streams[i].params,s=t.streams[i].streamId,o={id:s,audio:n.audio,video:n.video,audio_enable:n.audio_enable,video_enable:n.video_enable,screen:s.endsWith("_screen"),customInfo:n.customInfo},a=new Ke(this.client,this,e,!1,o);r.push(a)}return r}parseJoinResponse(e){return this.logger.log(`room-connect耗时: ${e.duration}`),this.total=e.total,this.pagesize=e.pagesize,this.index=e.index,this.startup=e.startup,this.duration=e.duration,this.limit=e.limit,this.switch=e.switch,this.audiooff=e.audiooff,this.selfopenaudio=e.selfopenaudio,this.videooff=e.videooff,this.msgoff=e.msgoff,this.lock=e.lock,this.master=e.master,this.creator=e.creator,this.name=e.name,this.limit=e.limit,this.msgSeq=e.msgSeq,this.sessionId=e.sessionId,this.permission=e.permission,this.customStats=e.customStats,this.getLocalParticipant().getPermission().set(this.permission),{total:this.total,sessionId:this.sessionId,customStats:this.customStats,joinwait:e.joinwait,waitroom:e.waitroom,permission:e.permission,audiooff:e.audiooff}}syncRoom(){let e=this.getJoinUserInfo(this.options.userinfo,!0);return this.client.syncRoom(this.options.room,this.options.user,e).then((e=>{D.Log().log("bloud syncRoom response : "+Qe.default.stringify(e));let t=this.parseJoinResponse(e);this.fire(de.BloudEvents.ROOM_SYNCED,[t])})).catch((e=>{throw D.Log().error(e),this.fire(de.BloudEvents.SYNC_FAILED,[{error:e}]),e}))}update(e={}){return"string"==typeof e.secret&&(e.secret=(0,Xe.default)(`${this.roomId}.${e.secret}`)),this.client.updateRoom(this.roomId,this.userId,e).then((()=>{"boolean"==typeof e.audiooff&&(this.audiooff=e.audiooff),"boolean"==typeof e.videooff&&(this.videooff=e.videooff),"boolean"==typeof e.msgoff&&(this.msgoff=e.msgoff),"boolean"==typeof e.switch&&(this.switch=e.switch),"string"==typeof e.secret&&(this.secret=e.secret),"boolean"==typeof e.lock&&(this.lock=e.lock),"boolean"==typeof e.selfopenaudio&&(this.selfopenaudio=e.selfopenaudio),D.Log().info(e)})).catch((e=>{throw D.Log().error(e),e}))}updateCustomStats(e,t){return e=e||{},this.client.updateCustomStats(this.roomId,this.userId,e,t).then((()=>{D.Log().info("updateCustomStats:"+Qe.default.stringify(e))})).catch((e=>{throw D.Log().error(e),e}))}updateStream(e,t,r){return this.client.updateStream(e,t,{customInfo:r})}getMessages(e,t){return this.client.getMessages(this.roomId,this.userId,{startSeq:e,endSeq:t})}parseGetUser(e){let t=[];for(let r=0;r<e.length;r++){if(e[r].userId===this.getLocalParticipant().getID()){t.push(this.getLocalParticipant());continue}let i=new ge(!1,e[r].userId,e[r]);this.parseStreams(i,e[r]).forEach((e=>i.addStream(e))),t.push(i)}return t}getUsers(e,t,r,i=!1){return this.index=e,this.pagesize=r||this.pagesize,this.client.getUsers(this.roomId,this.userId,this.pagesize,this.index+1,t,i).then((e=>{let t=e.value;this.total=e.total,this.pagesize=e.pagesize,this.index=e.index;let r=this.parseGetUser(t);return this.fire("users-list",[{usersEvent:{participants:r}}]),{participants:r,total:this.total}}))}getTotalUsers(){return this.total}getInfo(e){return e.ua=e.ua?e.ua:he(),e.device=e.device?e.device:le(),e.platform=e.platform?e.platform:"Web",e.network=e.network?e.network:"unknown",e.role=e.role?e.role:"anchor",e.create=this.create,e.secret=this.secret,e.nickname=this.nickname,e.userinfo=this.userinfo,e.permission=this.permission,e.custom_token=this.custom_token,e.name=this.name,this.create&&(e.limit=this.limit,e.limittime=this.limittime,e.stoptime=this.stoptime),e.pagesize=this.pagesize,e}getCustomStats(){return this.customStats}sendMessage(e,t){return this.client.sendMessage(this.roomId,this.userId,t,e).then((e=>(D.Log().log(Qe.default.stringify(e)),e))).catch((e=>{throw D.Log().error(e),e}))}customMessage(e,t){return this.client.customMessage(this.roomId,this.userId,t,e).then((e=>(D.Log().log(Qe.default.stringify(e)),e))).catch((e=>{throw D.Log().error(e),e}))}moveUserRoom(e,t,r){return this.client.moveUserRoom(e,t,r)}release(){return this.client.releaseRoom(this.roomId,this.userId).then((e=>(D.Log().log(Qe.default.stringify(e)),e))).catch((e=>{throw D.Log().error(e),e}))}close(){this.client&&(this.client.close(),this.client=void 0)}SpeakerDetector(){return new ot}Recorder(e){var t;let r=new mt(e);return D.Log().info("create local recorder"),r.addEventListener("started",(()=>{D.Log().info("local recorder started.")})),r.addEventListener("stopped",(()=>{var e,t;D.Log().info("local recorder stopped");let i=null==(e=this.recorders)?void 0:e.indexOf(r);i&&i>=0&&(this.recorders=null==(t=this.recorders)?void 0:t.splice(i,1))})),r.addEventListener("track-ended",(()=>{D.Log().info("local recorder track ended")})),null==(t=this.recorders)||t.push(r),r}removeAllListeners(){this.off()}Stream(e){if(this.client)return new Ke(this.client,this,this.getLocalParticipant(),!0,e)}};function yt(e){return e.screen?Ke.sharing().start(e):(e.audio&&e.audio.deviceId&&(e.audio.deviceId={exact:e.audio.deviceId}),e.video&&e.video.deviceId&&(e.video.deviceId={exact:e.video.deviceId}),navigator.mediaDevices.getUserMedia(e))}}(dist$2);var BRTC={exports:{}};!function(e,t){window,e.exports=function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=30)}([function(e,t,r){r.d(t,"d",(function(){return n})),r.d(t,"a",(function(){return s})),r.d(t,"h",(function(){return o})),r.d(t,"i",(function(){return a})),r.d(t,"f",(function(){return c})),r.d(t,"c",(function(){return u})),r.d(t,"g",(function(){return d})),r.d(t,"e",(function(){return h})),r.d(t,"b",(function(){return p}));var i=r(2);function n(e){return typeof e===i.i}function s(e){return Array.isArray(e)}function o(e){return e!==i.g&&"object"==typeof e}function a(e){return"string"==typeof e}function c(e){return"number"==typeof e&&!isNaN(e)}function u(e){return"boolean"==typeof e}function d(e){return c(e)||a(e)&&!isNaN(parseFloat(e))&&isFinite(+e)}const l={}.hasOwnProperty;function h(e){if(!o(e)||e.nodeType||e===e.window)return!1;if(e.constructor&&!l.call(e,"constructor")&&!l.call(e.constructor.prototype||{},"isPrototypeOf"))return!1;let t;for(t in e);return void 0===t||l.call(e,t)}function p(e){return e instanceof ArrayBuffer}},function(e,t,r){r.r(t),function(e){r.d(t,"TRACE",(function(){return s})),r.d(t,"DEBUG",(function(){return o})),r.d(t,"INFO",(function(){return a})),r.d(t,"WARN",(function(){return c})),r.d(t,"ERROR",(function(){return u})),r.d(t,"FATAL",(function(){return d})),r.d(t,"setLevel",(function(){return v})),r.d(t,"trace",(function(){return _})),r.d(t,"debug",(function(){return b})),r.d(t,"info",(function(){return S})),r.d(t,"call",(function(){return I})),r.d(t,"warn",(function(){return E})),r.d(t,"error",(function(){return T})),r.d(t,"fatal",(function(){return R})),r.d(t,"log",(function(){return w})),r.d(t,"setDefaultTag",(function(){return A})),r.d(t,"enableUploadLog",(function(){return M})),r.d(t,"disableUploadLog",(function(){return O})),r.d(t,"canUploadLog",(function(){return P})),r.d(t,"setUploadLevel",(function(){return L})),r.d(t,"getUploadLevel",(function(){return x}));var i=r(2),n=r(3);const s=0,o=1,a=2,c=3,u=4,d=5;let l="bjy";const h=typeof console!==i.j?console:i.g,p=/bjy/.test(Object(n.a)(i.b))?a:c,m=i.n&&/edge|msie|trident/i.test(i.n.navigator.userAgent)?i.c:"%c",f=h?m?function(e,t,r,i){i?h.log(m+e,r,t,i):h.log(m+e,r,t)}:function(e,t,r){r?h.log(e,t,r):h.log(e,t)}:i.b;function g(){if(i.e){const e=i.e.BJY_LOG_LEVEL;if(e>=s&&e<=d)return e}return p}function v(t){e.BJY_LOG_LEVEL=t}function y(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function _(e,t){g()<=s&&f((t||l)+" trace",e,y("#999"))}function b(e,t){g()<=o&&f((t||l)+" debug",e,y("#999"))}function S(e,t){g()<=a&&f((t||l)+" info",e,y("#2db7f5"))}function I(e,t,r){g()<=a&&f((t||l)+" info",e,y("#66cdaa"),r)}function E(e,t){g()<=c&&f((t||l)+" warn",e,y("#f90"))}function T(e,t){g()<=u&&f((t||l)+" error",e,y("#ed4014"))}function R(e,t){if(g()<=d)throw new Error(`[${t||l} fatal]: ${e}`)}function w(e,t,r){e===s?_(t,r):e===o?b(t,r):e===a?S(t,r):e===c?E(t,r):e===u?T(t,r):e===d&&R(t,r)}function A(e){l=e}let k=!0,C=c;function M(){k=!0}function O(){k=!1}function P(){return k}function L(e){C=e}function x(){return C}}.call(this,r(7))},function(e,t,r){(function(e){r.d(t,"l",(function(){return i})),r.d(t,"d",(function(){return n})),r.d(t,"g",(function(){return s})),r.d(t,"m",(function(){return o})),r.d(t,"f",(function(){return a})),r.d(t,"j",(function(){return c})),r.d(t,"i",(function(){return u})),r.d(t,"k",(function(){return d})),r.d(t,"h",(function(){return l})),r.d(t,"n",(function(){return h})),r.d(t,"e",(function(){return p})),r.d(t,"b",(function(){return m})),r.d(t,"a",(function(){return f})),r.d(t,"c",(function(){return g}));const i=!0,n=!1,s=null,o=void 0,a=-1,c="undefined",u="function",d="*",l=".",h=typeof window!==c?window:o,p=typeof e!==c?e:h,m=function(){},f=(Object.freeze({}),Object.freeze([])),g=""}).call(this,r(7))},function(e,t,r){r.d(t,"a",(function(){return n}));var i=r(2);function n(e,t){return e!=i.g&&e.toString?e.toString():t!==i.m?t:i.c}},function(e,t,r){r.d(t,"c",(function(){return s})),r.d(t,"b",(function(){return o})),r.d(t,"d",(function(){return a})),r.d(t,"a",(function(){return c}));var i=r(0),n=r(2);function s(e,t,r){return i.f(r)?t===r?n.c:e.slice(t,r):e.slice(t)}function o(e,t,r){return e.indexOf(t,r!==n.m?r:0)}function a(e,t){return 0===o(e,t)}function c(e,t){return o(e,t)>=0}r(3)},function(e,t,r){(function(e){var i=r(8),n=r(2);let s;typeof e===n.i&&Object(i.a)(e)&&(s=e),s=typeof MessageChannel===n.i&&Object(i.a)(MessageChannel)?function(e){const t=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(1)}:setTimeout,t.a=s}).call(this,r(14).setImmediate)},function(e,t,r){(function(t){e.exports=function(){function e(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 r(t){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?e(Object(i),!0).forEach((function(e){d(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function i(){i=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},s=n.iterator||"@@iterator",o=n.asyncIterator||"@@asyncIterator",a=n.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function u(e,t,r,i){var n=t&&t.prototype instanceof h?t:h,s=Object.create(n.prototype),o=new T(i||[]);return s._invoke=function(e,t,r){var i="suspendedStart";return function(n,s){if("executing"===i)throw new Error("Generator is already running");if("completed"===i){if("throw"===n)throw s;return{value:void 0,done:!0}}for(r.method=n,r.arg=s;;){var o=r.delegate;if(o){var a=S(o,r);if(a){if(a===l)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===i)throw i="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i="executing";var c=d(e,t,r);if("normal"===c.type){if(i=r.done?"completed":"suspendedYield",c.arg===l)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(i="completed",r.method="throw",r.arg=c.arg)}}}(e,r,o),s}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var l={};function h(){}function p(){}function m(){}var f={};c(f,s,(function(){return this}));var g=Object.getPrototypeOf,v=g&&g(g(R([])));v&&v!==t&&r.call(v,s)&&(f=v);var y=m.prototype=h.prototype=Object.create(f);function _(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function i(n,s,o,a){var c=d(e[n],e,s);if("throw"!==c.type){var u=c.arg,l=u.value;return l&&"object"==typeof l&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){i("next",e,o,a)}),(function(e){i("throw",e,o,a)})):t.resolve(l).then((function(e){u.value=e,o(u)}),(function(e){return i("throw",e,o,a)}))}a(c.arg)}var n;this._invoke=function(e,r){function s(){return new t((function(t,n){i(e,r,t,n)}))}return n=n?n.then(s,s):s()}}function S(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method))return l;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return l}var i=d(r,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,l;var n=i.arg;return n?n.done?(t[e.resultName]=n.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,l):n:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,l)}function I(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function T(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(I,this),this.reset(!0)}function R(e){if(e){var t=e[s];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var i=-1,n=function t(){for(;++i<e.length;)if(r.call(e,i))return t.value=e[i],t.done=!1,t;return t.value=void 0,t.done=!0,t};return n.next=n}}return{next:w}}function w(){return{value:void 0,done:!0}}return p.prototype=m,c(y,"constructor",m),c(m,"constructor",p),p.displayName=c(m,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===p||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,m):(e.__proto__=m,c(e,a,"GeneratorFunction")),e.prototype=Object.create(y),e},e.awrap=function(e){return{__await:e}},_(b.prototype),c(b.prototype,o,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,i,n,s){void 0===s&&(s=Promise);var o=new b(u(t,r,i,n),s);return e.isGeneratorFunction(r)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},_(y),c(y,a,"Generator"),c(y,s,(function(){return this})),c(y,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function r(){for(;t.length;){var i=t.pop();if(i in e)return r.value=i,r.done=!1,r}return r.done=!0,r}},e.values=R,T.prototype={constructor:T,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function i(r,i){return o.type="throw",o.arg=e,t.next=r,i&&(t.method="next",t.arg=void 0),!!i}for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n],o=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=r.call(s,"catchLoc"),c=r.call(s,"finallyLoc");if(a&&c){if(this.prev<s.catchLoc)return i(s.catchLoc,!0);if(this.prev<s.finallyLoc)return i(s.finallyLoc)}else if(a){if(this.prev<s.catchLoc)return i(s.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return i(s.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var n=this.tryEntries[i];if(n.tryLoc<=this.prev&&r.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var s=n;break}}s&&("break"===e||"continue"===e)&&s.tryLoc<=t&&t<=s.finallyLoc&&(s=null);var o=s?s.completion:{};return o.type=e,o.arg=t,s?(this.method="next",this.next=s.finallyLoc,l):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),l},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),E(r),l}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var i=r.completion;if("throw"===i.type){var n=i.arg;E(r)}return n}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:R(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),l}},e}function n(e){return(n="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})(e)}function s(e,t,r,i,n,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(i,n)}function o(e){return function(){var t=this,r=arguments;return new Promise((function(i,n){var o=e.apply(t,r);function a(e){s(o,i,n,a,c,"next",e)}function c(e){s(o,i,n,a,c,"throw",e)}a(void 0)}))}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function u(e,t,r){return t&&c(e.prototype,t),r&&c(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function d(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&p(e,t)}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function p(e,t){return(p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function m(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function f(e,t,r){return(f=m()?Reflect.construct.bind():function(e,t,r){var i=[null];i.push.apply(i,t);var n=new(Function.bind.apply(e,i));return r&&p(n,r.prototype),n}).apply(null,arguments)}function g(e){var t="function"==typeof Map?new Map:void 0;return(g=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return f(e,arguments,h(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),p(i,e)})(e)}function v(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function y(e){var t=m();return function(){var r,i=h(e);if(t){var n=h(this).constructor;r=Reflect.construct(i,arguments,n)}else r=i.apply(this,arguments);return v(this,r)}}function _(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=h(e)););return e}function b(){return(b="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var i=_(e,t);if(i){var n=Object.getOwnPropertyDescriptor(i,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}}).apply(this,arguments)}function S(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var i,n,s=[],o=!0,a=!1;try{for(r=r.call(e);!(o=(i=r.next()).done)&&(s.push(i.value),!t||s.length!==t);o=!0);}catch(e){a=!0,n=e}finally{try{o||null==r.return||r.return()}finally{if(a)throw n}}return s}}(e,t)||E(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function I(e){return function(e){if(Array.isArray(e))return T(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||E(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function E(e,t){if(e){if("string"==typeof e)return T(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?T(e,t):void 0}}function T(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r<t;r++)i[r]=e[r];return i}function R(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=E(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,s=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw s}}}}function w(e,t,r,i,n){var s={};return Object.keys(i).forEach((function(e){s[e]=i[e]})),s.enumerable=!!s.enumerable,s.configurable=!!s.configurable,("value"in s||s.initializer)&&(s.writable=!0),s=r.slice().reverse().reduce((function(r,i){return i(e,t,r)||r}),s),n&&void 0!==s.initializer&&(s.value=s.initializer?s.initializer.call(n):void 0,s.initializer=void 0),void 0===s.initializer&&(Object.defineProperty(e,t,s),s=null),s}var A="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{},k=function(e){return e&&e.Math==Math&&e},C=k("object"==typeof globalThis&&globalThis)||k("object"==typeof window&&window)||k("object"==typeof self&&self)||k("object"==typeof A&&A)||function(){return this}()||Function("return this")(),M={},O=function(e){try{return!!e()}catch(e){return!0}},P=!O((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),L=!O((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),x=L,D=Function.prototype.call,N=x?D.bind(D):function(){return D.apply(D,arguments)},$={},U={}.propertyIsEnumerable,B=Object.getOwnPropertyDescriptor,V=B&&!U.call({1:2},1);$.f=V?function(e){var t=B(this,e);return!!t&&t.enumerable}:U;var F,j,W=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},q=L,G=Function.prototype,H=G.call,z=q&&G.bind.bind(H,H),J=function(e){return q?z(e):function(){return H.apply(e,arguments)}},Y=J,K=Y({}.toString),Q=Y("".slice),X=function(e){return Q(K(e),8,-1)},Z=X,ee=J,te=function(e){if("Function"===Z(e))return ee(e)},re=O,ie=X,ne=Object,se=te("".split),oe=re((function(){return!ne("z").propertyIsEnumerable(0)}))?function(e){return"String"==ie(e)?se(e,""):ne(e)}:ne,ae=function(e){return null==e},ce=ae,ue=TypeError,de=function(e){if(ce(e))throw ue("Can't call method on "+e);return e},le=oe,he=de,pe=function(e){return le(he(e))},me="object"==typeof document&&document.all,fe={all:me,IS_HTMLDDA:void 0===me&&void 0!==me},ge=fe.all,ve=fe.IS_HTMLDDA?function(e){return"function"==typeof e||e===ge}:function(e){return"function"==typeof e},ye=ve,_e=fe.all,be=fe.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:ye(e)||e===_e}:function(e){return"object"==typeof e?null!==e:ye(e)},Se=C,Ie=ve,Ee=function(e){return Ie(e)?e:void 0},Te=function(e,t){return arguments.length<2?Ee(Se[e]):Se[e]&&Se[e][t]},Re=te({}.isPrototypeOf),we=Te("navigator","userAgent")||"",Ae=C,ke=we,Ce=Ae.process,Me=Ae.Deno,Oe=Ce&&Ce.versions||Me&&Me.version,Pe=Oe&&Oe.v8;Pe&&(j=(F=Pe.split("."))[0]>0&&F[0]<4?1:+(F[0]+F[1])),!j&&ke&&(!(F=ke.match(/Edge\/(\d+)/))||F[1]>=74)&&(F=ke.match(/Chrome\/(\d+)/))&&(j=+F[1]);var Le=j,xe=Le,De=O,Ne=!!Object.getOwnPropertySymbols&&!De((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&xe&&xe<41})),$e=Ne&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Ue=Te,Be=ve,Ve=Re,Fe=Object,je=$e?function(e){return"symbol"==typeof e}:function(e){var t=Ue("Symbol");return Be(t)&&Ve(t.prototype,Fe(e))},We=String,qe=function(e){try{return We(e)}catch(e){return"Object"}},Ge=ve,He=qe,ze=TypeError,Je=function(e){if(Ge(e))return e;throw ze(He(e)+" is not a function")},Ye=Je,Ke=ae,Qe=function(e,t){var r=e[t];return Ke(r)?void 0:Ye(r)},Xe=N,Ze=ve,et=be,tt=TypeError,rt={exports:{}},it=C,nt=Object.defineProperty,st=function(e,t){try{nt(it,e,{value:t,configurable:!0,writable:!0})}catch(r){it[e]=t}return t},ot=st,at="__core-js_shared__",ct=C[at]||ot(at,{}),ut=ct;(rt.exports=function(e,t){return ut[e]||(ut[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.25.5",mode:"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.25.5/LICENSE",source:"https://github.com/zloirock/core-js"});var dt=de,lt=Object,ht=function(e){return lt(dt(e))},pt=ht,mt=te({}.hasOwnProperty),ft=Object.hasOwn||function(e,t){return mt(pt(e),t)},gt=te,vt=0,yt=Math.random(),_t=gt(1..toString),bt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+_t(++vt+yt,36)},St=C,It=rt.exports,Et=ft,Tt=bt,Rt=Ne,wt=$e,At=It("wks"),kt=St.Symbol,Ct=kt&&kt.for,Mt=wt?kt:kt&&kt.withoutSetter||Tt,Ot=function(e){if(!Et(At,e)||!Rt&&"string"!=typeof At[e]){var t="Symbol."+e;Rt&&Et(kt,e)?At[e]=kt[e]:At[e]=wt&&Ct?Ct(t):Mt(t)}return At[e]},Pt=N,Lt=be,xt=je,Dt=Qe,Nt=TypeError,$t=Ot("toPrimitive"),Ut=function(e,t){if(!Lt(e)||xt(e))return e;var r,i=Dt(e,$t);if(i){if(void 0===t&&(t="default"),r=Pt(i,e,t),!Lt(r)||xt(r))return r;throw Nt("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var r,i;if("string"===t&&Ze(r=e.toString)&&!et(i=Xe(r,e)))return i;if(Ze(r=e.valueOf)&&!et(i=Xe(r,e)))return i;if("string"!==t&&Ze(r=e.toString)&&!et(i=Xe(r,e)))return i;throw tt("Can't convert object to primitive value")}(e,t)},Bt=Ut,Vt=je,Ft=function(e){var t=Bt(e,"string");return Vt(t)?t:t+""},jt=be,Wt=C.document,qt=jt(Wt)&&jt(Wt.createElement),Gt=function(e){return qt?Wt.createElement(e):{}},Ht=Gt,zt=!P&&!O((function(){return 7!=Object.defineProperty(Ht("div"),"a",{get:function(){return 7}}).a})),Jt=P,Yt=N,Kt=$,Qt=W,Xt=pe,Zt=Ft,er=ft,tr=zt,rr=Object.getOwnPropertyDescriptor;M.f=Jt?rr:function(e,t){if(e=Xt(e),t=Zt(t),tr)try{return rr(e,t)}catch(e){}if(er(e,t))return Qt(!Yt(Kt.f,e,t),e[t])};var ir={},nr=P&&O((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),sr=be,or=String,ar=TypeError,cr=function(e){if(sr(e))return e;throw ar(or(e)+" is not an object")},ur=P,dr=zt,lr=nr,hr=cr,pr=Ft,mr=TypeError,fr=Object.defineProperty,gr=Object.getOwnPropertyDescriptor;ir.f=ur?lr?function(e,t,r){if(hr(e),t=pr(t),hr(r),"function"==typeof e&&"prototype"===t&&"value"in r&&"writable"in r&&!r.writable){var i=gr(e,t);i&&i.writable&&(e[t]=r.value,r={configurable:"configurable"in r?r.configurable:i.configurable,enumerable:"enumerable"in r?r.enumerable:i.enumerable,writable:!1})}return fr(e,t,r)}:fr:function(e,t,r){if(hr(e),t=pr(t),hr(r),dr)try{return fr(e,t,r)}catch(e){}if("get"in r||"set"in r)throw mr("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var vr=ir,yr=W,_r=P?function(e,t,r){return vr.f(e,t,yr(1,r))}:function(e,t,r){return e[t]=r,e},br={exports:{}},Sr=P,Ir=ft,Er=Function.prototype,Tr=Sr&&Object.getOwnPropertyDescriptor,Rr=Ir(Er,"name"),wr={EXISTS:Rr,PROPER:Rr&&"something"===function(){}.name,CONFIGURABLE:Rr&&(!Sr||Sr&&Tr(Er,"name").configurable)},Ar=ve,kr=ct,Cr=te(Function.toString);Ar(kr.inspectSource)||(kr.inspectSource=function(e){return Cr(e)});var Mr,Or,Pr,Lr=kr.inspectSource,xr=ve,Dr=C.WeakMap,Nr=xr(Dr)&&/native code/.test(String(Dr)),$r=rt.exports,Ur=bt,Br=$r("keys"),Vr=function(e){return Br[e]||(Br[e]=Ur(e))},Fr={},jr=Nr,Wr=C,qr=be,Gr=_r,Hr=ft,zr=ct,Jr=Vr,Yr=Fr,Kr="Object already initialized",Qr=Wr.TypeError,Xr=Wr.WeakMap;if(jr||zr.state){var Zr=zr.state||(zr.state=new Xr);Zr.get=Zr.get,Zr.has=Zr.has,Zr.set=Zr.set,Mr=function(e,t){if(Zr.has(e))throw Qr(Kr);return t.facade=e,Zr.set(e,t),t},Or=function(e){return Zr.get(e)||{}},Pr=function(e){return Zr.has(e)}}else{var ei=Jr("state");Yr[ei]=!0,Mr=function(e,t){if(Hr(e,ei))throw Qr(Kr);return t.facade=e,Gr(e,ei,t),t},Or=function(e){return Hr(e,ei)?e[ei]:{}},Pr=function(e){return Hr(e,ei)}}var ti={set:Mr,get:Or,has:Pr,enforce:function(e){return Pr(e)?Or(e):Mr(e,{})},getterFor:function(e){return function(t){var r;if(!qr(t)||(r=Or(t)).type!==e)throw Qr("Incompatible receiver, "+e+" required");return r}}},ri=O,ii=ve,ni=ft,si=P,oi=wr.CONFIGURABLE,ai=Lr,ci=ti.enforce,ui=ti.get,di=Object.defineProperty,li=si&&!ri((function(){return 8!==di((function(){}),"length",{value:8}).length})),hi=String(String).split("String"),pi=br.exports=function(e,t,r){"Symbol("===String(t).slice(0,7)&&(t="["+String(t).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!ni(e,"name")||oi&&e.name!==t)&&(si?di(e,"name",{value:t,configurable:!0}):e.name=t),li&&r&&ni(r,"arity")&&e.length!==r.arity&&di(e,"length",{value:r.arity});try{r&&ni(r,"constructor")&&r.constructor?si&&di(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(e){}var i=ci(e);return ni(i,"source")||(i.source=hi.join("string"==typeof t?t:"")),e};Function.prototype.toString=pi((function(){return ii(this)&&ui(this).source||ai(this)}),"toString");var mi=ve,fi=ir,gi=br.exports,vi=st,yi=function(e,t,r,i){i||(i={});var n=i.enumerable,s=void 0!==i.name?i.name:t;if(mi(r)&&gi(r,s,i),i.global)n?e[t]=r:vi(t,r);else{try{i.unsafe?e[t]&&(n=!0):delete e[t]}catch(e){}n?e[t]=r:fi.f(e,t,{value:r,enumerable:!1,configurable:!i.nonConfigurable,writable:!i.nonWritable})}return e},_i={},bi=Math.ceil,Si=Math.floor,Ii=Math.trunc||function(e){var t=+e;return(t>0?Si:bi)(t)},Ei=function(e){var t=+e;return t!=t||0===t?0:Ii(t)},Ti=Ei,Ri=Math.max,wi=Math.min,Ai=function(e,t){var r=Ti(e);return r<0?Ri(r+t,0):wi(r,t)},ki=Ei,Ci=Math.min,Mi=function(e){return e>0?Ci(ki(e),9007199254740991):0},Oi=Mi,Pi=function(e){return Oi(e.length)},Li=pe,xi=Ai,Di=Pi,Ni=function(e){return function(t,r,i){var n,s=Li(t),o=Di(s),a=xi(i,o);if(e&&r!=r){for(;o>a;)if((n=s[a++])!=n)return!0}else for(;o>a;a++)if((e||a in s)&&s[a]===r)return e||a||0;return!e&&-1}},$i={includes:Ni(!0),indexOf:Ni(!1)},Ui=ft,Bi=pe,Vi=$i.indexOf,Fi=Fr,ji=te([].push),Wi=function(e,t){var r,i=Bi(e),n=0,s=[];for(r in i)!Ui(Fi,r)&&Ui(i,r)&&ji(s,r);for(;t.length>n;)Ui(i,r=t[n++])&&(~Vi(s,r)||ji(s,r));return s},qi=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Gi=Wi,Hi=qi.concat("length","prototype");_i.f=Object.getOwnPropertyNames||function(e){return Gi(e,Hi)};var zi={};zi.f=Object.getOwnPropertySymbols;var Ji=Te,Yi=_i,Ki=zi,Qi=cr,Xi=te([].concat),Zi=Ji("Reflect","ownKeys")||function(e){var t=Yi.f(Qi(e)),r=Ki.f;return r?Xi(t,r(e)):t},en=ft,tn=Zi,rn=M,nn=ir,sn=O,on=ve,an=/#|\.prototype\./,cn=function(e,t){var r=dn[un(e)];return r==hn||r!=ln&&(on(t)?sn(t):!!t)},un=cn.normalize=function(e){return String(e).replace(an,".").toLowerCase()},dn=cn.data={},ln=cn.NATIVE="N",hn=cn.POLYFILL="P",pn=cn,mn=C,fn=M.f,gn=_r,vn=yi,yn=st,_n=function(e,t,r){for(var i=tn(t),n=nn.f,s=rn.f,o=0;o<i.length;o++){var a=i[o];en(e,a)||r&&en(r,a)||n(e,a,s(t,a))}},bn=pn,Sn=function(e,t){var r,i,n,s,o,a=e.target,c=e.global,u=e.stat;if(r=c?mn:u?mn[a]||yn(a,{}):(mn[a]||{}).prototype)for(i in t){if(s=t[i],n=e.dontCallGetSet?(o=fn(r,i))&&o.value:r[i],!bn(c?i:a+(u?".":"#")+i,e.forced)&&void 0!==n){if(typeof s==typeof n)continue;_n(s,n)}(e.sham||n&&n.sham)&&gn(s,"sham",!0),vn(r,i,s,e)}},In=Je,En=L,Tn=te(te.bind),Rn=function(e,t){return In(e),void 0===t?e:En?Tn(e,t):function(){return e.apply(t,arguments)}},wn=X,An=Array.isArray||function(e){return"Array"==wn(e)},kn={};kn[Ot("toStringTag")]="z";var Cn="[object z]"===String(kn),Mn=Cn,On=ve,Pn=X,Ln=Ot("toStringTag"),xn=Object,Dn="Arguments"==Pn(function(){return arguments}()),Nn=Mn?Pn:function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=xn(e),Ln))?r:Dn?Pn(t):"Object"==(i=Pn(t))&&On(t.callee)?"Arguments":i},$n=te,Un=O,Bn=ve,Vn=Nn,Fn=Lr,jn=function(){},Wn=[],qn=Te("Reflect","construct"),Gn=/^\s*(?:class|function)\b/,Hn=$n(Gn.exec),zn=!Gn.exec(jn),Jn=function(e){if(!Bn(e))return!1;try{return qn(jn,Wn,e),!0}catch(e){return!1}},Yn=function(e){if(!Bn(e))return!1;switch(Vn(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return zn||!!Hn(Gn,Fn(e))}catch(e){return!0}};Yn.sham=!0;var Kn=!qn||Un((function(){var e;return Jn(Jn.call)||!Jn(Object)||!Jn((function(){e=!0}))||e}))?Yn:Jn,Qn=An,Xn=Kn,Zn=be,es=Ot("species"),ts=Array,rs=function(e,t){return new(function(e){var t;return Qn(e)&&(t=e.constructor,(Xn(t)&&(t===ts||Qn(t.prototype))||Zn(t)&&null===(t=t[es]))&&(t=void 0)),void 0===t?ts:t}(e))(0===t?0:t)},is=Rn,ns=oe,ss=ht,os=Pi,as=rs,cs=te([].push),us=function(e){var t=1==e,r=2==e,i=3==e,n=4==e,s=6==e,o=7==e,a=5==e||s;return function(c,u,d,l){for(var h,p,m=ss(c),f=ns(m),g=is(u,d),v=os(f),y=0,_=l||as,b=t?_(c,v):r||o?_(c,0):void 0;v>y;y++)if((a||y in f)&&(p=g(h=f[y],y,m),e))if(t)b[y]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return y;case 2:cs(b,h)}else switch(e){case 4:return!1;case 7:cs(b,h)}return s?-1:i||n?n:b}},ds={forEach:us(0),map:us(1),filter:us(2),some:us(3),every:us(4),find:us(5),findIndex:us(6),filterReject:us(7)},ls=O,hs=Le,ps=Ot("species"),ms=function(e){return hs>=51||!ls((function(){var t=[];return(t.constructor={})[ps]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},fs=ds.map;Sn({target:"Array",proto:!0,forced:!ms("map")},{map:function(e){return fs(this,e,arguments.length>1?arguments[1]:void 0)}});var gs=ds.filter;Sn({target:"Array",proto:!0,forced:!ms("filter")},{filter:function(e){return gs(this,e,arguments.length>1?arguments[1]:void 0)}});var vs=Nn,ys=Cn?{}.toString:function(){return"[object "+vs(this)+"]"};Cn||yi(Object.prototype,"toString",ys,{unsafe:!0});var _s=Sn,bs=O,Ss=pe,Is=M.f,Es=P,Ts=bs((function(){Is(1)}));_s({target:"Object",stat:!0,forced:!Es||Ts,sham:!Es},{getOwnPropertyDescriptor:function(e,t){return Is(Ss(e),t)}});let Rs=!0,ws=!0;function As(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function ks(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Cs(e){return"boolean"!=typeof e?new Error("Argument types: "+typeof e+". Please use a boolean."):(Rs=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Ms(e){return"boolean"!=typeof e?new Error("Argument types: "+typeof e+". Please use a boolean."):(ws=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Os(){if("object"==typeof window){if(Rs)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ps(e,t){ws&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Ls(e){return"[object Object]"===Object.prototype.toString.call(e)}function xs(e){return Ls(e)?Object.keys(e).reduce((function(t,r){const i=Ls(e[r]),n=i?xs(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function Ds(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&function e(t,r,i){r&&!i.has(r.id)&&(i.set(r.id,r),Object.keys(r).forEach((n=>{n.endsWith("Id")?e(t,t.get(r[n]),i):n.endsWith("Ids")&&r[n].forEach((r=>{e(t,t.get(r),i)}))})))}(e,r,n)}))})),n}const Ns=Os;function $s(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let o=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),Ns("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return Ns("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function Us(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Bs(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ks(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Vs(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Fs(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(s(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(n(t)))},r])})).then(r,i)}}function js(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ds(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ks(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ds(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Ws(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function qs(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Ws(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=o(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Gs(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function Hs(e,t){ks(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var zs=Object.freeze({__proto__:null,shimMediaStream:Us,shimOnTrack:Bs,shimGetSendersWithDtmf:Vs,shimGetStats:Fs,shimSenderReceiverGetStats:js,shimAddTrackRemoveTrackWithNative:Ws,shimAddTrackRemoveTrack:qs,shimPeerConnection:Gs,fixNegotiationNeeded:Hs,shimGetUserMedia:$s,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}}),Js={exports:{}};!function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&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.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),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){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<i.length;n++)r[(t=i[n].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(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;var t=e.substr(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){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),n=3;n<i.length;n++){var s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){var a=t.parseRtpMap(o),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return 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((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var n=0;return r.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,u=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));u.length>0&&u[0].length>1&&u[0][0]===c&&(r=u[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var n=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(r=n[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");n.length>0&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var o=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var 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,21)},t.writeSessionBoilerplate=function(e,r,i){var n=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,n){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+o,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+o,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+o,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var i=t.splitLines(e),n=0;n<i.length;n++)switch(i[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[n].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(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;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t}(Js);var Ys=Js.exports,Ks=Js.exports;function Qs(e,t,r,i,n){var s=Ks.writeRtpDescription(e.kind,t);if(s+=Ks.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=Ks.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":n||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=o;var a="msid:"+(i?i.id:"-")+" "+o+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+Ks.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+Ks.localCName+"\r\n"),s}function Xs(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},n=function(e,t,r,n){var s=i(e.parameters.apt,r),o=i(t.parameters.apt,n);return s&&o&&s.name.toLowerCase()===o.name.toLowerCase()};return e.codecs.forEach((function(i){for(var s=0;s<t.codecs.length;s++){var o=t.codecs[s];if(i.name.toLowerCase()===o.name.toLowerCase()&&i.clockRate===o.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&o.parameters.apt&&!n(i,o,e.codecs,t.codecs))continue;(o=JSON.parse(JSON.stringify(o))).numChannels=Math.min(i.numChannels,o.numChannels),r.codecs.push(o),o.rtcpFeedback=o.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var n=t.headerExtensions[i];if(e.uri===n.uri){r.headerExtensions.push(n);break}}})),r}function Zs(e,t,r){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][e].indexOf(r)}function eo(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function to(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}function ro(e){const t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(e).catch((e=>Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString(){return this.name}}}(e))))}}function io(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function no(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,n){var s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=n,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var n=function(r){var i=this,n=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=n[e].bind(n)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw to("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=Ks.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(n.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(n.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),n.prototype.onicecandidate=null,n.prototype.onaddstream=null,n.prototype.ontrack=null,n.prototype.onremovestream=null,n.prototype.onsignalingstatechange=null,n.prototype.oniceconnectionstatechange=null,n.prototype.onconnectionstatechange=null,n.prototype.onicegatheringstatechange=null,n.prototype.onnegotiationneeded=null,n.prototype.ondatachannel=null,n.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},n.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},n.prototype.getConfiguration=function(){return this._config},n.prototype.getLocalStreams=function(){return this.localStreams},n.prototype.getRemoteStreams=function(){return this.remoteStreams},n.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();i.iceTransport=n.iceTransport,i.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(i),i},n.prototype.addTrack=function(t,r){if(this._isClosed)throw to("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw to("InvalidAccessError","Track already exists.");for(var n=0;n<this.transceivers.length;n++)this.transceivers[n].track||this.transceivers[n].kind!==t.kind||(i=this.transceivers[n]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},n.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},n.prototype.removeTrack=function(t){if(this._isClosed)throw to("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw to("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},n.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},n.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},n.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},n.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;n.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},n.prototype._gather=function(t,r){var i=this,n=this.transceivers[r].iceGatherer;if(!n.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,n.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),n.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var o=e.candidate,a=!o||0===Object.keys(o).length;if(a)"new"!==n.state&&"gathering"!==n.state||(n.state="completed");else{"new"===n.state&&(n.state="gathering"),o.component=1,o.ufrag=n.getLocalParameters().usernameFragment;var c=Ks.writeCandidate(o);s.candidate=Object.assign(s.candidate,Ks.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var u=Ks.getMediaSections(i._localDescription.sdp);u[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=Ks.getDescription(i._localDescription.sdp)+u.join("");var d=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",s),d&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){n.onlocalcandidate(e)}))}),0)}},n.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},n.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},n.prototype._transceive=function(e,r,i){var n=Xs(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:Ks.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(n.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(n)),i&&e.rtpReceiver&&n.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?n.encodings=e.recvEncodingParameters:n.encodings=[{}],n.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(n.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(n.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(n))},n.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(to("TypeError",'Unsupported types "'+e.type+'"'));if(!Zs("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(to("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=Ks.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=Ks.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=Ks.splitSections(i._remoteDescription.sdp),r=t.shift();var n=Ks.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=i.transceivers[t],o=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,u=s.localCapabilities,d=s.remoteCapabilities;if(!(Ks.isRejected(e)&&0===Ks.matchPrefix(e,"a=bundle-only").length||s.rejected)){var l=Ks.getIceParameters(e,r),h=Ks.getDtlsParameters(e,r);n&&(h.role="server"),i.usingBundle&&0!==t||(i._gather(s.mid,t),"new"===a.state&&a.start(o,l,n?"controlling":"controlled"),"new"===c.state&&c.start(h));var p=Xs(u,d);i._transceive(s,p.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},n.prototype.setRemoteDescription=function(n){var s=this;if(-1===["offer","answer"].indexOf(n.type))return Promise.reject(to("TypeError",'Unsupported types "'+n.type+'"'));if(!Zs("setRemoteDescription",n.type,s.signalingState)||s._isClosed)return Promise.reject(to("InvalidStateError","Can not set remote "+n.type+" in state "+s.signalingState));var o={};s.remoteStreams.forEach((function(e){o[e.id]=e}));var a=[],c=Ks.splitSections(n.sdp),u=c.shift(),d=Ks.matchPrefix(u,"a=ice-lite").length>0,l=Ks.matchPrefix(u,"a=group:BUNDLE ").length>0;s.usingBundle=l;var h=Ks.matchPrefix(u,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!h&&h.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var h=Ks.splitLines(i),p=Ks.getKind(i),m=Ks.isRejected(i)&&0===Ks.matchPrefix(i,"a=bundle-only").length,f=h[0].substr(2).split(" ")[2],g=Ks.getDirection(i,u),v=Ks.parseMsid(i),y=Ks.getMid(i)||Ks.generateIdentifier();if(m||"application"===p&&("DTLS/SCTP"===f||"UDP/DTLS/SCTP"===f))s.transceivers[c]={mid:y,kind:p,protocol:f,rejected:!0};else{var _,b,S,I,E,T,R,w,A;!m&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(p,!0));var k,C,M=Ks.parseRtpParameters(i);m||(k=Ks.getIceParameters(i,u),(C=Ks.getDtlsParameters(i,u)).role="client"),R=Ks.parseRtpEncodingParameters(i);var O=Ks.parseRtcpParameters(i),P=Ks.matchPrefix(i,"a=end-of-candidates",u).length>0,L=Ks.matchPrefix(i,"a=candidate:").map((function(e){return Ks.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!m&&l&&c>0&&s.transceivers[c]&&(s._disposeIceAndDtlsTransports(c),s.transceivers[c].iceGatherer=s.transceivers[0].iceGatherer,s.transceivers[c].iceTransport=s.transceivers[0].iceTransport,s.transceivers[c].dtlsTransport=s.transceivers[0].dtlsTransport,s.transceivers[c].rtpSender&&s.transceivers[c].rtpSender.setTransport(s.transceivers[0].dtlsTransport),s.transceivers[c].rtpReceiver&&s.transceivers[c].rtpReceiver.setTransport(s.transceivers[0].dtlsTransport)),"offer"!==n.type||m)"answer"!==n.type||m||(b=(_=s.transceivers[c]).iceGatherer,S=_.iceTransport,I=_.dtlsTransport,E=_.rtpReceiver,T=_.sendEncodingParameters,w=_.localCapabilities,s.transceivers[c].recvEncodingParameters=R,s.transceivers[c].remoteCapabilities=M,s.transceivers[c].rtcpParameters=O,L.length&&"new"===S.state&&(!d&&!P||l&&0!==c?L.forEach((function(e){eo(_.iceTransport,e)})):S.setRemoteCandidates(L)),l&&0!==c||("new"===S.state&&S.start(b,k,"controlling"),"new"===I.state&&I.start(C)),!Xs(_.localCapabilities,_.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&_.sendEncodingParameters[0].rtx&&delete _.sendEncodingParameters[0].rtx,s._transceive(_,"sendrecv"===g||"recvonly"===g,"sendrecv"===g||"sendonly"===g),!E||"sendrecv"!==g&&"sendonly"!==g?delete _.rtpReceiver:(A=E.track,v?(o[v.stream]||(o[v.stream]=new e.MediaStream),r(A,o[v.stream]),a.push([A,E,o[v.stream]])):(o.default||(o.default=new e.MediaStream),r(A,o.default),a.push([A,E,o.default]))));else{(_=s.transceivers[c]||s._createTransceiver(p)).mid=y,_.iceGatherer||(_.iceGatherer=s._createIceGatherer(c,l)),L.length&&"new"===_.iceTransport.state&&(!P||l&&0!==c?L.forEach((function(e){eo(_.iceTransport,e)})):_.iceTransport.setRemoteCandidates(L)),w=e.RTCRtpReceiver.getCapabilities(p),t<15019&&(w.codecs=w.codecs.filter((function(e){return"rtx"!==e.name}))),T=_.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var x,D=!1;"sendrecv"===g||"sendonly"===g?(D=!_.rtpReceiver,E=_.rtpReceiver||new e.RTCRtpReceiver(_.dtlsTransport,p),D&&(A=E.track,v&&"-"===v.stream||(v?(o[v.stream]||(o[v.stream]=new e.MediaStream,Object.defineProperty(o[v.stream],"id",{get:function(){return v.stream}})),Object.defineProperty(A,"id",{get:function(){return v.track}}),x=o[v.stream]):(o.default||(o.default=new e.MediaStream),x=o.default)),x&&(r(A,x),_.associatedRemoteMediaStreams.push(x)),a.push([A,E,x]))):_.rtpReceiver&&_.rtpReceiver.track&&(_.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===_.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),_.associatedRemoteMediaStreams=[]),_.localCapabilities=w,_.remoteCapabilities=M,_.rtpReceiver=E,_.rtcpParameters=O,_.sendEncodingParameters=T,_.recvEncodingParameters=R,s._transceive(s.transceivers[c],!1,D)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===n.type?"active":"passive"),s._remoteDescription={type:n.type,sdp:n.sdp},"offer"===n.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(o).forEach((function(t){var r=o[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var n=new Event("addstream");n.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",n)}))}a.forEach((function(e){var t=e[0],n=e[1];r.id===e[2].id&&i(s,t,n,[r])}))}})),a.forEach((function(e){e[2]||i(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},n.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},n.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},n.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},n.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},n.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},n.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(to("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,n=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(i=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(n=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--n<0&&(e.wantReceive=!1)}));i>0||n>0;)i>0&&(r._createTransceiver("audio"),i--),n>0&&(r._createTransceiver("video"),n--);var o=Ks.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,n){var s=i.track,o=i.kind,a=i.mid||Ks.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(n,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(o);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var u=i.sendEncodingParameters||[{ssrc:1001*(2*n+1)}];s&&t>=15019&&"video"===o&&!u[0].rtx&&(u[0].rtx={ssrc:u[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,o)),i.localCapabilities=c,i.sendEncodingParameters=u})),"max-compat"!==r._config.bundlePolicy&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){o+=Qs(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),o+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,o+="a="+Ks.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(o+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:o});return Promise.resolve(a)},n.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(to("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(to("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=Ks.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var n=Ks.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>n)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var o;e.stream&&("audio"===e.kind?o=e.stream.getAudioTracks()[0]:"video"===e.kind&&(o=e.stream.getVideoTracks()[0]),o&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1}));var a=Xs(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=Qs(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(s)},n.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,n){if(!r._remoteDescription)return n(to("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var o=0;o<r.transceivers.length;o++)if(r.transceivers[o].mid===e.sdpMid){s=o;break}var a=r.transceivers[s];if(!a)return n(to("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?Ks.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!eo(a.iceTransport,c))return n(to("OperationError","Can not add ICE candidate"));var u=e.candidate.trim();0===u.indexOf("a=")&&(u=u.substr(2)),(t=Ks.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?u:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=Ks.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var d=0;d<r.transceivers.length&&(r.transceivers[d].rejected||(r.transceivers[d].iceTransport.addRemoteCandidate({}),(t=Ks.getMediaSections(r._remoteDescription.sdp))[d]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=Ks.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));d++);i()}))},n.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw to("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),n}(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((e=>{if(e&&(e.urls||e.url)){let t=e.urls||e.url;e.url&&!e.urls&&Ps("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),Os("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function so(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var oo=Object.freeze({__proto__:null,shimPeerConnection:no,shimReplaceTrack:so,shimGetUserMedia:ro,shimGetDisplayMedia:io});function ao(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){Ps("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function co(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function uo(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,s)}}function lo(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ho(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ks(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function po(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ps("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function mo(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function fo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function go(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function vo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function yo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var _o=Object.freeze({__proto__:null,shimOnTrack:co,shimPeerConnection:uo,shimSenderGetStats:lo,shimReceiverGetStats:ho,shimRemoveStream:po,shimRTCDataChannel:mo,shimAddTransceiver:fo,shimGetParameters:go,shimCreateOffer:vo,shimCreateAnswer:yo,shimGetUserMedia:ao,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function bo(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function So(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function Io(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function Eo(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(To(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function To(e){return e&&void 0!==e.video?Object.assign({},e,{video:xs(e.video)}):e}function Ro(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(Ps("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function wo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ao(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function ko(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Co=Object.freeze({__proto__:null,shimLocalStreamsAPI:bo,shimRemoteStreamsAPI:So,shimCallbacksAPI:Io,shimGetUserMedia:Eo,shimConstraints:To,shimRTCIceServerUrls:Ro,shimTrackEventTransceiver:wo,shimCreateOfferLegacy:Ao,shimAudioContext:ko});function Mo(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=Ys.parseCandidate(e.candidate),n=Object.assign(r,i);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ks(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Oo(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=function(e){if(!e||!e.sdp)return!1;const t=Ys.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Ys.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},n=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},s=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=Ys.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=n(e),r=s(arguments[0],e);let o;o=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function Po(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},ks(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Lo(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function xo(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function Do(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var No=Object.freeze({__proto__:null,shimRTCIceCandidate:Mo,shimMaxMessageSize:Oo,shimSendThrowTypeError:Po,shimConnectionState:Lo,removeExtmapAllowMixed:xo,shimAddIceCandidateNullOrEmpty:Do});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=Os,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=As(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=As(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=As(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=As(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:No,extractVersion:As,disableLog:Cs,disableWarnings:Ms};switch(i.browser){case"chrome":if(!zs||!Gs||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=zs,Do(e,i),$s(e,i),Us(e),Gs(e,i),Bs(e),qs(e,i),Vs(e),Fs(e),js(e),Hs(e,i),Mo(e),Lo(e),Oo(e,i),Po(e),xo(e,i);break;case"firefox":if(!_o||!uo||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=_o,Do(e,i),ao(e,i),uo(e,i),co(e),po(e),lo(e),ho(e),mo(e),fo(e),go(e),vo(e),yo(e),Mo(e),Lo(e),Oo(e,i),Po(e);break;case"edge":if(!oo||!no||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),n;r("adapter.js shimming edge."),n.browserShim=oo,ro(e),io(e),no(e,i),so(e),Oo(e,i),Po(e);break;case"safari":if(!Co||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=Co,Do(e,i),Ro(e),Ao(e),Io(e),bo(e),So(e),wo(e),Eo(e),ko(e),Mo(e),Oo(e,i),Po(e),xo(e,i);break;default:r("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var $o="4.14.7",Uo={},Bo=Wi,Vo=qi,Fo=Object.keys||function(e){return Bo(e,Vo)},jo=P,Wo=nr,qo=ir,Go=cr,Ho=pe,zo=Fo;Uo.f=jo&&!Wo?Object.defineProperties:function(e,t){Go(e);for(var r,i=Ho(t),n=zo(t),s=n.length,o=0;s>o;)qo.f(e,r=n[o++],i[r]);return e};var Jo,Yo=Te("document","documentElement"),Ko=cr,Qo=Uo,Xo=qi,Zo=Fr,ea=Yo,ta=Gt,ra=Vr("IE_PROTO"),ia=function(){},na=function(e){return"<script>"+e+"<\/script>"},sa=function(e){e.write(na("")),e.close();var t=e.parentWindow.Object;return e=null,t},oa=function(){try{Jo=new ActiveXObject("htmlfile")}catch(e){}var e,t;oa="undefined"!=typeof document?document.domain&&Jo?sa(Jo):((t=ta("iframe")).style.display="none",ea.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(na("document.F=Object")),e.close(),e.F):sa(Jo);for(var r=Xo.length;r--;)delete oa.prototype[Xo[r]];return oa()};Zo[ra]=!0;var aa=Object.create||function(e,t){var r;return null!==e?(ia.prototype=Ko(e),r=new ia,ia.prototype=null,r[ra]=e):r=oa(),void 0===t?r:Qo.f(r,t)},ca=Ot,ua=aa,da=ir.f,la=ca("unscopables"),ha=Array.prototype;null==ha[la]&&da(ha,la,{configurable:!0,value:ua(null)});var pa,ma,fa,ga=function(e){ha[la][e]=!0},va={},ya=!O((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),_a=ft,ba=ve,Sa=ht,Ia=ya,Ea=Vr("IE_PROTO"),Ta=Object,Ra=Ta.prototype,wa=Ia?Ta.getPrototypeOf:function(e){var t=Sa(e);if(_a(t,Ea))return t[Ea];var r=t.constructor;return ba(r)&&t instanceof r?r.prototype:t instanceof Ta?Ra:null},Aa=O,ka=ve,Ca=be,Ma=wa,Oa=yi,Pa=Ot("iterator"),La=!1;[].keys&&("next"in(fa=[].keys())?(ma=Ma(Ma(fa)))!==Object.prototype&&(pa=ma):La=!0),(!Ca(pa)||Aa((function(){var e={};return pa[Pa].call(e)!==e})))&&(pa={}),ka(pa[Pa])||Oa(pa,Pa,(function(){return this}));var xa={IteratorPrototype:pa,BUGGY_SAFARI_ITERATORS:La},Da=ir.f,Na=ft,$a=Ot("toStringTag"),Ua=function(e,t,r){e&&!r&&(e=e.prototype),e&&!Na(e,$a)&&Da(e,$a,{configurable:!0,value:t})},Ba=xa.IteratorPrototype,Va=aa,Fa=W,ja=Ua,Wa=va,qa=function(){return this},Ga=function(e,t,r,i){var n=t+" Iterator";return e.prototype=Va(Ba,{next:Fa(+!i,r)}),ja(e,n,!1),Wa[n]=qa,e},Ha=ve,za=String,Ja=TypeError,Ya=te,Ka=cr,Qa=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,r={};try{(e=Ya(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(r,[]),t=r instanceof Array}catch(e){}return function(r,i){return Ka(r),function(e){if("object"==typeof e||Ha(e))return e;throw Ja("Can't set "+za(e)+" as a prototype")}(i),t?e(r,i):r.__proto__=i,r}}():void 0),Xa=Sn,Za=N,ec=ve,tc=Ga,rc=wa,ic=Qa,nc=Ua,sc=_r,oc=yi,ac=va,cc=wr.PROPER,uc=wr.CONFIGURABLE,dc=xa.IteratorPrototype,lc=xa.BUGGY_SAFARI_ITERATORS,hc=Ot("iterator"),pc="values",mc="entries",fc=function(){return this},gc=function(e,t,r,i,n,s,o){tc(r,t,i);var a,c,u,d=function(e){if(e===n&&f)return f;if(!lc&&e in p)return p[e];switch(e){case"keys":case pc:case mc:return function(){return new r(this,e)}}return function(){return new r(this)}},l=t+" Iterator",h=!1,p=e.prototype,m=p[hc]||p["@@iterator"]||n&&p[n],f=!lc&&m||d(n),g="Array"==t&&p.entries||m;if(g&&(a=rc(g.call(new e)))!==Object.prototype&&a.next&&(rc(a)!==dc&&(ic?ic(a,dc):ec(a[hc])||oc(a,hc,fc)),nc(a,l,!0)),cc&&n==pc&&m&&m.name!==pc&&(uc?sc(p,"name",pc):(h=!0,f=function(){return Za(m,this)})),n)if(c={values:d(pc),keys:s?f:d("keys"),entries:d(mc)},o)for(u in c)(lc||h||!(u in p))&&oc(p,u,c[u]);else Xa({target:t,proto:!0,forced:lc||h},c);return p[hc]!==f&&oc(p,hc,f,{name:n}),ac[t]=f,c},vc=function(e,t){return{value:e,done:t}},yc=pe,_c=ga,bc=va,Sc=ti,Ic=ir.f,Ec=gc,Tc=vc,Rc=P,wc="Array Iterator",Ac=Sc.set,kc=Sc.getterFor(wc),Cc=Ec(Array,"Array",(function(e,t){Ac(this,{type:wc,target:yc(e),index:0,kind:t})}),(function(){var e=kc(this),t=e.target,r=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,Tc(void 0,!0)):Tc("keys"==r?i:"values"==r?t[i]:[i,t[i]],!1)}),"values"),Mc=bc.Arguments=bc.Array;if(_c("keys"),_c("values"),_c("entries"),Rc&&"values"!==Mc.name)try{Ic(Mc,"name",{value:"values"})}catch(e){}var Oc={exports:{}},Pc={},Lc=Ft,xc=ir,Dc=W,Nc=function(e,t,r){var i=Lc(t);i in e?xc.f(e,i,Dc(0,r)):e[i]=r},$c=Ai,Uc=Pi,Bc=Nc,Vc=Array,Fc=Math.max,jc=function(e,t,r){for(var i=Uc(e),n=$c(t,i),s=$c(void 0===r?i:r,i),o=Vc(Fc(s-n,0)),a=0;n<s;n++,a++)Bc(o,a,e[n]);return o.length=a,o},Wc=X,qc=pe,Gc=_i.f,Hc=jc,zc="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];Pc.f=function(e){return zc&&"Window"==Wc(e)?function(e){try{return Gc(e)}catch(e){return Hc(zc)}}(e):Gc(qc(e))};var Jc=O((function(){if("function"==typeof ArrayBuffer){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}})),Yc=O,Kc=be,Qc=X,Xc=Jc,Zc=Object.isExtensible,eu=Yc((function(){Zc(1)}))||Xc?function(e){return!!Kc(e)&&(!Xc||"ArrayBuffer"!=Qc(e))&&(!Zc||Zc(e))}:Zc,tu=!O((function(){return Object.isExtensible(Object.preventExtensions({}))})),ru=Sn,iu=te,nu=Fr,su=be,ou=ft,au=ir.f,cu=_i,uu=Pc,du=eu,lu=tu,hu=!1,pu=bt("meta"),mu=0,fu=function(e){au(e,pu,{value:{objectID:"O"+mu++,weakData:{}}})},gu=Oc.exports={enable:function(){gu.enable=function(){},hu=!0;var e=cu.f,t=iu([].splice),r={};r[pu]=1,e(r).length&&(cu.f=function(r){for(var i=e(r),n=0,s=i.length;n<s;n++)if(i[n]===pu){t(i,n,1);break}return i},ru({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:uu.f}))},fastKey:function(e,t){if(!su(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!ou(e,pu)){if(!du(e))return"F";if(!t)return"E";fu(e)}return e[pu].objectID},getWeakData:function(e,t){if(!ou(e,pu)){if(!du(e))return!0;if(!t)return!1;fu(e)}return e[pu].weakData},onFreeze:function(e){return lu&&hu&&du(e)&&!ou(e,pu)&&fu(e),e}};nu[pu]=!0;var vu=va,yu=Ot("iterator"),_u=Array.prototype,bu=function(e){return void 0!==e&&(vu.Array===e||_u[yu]===e)},Su=Nn,Iu=Qe,Eu=ae,Tu=va,Ru=Ot("iterator"),wu=function(e){if(!Eu(e))return Iu(e,Ru)||Iu(e,"@@iterator")||Tu[Su(e)]},Au=N,ku=Je,Cu=cr,Mu=qe,Ou=wu,Pu=TypeError,Lu=function(e,t){var r=arguments.length<2?Ou(e):t;if(ku(r))return Cu(Au(r,e));throw Pu(Mu(e)+" is not iterable")},xu=N,Du=cr,Nu=Qe,$u=function(e,t,r){var i,n;Du(e);try{if(!(i=Nu(e,"return"))){if("throw"===t)throw r;return r}i=xu(i,e)}catch(e){n=!0,i=e}if("throw"===t)throw r;if(n)throw i;return Du(i),r},Uu=Rn,Bu=N,Vu=cr,Fu=qe,ju=bu,Wu=Pi,qu=Re,Gu=Lu,Hu=wu,zu=$u,Ju=TypeError,Yu=function(e,t){this.stopped=e,this.result=t},Ku=Yu.prototype,Qu=function(e,t,r){var i,n,s,o,a,c,u,d=r&&r.that,l=!(!r||!r.AS_ENTRIES),h=!(!r||!r.IS_RECORD),p=!(!r||!r.IS_ITERATOR),m=!(!r||!r.INTERRUPTED),f=Uu(t,d),g=function(e){return i&&zu(i,"normal",e),new Yu(!0,e)},v=function(e){return l?(Vu(e),m?f(e[0],e[1],g):f(e[0],e[1])):m?f(e,g):f(e)};if(h)i=e.iterator;else if(p)i=e;else{if(!(n=Hu(e)))throw Ju(Fu(e)+" is not iterable");if(ju(n)){for(s=0,o=Wu(e);o>s;s++)if((a=v(e[s]))&&qu(Ku,a))return a;return new Yu(!1)}i=Gu(e,n)}for(c=h?e.next:i.next;!(u=Bu(c,i)).done;){try{a=v(u.value)}catch(e){zu(i,"throw",e)}if("object"==typeof a&&a&&qu(Ku,a))return a}return new Yu(!1)},Xu=Re,Zu=TypeError,ed=function(e,t){if(Xu(t,e))return e;throw Zu("Incorrect invocation")},td=Ot("iterator"),rd=!1;try{var id=0,nd={next:function(){return{done:!!id++}},return:function(){rd=!0}};nd[td]=function(){return this},Array.from(nd,(function(){throw 2}))}catch(e){}var sd=function(e,t){if(!t&&!rd)return!1;var r=!1;try{var i={};i[td]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(e){}return r},od=ve,ad=be,cd=Qa,ud=function(e,t,r){var i,n;return cd&&od(i=t.constructor)&&i!==r&&ad(n=i.prototype)&&n!==r.prototype&&cd(e,n),e},dd=Sn,ld=C,hd=te,pd=pn,md=yi,fd=Oc.exports,gd=Qu,vd=ed,yd=ve,_d=ae,bd=be,Sd=O,Id=sd,Ed=Ua,Td=ud,Rd=function(e,t,r){var i=-1!==e.indexOf("Map"),n=-1!==e.indexOf("Weak"),s=i?"set":"add",o=ld[e],a=o&&o.prototype,c=o,u={},d=function(e){var t=hd(a[e]);md(a,e,"add"==e?function(e){return t(this,0===e?0:e),this}:"delete"==e?function(e){return!(n&&!bd(e))&&t(this,0===e?0:e)}:"get"==e?function(e){return n&&!bd(e)?void 0:t(this,0===e?0:e)}:"has"==e?function(e){return!(n&&!bd(e))&&t(this,0===e?0:e)}:function(e,r){return t(this,0===e?0:e,r),this})};if(pd(e,!yd(o)||!(n||a.forEach&&!Sd((function(){(new o).entries().next()})))))c=r.getConstructor(t,e,i,s),fd.enable();else if(pd(e,!0)){var l=new c,h=l[s](n?{}:-0,1)!=l,p=Sd((function(){l.has(1)})),m=Id((function(e){new o(e)})),f=!n&&Sd((function(){for(var e=new o,t=5;t--;)e[s](t,t);return!e.has(-0)}));m||((c=t((function(e,t){vd(e,a);var r=Td(new o,e,c);return _d(t)||gd(t,r[s],{that:r,AS_ENTRIES:i}),r}))).prototype=a,a.constructor=c),(p||f)&&(d("delete"),d("has"),i&&d("get")),(f||h)&&d(s),n&&a.clear&&delete a.clear}return u[e]=c,dd({global:!0,constructor:!0,forced:c!=o},u),Ed(c,e),n||r.setStrong(c,e,i),c},wd=yi,Ad=function(e,t,r){for(var i in t)wd(e,i,t[i],r);return e},kd=Te,Cd=ir,Md=P,Od=Ot("species"),Pd=function(e){var t=kd(e),r=Cd.f;Md&&t&&!t[Od]&&r(t,Od,{configurable:!0,get:function(){return this}})},Ld=ir.f,xd=aa,Dd=Ad,Nd=Rn,$d=ed,Ud=ae,Bd=Qu,Vd=gc,Fd=vc,jd=Pd,Wd=P,qd=Oc.exports.fastKey,Gd=ti.set,Hd=ti.getterFor,zd={getConstructor:function(e,t,r,i){var n=e((function(e,n){$d(e,s),Gd(e,{type:t,index:xd(null),first:void 0,last:void 0,size:0}),Wd||(e.size=0),Ud(n)||Bd(n,e[i],{that:e,AS_ENTRIES:r})})),s=n.prototype,o=Hd(t),a=function(e,t,r){var i,n,s=o(e),a=c(e,t);return a?a.value=r:(s.last=a={index:n=qd(t,!0),key:t,value:r,previous:i=s.last,next:void 0,removed:!1},s.first||(s.first=a),i&&(i.next=a),Wd?s.size++:e.size++,"F"!==n&&(s.index[n]=a)),e},c=function(e,t){var r,i=o(e),n=qd(t);if("F"!==n)return i.index[n];for(r=i.first;r;r=r.next)if(r.key==t)return r};return Dd(s,{clear:function(){for(var e=o(this),t=e.index,r=e.first;r;)r.removed=!0,r.previous&&(r.previous=r.previous.next=void 0),delete t[r.index],r=r.next;e.first=e.last=void 0,Wd?e.size=0:this.size=0},delete:function(e){var t=this,r=o(t),i=c(t,e);if(i){var n=i.next,s=i.previous;delete r.index[i.index],i.removed=!0,s&&(s.next=n),n&&(n.previous=s),r.first==i&&(r.first=n),r.last==i&&(r.last=s),Wd?r.size--:t.size--}return!!i},forEach:function(e){for(var t,r=o(this),i=Nd(e,arguments.length>1?arguments[1]:void 0);t=t?t.next:r.first;)for(i(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!c(this,e)}}),Dd(s,r?{get:function(e){var t=c(this,e);return t&&t.value},set:function(e,t){return a(this,0===e?0:e,t)}}:{add:function(e){return a(this,e=0===e?0:e,e)}}),Wd&&Ld(s,"size",{get:function(){return o(this).size}}),n},setStrong:function(e,t,r){var i=t+" Iterator",n=Hd(t),s=Hd(i);Vd(e,t,(function(e,t){Gd(this,{type:i,target:e,state:n(e),kind:t,last:void 0})}),(function(){for(var e=s(this),t=e.kind,r=e.last;r&&r.removed;)r=r.previous;return e.target&&(e.last=r=r?r.next:e.state.first)?Fd("keys"==t?r.key:"values"==t?r.value:[r.key,r.value],!1):(e.target=void 0,Fd(void 0,!0))}),r?"entries":"values",!r,!0),jd(t)}};Rd("Set",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),zd);var Jd=Nn,Yd=String,Kd=function(e){if("Symbol"===Jd(e))throw TypeError("Cannot convert a Symbol value to a string");return Yd(e)},Qd=te,Xd=Ei,Zd=Kd,el=de,tl=Qd("".charAt),rl=Qd("".charCodeAt),il=Qd("".slice),nl=function(e){return function(t,r){var i,n,s=Zd(el(t)),o=Xd(r),a=s.length;return o<0||o>=a?e?"":void 0:(i=rl(s,o))<55296||i>56319||o+1===a||(n=rl(s,o+1))<56320||n>57343?e?tl(s,o):i:e?il(s,o,o+2):n-56320+(i-55296<<10)+65536}},sl={codeAt:nl(!1),charAt:nl(!0)},ol=sl.charAt,al=Kd,cl=ti,ul=gc,dl=vc,ll="String Iterator",hl=cl.set,pl=cl.getterFor(ll);ul(String,"String",(function(e){hl(this,{type:ll,string:al(e),index:0})}),(function(){var e,t=pl(this),r=t.string,i=t.index;return i>=r.length?dl(void 0,!0):(e=ol(r,i),t.index+=e.length,dl(e,!1))}));var ml={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},fl=Gt("span").classList,gl=fl&&fl.constructor&&fl.constructor.prototype,vl=gl===Object.prototype?void 0:gl,yl=C,_l=ml,bl=vl,Sl=Cc,Il=_r,El=Ot,Tl=El("iterator"),Rl=El("toStringTag"),wl=Sl.values,Al=function(e,t){if(e){if(e[Tl]!==wl)try{Il(e,Tl,wl)}catch(t){e[Tl]=wl}if(e[Rl]||Il(e,Rl,t),_l[t])for(var r in Sl)if(e[r]!==Sl[r])try{Il(e,r,Sl[r])}catch(t){e[r]=Sl[r]}}};for(var kl in _l)Al(yl[kl]&&yl[kl].prototype,kl);Al(bl,"DOMTokenList");var Cl=L,Ml=Function.prototype,Ol=Ml.apply,Pl=Ml.call,Ll="object"==typeof Reflect&&Reflect.apply||(Cl?Pl.bind(Ol):function(){return Pl.apply(Ol,arguments)}),xl=te([].slice),Dl=TypeError,Nl=function(e,t){if(e<t)throw Dl("Not enough arguments");return e},$l=C,Ul=Ll,Bl=ve,Vl=xl,Fl=Nl,jl=/MSIE .\./.test(we),Wl=$l.Function,ql=function(e){return jl?function(t,r){var i=Fl(arguments.length,1)>2,n=Bl(t)?t:Wl(t),s=i?Vl(arguments,2):void 0;return e(i?function(){Ul(n,this,s)}:n,r)}:e},Gl={setTimeout:ql($l.setTimeout),setInterval:ql($l.setInterval)},Hl=Gl.setInterval;Sn({global:!0,bind:!0,forced:C.setInterval!==Hl},{setInterval:Hl});var zl=Gl.setTimeout;Sn({global:!0,bind:!0,forced:C.setTimeout!==zl},{setTimeout:zl}),Rd("Map",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),zd);var Jl=P,Yl=An,Kl=TypeError,Ql=Object.getOwnPropertyDescriptor,Xl=Jl&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}(),Zl=TypeError,eh=function(e){if(e>9007199254740991)throw Zl("Maximum allowed index exceeded");return e},th=qe,rh=TypeError,ih=function(e,t){if(!delete e[t])throw rh("Cannot delete property "+th(t)+" of "+th(e))},nh=Sn,sh=ht,oh=Ai,ah=Ei,ch=Pi,uh=Xl?function(e,t){if(Yl(e)&&!Ql(e,"length").writable)throw Kl("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},dh=eh,lh=rs,hh=Nc,ph=ih,mh=ms("splice"),fh=Math.max,gh=Math.min;nh({target:"Array",proto:!0,forced:!mh},{splice:function(e,t){var r,i,n,s,o,a,c=sh(this),u=ch(c),d=oh(e,u),l=arguments.length;for(0===l?r=i=0:1===l?(r=0,i=u-d):(r=l-2,i=gh(fh(ah(t),0),u-d)),dh(u+r-i),n=lh(c,i),s=0;s<i;s++)(o=d+s)in c&&hh(n,s,c[o]);if(n.length=i,r<i){for(s=d;s<u-i;s++)a=s+r,(o=s+i)in c?c[a]=c[o]:ph(c,a);for(s=u;s>u-i+r;s--)ph(c,s-1)}else if(r>i)for(s=u-i;s>d;s--)a=s+r-1,(o=s+i-1)in c?c[a]=c[o]:ph(c,a);for(s=0;s<r;s++)c[s+d]=arguments[s+2];return uh(c,u-i+r),n}});var vh=O,yh=function(e,t){var r=[][e];return!!r&&vh((function(){r.call(null,t||function(){return 1},1)}))},_h=ds.forEach,bh=yh("forEach")?[].forEach:function(e){return _h(this,e,arguments.length>1?arguments[1]:void 0)};Sn({target:"Array",proto:!0,forced:[].forEach!=bh},{forEach:bh});var Sh=C,Ih=ml,Eh=vl,Th=bh,Rh=_r,wh=function(e){if(e&&e.forEach!==Th)try{Rh(e,"forEach",Th)}catch(t){e.forEach=Th}};for(var Ah in Ih)Ih[Ah]&&wh(Sh[Ah]&&Sh[Ah].prototype);wh(Eh);var kh=Sn,Ch=oe,Mh=pe,Oh=yh,Ph=te([].join),Lh=Ch!=Object,xh=Oh("join",",");kh({target:"Array",proto:!0,forced:Lh||!xh},{join:function(e){return Ph(Mh(this),void 0===e?",":e)}});var Dh=Sn,Nh=O,$h=An,Uh=be,Bh=ht,Vh=Pi,Fh=eh,jh=Nc,Wh=rs,qh=ms,Gh=Le,Hh=Ot("isConcatSpreadable"),zh=Gh>=51||!Nh((function(){var e=[];return e[Hh]=!1,e.concat()[0]!==e})),Jh=qh("concat"),Yh=function(e){if(!Uh(e))return!1;var t=e[Hh];return void 0!==t?!!t:$h(e)};Dh({target:"Array",proto:!0,arity:1,forced:!zh||!Jh},{concat:function(e){var t,r,i,n,s,o=Bh(this),a=Wh(o,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(Yh(s=-1===t?o:arguments[t]))for(n=Vh(s),Fh(c+n),r=0;r<n;r++,c++)r in s&&jh(a,c,s[r]);else Fh(c+1),jh(a,c++,s);return a.length=c,a}});var Kh=te,Qh=yi,Xh=Date.prototype,Zh="Invalid Date",ep=Kh(Xh.toString),tp=Kh(Xh.getTime);String(new Date(NaN))!=Zh&&Qh(Xh,"toString",(function(){var e=tp(this);return e==e?ep(this):Zh}));var rp=Ei,ip=Kd,np=de,sp=RangeError,op=function(e){var t=ip(np(this)),r="",i=rp(e);if(i<0||1/0==i)throw sp("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))1&i&&(r+=t);return r},ap=te,cp=Mi,up=Kd,dp=de,lp=ap(op),hp=ap("".slice),pp=Math.ceil,mp=function(e){return function(t,r,i){var n,s,o=up(dp(t)),a=cp(r),c=o.length,u=void 0===i?" ":up(i);return a<=c||""==u?o:((s=lp(u,pp((n=a-c)/u.length))).length>n&&(s=hp(s,0,n)),e?o+s:s+o)}},fp={start:mp(!1),end:mp(!0)},gp=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(we),vp=fp.start;Sn({target:"String",proto:!0,forced:gp},{padStart:function(e){return vp(this,e,arguments.length>1?arguments[1]:void 0)}});var yp=cr,_p=function(){var e=yp(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},bp=O,Sp=C.RegExp,Ip=bp((function(){var e=Sp("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),Ep=Ip||bp((function(){return!Sp("a","y").sticky})),Tp={BROKEN_CARET:Ip||bp((function(){var e=Sp("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),MISSED_STICKY:Ep,UNSUPPORTED_Y:Ip},Rp=O,wp=C.RegExp,Ap=Rp((function(){var e=wp(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),kp=O,Cp=C.RegExp,Mp=kp((function(){var e=Cp("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Op=N,Pp=te,Lp=Kd,xp=_p,Dp=Tp,Np=rt.exports,$p=aa,Up=ti.get,Bp=Ap,Vp=Mp,Fp=Np("native-string-replace",String.prototype.replace),jp=RegExp.prototype.exec,Wp=jp,qp=Pp("".charAt),Gp=Pp("".indexOf),Hp=Pp("".replace),zp=Pp("".slice),Jp=function(){var e=/a/,t=/b*/g;return Op(jp,e,"a"),Op(jp,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Yp=Dp.BROKEN_CARET,Kp=void 0!==/()??/.exec("")[1];(Jp||Kp||Yp||Bp||Vp)&&(Wp=function(e){var t,r,i,n,s,o,a,c=this,u=Up(c),d=Lp(e),l=u.raw;if(l)return l.lastIndex=c.lastIndex,t=Op(Wp,l,d),c.lastIndex=l.lastIndex,t;var h=u.groups,p=Yp&&c.sticky,m=Op(xp,c),f=c.source,g=0,v=d;if(p&&(m=Hp(m,"y",""),-1===Gp(m,"g")&&(m+="g"),v=zp(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==qp(d,c.lastIndex-1))&&(f="(?: "+f+")",v=" "+v,g++),r=new RegExp("^(?:"+f+")",m)),Kp&&(r=new RegExp("^"+f+"$(?!\\s)",m)),Jp&&(i=c.lastIndex),n=Op(jp,p?r:c,v),p?n?(n.input=zp(n.input,g),n[0]=zp(n[0],g),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Jp&&n&&(c.lastIndex=c.global?n.index+n[0].length:i),Kp&&n&&n.length>1&&Op(Fp,n[0],r,(function(){for(s=1;s<arguments.length-2;s++)void 0===arguments[s]&&(n[s]=void 0)})),n&&h)for(n.groups=o=$p(null),s=0;s<h.length;s++)o[(a=h[s])[0]]=n[a[1]];return n});var Qp=Wp;Sn({target:"RegExp",proto:!0,forced:/./.exec!==Qp},{exec:Qp});var Xp=te,Zp=yi,em=Qp,tm=O,rm=Ot,im=_r,nm=rm("species"),sm=RegExp.prototype,om=function(e,t,r,i){var n=rm(e),s=!tm((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),o=s&&!tm((function(){var t=!1,r=/a/;return"split"===e&&((r={}).constructor={},r.constructor[nm]=function(){return r},r.flags="",r[n]=/./[n]),r.exec=function(){return t=!0,null},r[n](""),!t}));if(!s||!o||r){var a=Xp(/./[n]),c=t(n,""[e],(function(e,t,r,i,n){var o=Xp(e),c=t.exec;return c===em||c===sm.exec?s&&!n?{done:!0,value:a(t,r,i)}:{done:!0,value:o(r,t,i)}:{done:!1}}));Zp(String.prototype,e,c[0]),Zp(sm,n,c[1])}i&&im(sm[n],"sham",!0)},am=sl.charAt,cm=function(e,t,r){return t+(r?am(e,t).length:1)},um=te,dm=ht,lm=Math.floor,hm=um("".charAt),pm=um("".replace),mm=um("".slice),fm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,gm=/\$([$&'`]|\d{1,2})/g,vm=N,ym=cr,_m=ve,bm=X,Sm=Qp,Im=TypeError,Em=function(e,t){var r=e.exec;if(_m(r)){var i=vm(r,e,t);return null!==i&&ym(i),i}if("RegExp"===bm(e))return vm(Sm,e,t);throw Im("RegExp#exec called on incompatible receiver")},Tm=Ll,Rm=N,wm=te,Am=om,km=O,Cm=cr,Mm=ve,Om=ae,Pm=Ei,Lm=Mi,xm=Kd,Dm=de,Nm=cm,$m=Qe,Um=function(e,t,r,i,n,s){var o=r+e.length,a=i.length,c=gm;return void 0!==n&&(n=dm(n),c=fm),pm(s,c,(function(s,c){var u;switch(hm(c,0)){case"$":return"$";case"&":return e;case"`":return mm(t,0,r);case"'":return mm(t,o);case"<":u=n[mm(c,1,-1)];break;default:var d=+c;if(0===d)return s;if(d>a){var l=lm(d/10);return 0===l?s:l<=a?void 0===i[l-1]?hm(c,1):i[l-1]+hm(c,1):s}u=i[d-1]}return void 0===u?"":u}))},Bm=Em,Vm=Ot("replace"),Fm=Math.max,jm=Math.min,Wm=wm([].concat),qm=wm([].push),Gm=wm("".indexOf),Hm=wm("".slice),zm="$0"==="a".replace(/./,"$0"),Jm=!!/./[Vm]&&""===/./[Vm]("a","$0"),Ym=!km((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Am("replace",(function(e,t,r){var i=Jm?"$":"$0";return[function(e,r){var i=Dm(this),n=Om(e)?void 0:$m(e,Vm);return n?Rm(n,e,i,r):Rm(t,xm(i),e,r)},function(e,n){var s=Cm(this),o=xm(e);if("string"==typeof n&&-1===Gm(n,i)&&-1===Gm(n,"$<")){var a=r(t,s,o,n);if(a.done)return a.value}var c=Mm(n);c||(n=xm(n));var u=s.global;if(u){var d=s.unicode;s.lastIndex=0}for(var l=[];;){var h=Bm(s,o);if(null===h)break;if(qm(l,h),!u)break;""===xm(h[0])&&(s.lastIndex=Nm(o,Lm(s.lastIndex),d))}for(var p,m="",f=0,g=0;g<l.length;g++){for(var v=xm((h=l[g])[0]),y=Fm(jm(Pm(h.index),o.length),0),_=[],b=1;b<h.length;b++)qm(_,void 0===(p=h[b])?p:String(p));var S=h.groups;if(c){var I=Wm([v],_,y,o);void 0!==S&&qm(I,S);var E=xm(Tm(n,void 0,I))}else E=Um(v,o,y,_,S,n);y>=f&&(m+=Hm(o,f,y)+E,f=y+v.length)}return m+Hm(o,f)}]}),!Ym||!zm||Jm);var Km=N,Qm=ft,Xm=Re,Zm=_p,ef=RegExp.prototype,tf=function(e){var t=e.flags;return void 0!==t||"flags"in ef||Qm(e,"flags")||!Xm(ef,e)?t:Km(Zm,e)},rf=wr.PROPER,nf=yi,sf=cr,of=Kd,af=O,cf=tf,uf="toString",df=RegExp.prototype.toString,lf=af((function(){return"/a/b"!=df.call({source:"a",flags:"b"})})),hf=rf&&df.name!=uf;(lf||hf)&&nf(RegExp.prototype,uf,(function(){var e=sf(this);return"/"+of(e.source)+"/"+of(cf(e))}),{unsafe:!0});var pf=O,mf=Ot("iterator"),ff=!pf((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,r="";return e.pathname="c%20d",t.forEach((function(e,i){t.delete("b"),r+=i+e})),!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[mf]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==r||"x"!==new URL("http://x",void 0).host})),gf=jc,vf=Math.floor,yf=function(e,t){var r=e.length,i=vf(r/2);return r<8?_f(e,t):bf(e,yf(gf(e,0,i),t),yf(gf(e,i),t),t)},_f=function(e,t){for(var r,i,n=e.length,s=1;s<n;){for(i=s,r=e[s];i&&t(e[i-1],r)>0;)e[i]=e[--i];i!==s++&&(e[i]=r)}return e},bf=function(e,t,r,i){for(var n=t.length,s=r.length,o=0,a=0;o<n||a<s;)e[o+a]=o<n&&a<s?i(t[o],r[a])<=0?t[o++]:r[a++]:o<n?t[o++]:r[a++];return e},Sf=yf,If=Sn,Ef=C,Tf=N,Rf=te,wf=P,Af=ff,kf=yi,Cf=Ad,Mf=Ua,Of=Ga,Pf=ti,Lf=ed,xf=ve,Df=ft,Nf=Rn,$f=Nn,Uf=cr,Bf=be,Vf=Kd,Ff=aa,jf=W,Wf=Lu,qf=wu,Gf=Nl,Hf=Sf,zf=Ot("iterator"),Jf="URLSearchParams",Yf="URLSearchParamsIterator",Kf=Pf.set,Qf=Pf.getterFor(Jf),Xf=Pf.getterFor(Yf),Zf=Object.getOwnPropertyDescriptor,eg=function(e){if(!wf)return Ef[e];var t=Zf(Ef,e);return t&&t.value},tg=eg("fetch"),rg=eg("Request"),ig=eg("Headers"),ng=rg&&rg.prototype,sg=ig&&ig.prototype,og=Ef.RegExp,ag=Ef.TypeError,cg=Ef.decodeURIComponent,ug=Ef.encodeURIComponent,dg=Rf("".charAt),lg=Rf([].join),hg=Rf([].push),pg=Rf("".replace),mg=Rf([].shift),fg=Rf([].splice),gg=Rf("".split),vg=Rf("".slice),yg=/\+/g,_g=Array(4),bg=function(e){return _g[e-1]||(_g[e-1]=og("((?:%[\\da-f]{2}){"+e+"})","gi"))},Sg=function(e){try{return cg(e)}catch(t){return e}},Ig=function(e){var t=pg(e,yg," "),r=4;try{return cg(t)}catch(e){for(;r;)t=pg(t,bg(r--),Sg);return t}},Eg=/[!'()~]|%20/g,Tg={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Rg=function(e){return Tg[e]},wg=function(e){return pg(ug(e),Eg,Rg)},Ag=Of((function(e,t){Kf(this,{type:Yf,iterator:Wf(Qf(e).entries),kind:t})}),"Iterator",(function(){var e=Xf(this),t=e.kind,r=e.iterator.next(),i=r.value;return r.done||(r.value="keys"===t?i.key:"values"===t?i.value:[i.key,i.value]),r}),!0),kg=function(e){this.entries=[],this.url=null,void 0!==e&&(Bf(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===dg(e,0)?vg(e,1):e:Vf(e)))};kg.prototype={type:Jf,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,r,i,n,s,o,a,c=qf(e);if(c)for(r=(t=Wf(e,c)).next;!(i=Tf(r,t)).done;){if(s=(n=Wf(Uf(i.value))).next,(o=Tf(s,n)).done||(a=Tf(s,n)).done||!Tf(s,n).done)throw ag("Expected sequence with length 2");hg(this.entries,{key:Vf(o.value),value:Vf(a.value)})}else for(var u in e)Df(e,u)&&hg(this.entries,{key:u,value:Vf(e[u])})},parseQuery:function(e){if(e)for(var t,r,i=gg(e,"&"),n=0;n<i.length;)(t=i[n++]).length&&(r=gg(t,"="),hg(this.entries,{key:Ig(mg(r)),value:Ig(lg(r,"="))}))},serialize:function(){for(var e,t=this.entries,r=[],i=0;i<t.length;)e=t[i++],hg(r,wg(e.key)+"="+wg(e.value));return lg(r,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Cg=function(){Lf(this,Mg),Kf(this,new kg(arguments.length>0?arguments[0]:void 0))},Mg=Cg.prototype;if(Cf(Mg,{append:function(e,t){Gf(arguments.length,2);var r=Qf(this);hg(r.entries,{key:Vf(e),value:Vf(t)}),r.updateURL()},delete:function(e){Gf(arguments.length,1);for(var t=Qf(this),r=t.entries,i=Vf(e),n=0;n<r.length;)r[n].key===i?fg(r,n,1):n++;t.updateURL()},get:function(e){Gf(arguments.length,1);for(var t=Qf(this).entries,r=Vf(e),i=0;i<t.length;i++)if(t[i].key===r)return t[i].value;return null},getAll:function(e){Gf(arguments.length,1);for(var t=Qf(this).entries,r=Vf(e),i=[],n=0;n<t.length;n++)t[n].key===r&&hg(i,t[n].value);return i},has:function(e){Gf(arguments.length,1);for(var t=Qf(this).entries,r=Vf(e),i=0;i<t.length;)if(t[i++].key===r)return!0;return!1},set:function(e,t){Gf(arguments.length,1);for(var r,i=Qf(this),n=i.entries,s=!1,o=Vf(e),a=Vf(t),c=0;c<n.length;c++)(r=n[c]).key===o&&(s?fg(n,c--,1):(s=!0,r.value=a));s||hg(n,{key:o,value:a}),i.updateURL()},sort:function(){var e=Qf(this);Hf(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,r=Qf(this).entries,i=Nf(e,arguments.length>1?arguments[1]:void 0),n=0;n<r.length;)i((t=r[n++]).value,t.key,this)},keys:function(){return new Ag(this,"keys")},values:function(){return new Ag(this,"values")},entries:function(){return new Ag(this,"entries")}},{enumerable:!0}),kf(Mg,zf,Mg.entries,{name:"entries"}),kf(Mg,"toString",(function(){return Qf(this).serialize()}),{enumerable:!0}),Mf(Cg,Jf),If({global:!0,constructor:!0,forced:!Af},{URLSearchParams:Cg}),!Af&&xf(ig)){var Og=Rf(sg.has),Pg=Rf(sg.set),Lg=function(e){if(Bf(e)){var t,r=e.body;if($f(r)===Jf)return t=e.headers?new ig(e.headers):new ig,Og(t,"content-type")||Pg(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),Ff(e,{body:jf(0,Vf(r)),headers:jf(0,t)})}return e};if(xf(tg)&&If({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return tg(e,arguments.length>1?Lg(arguments[1]):{})}}),xf(rg)){var xg=function(e){return Lf(this,ng),new rg(e,arguments.length>1?Lg(arguments[1]):{})};ng.constructor=xg,xg.prototype=ng,If({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:xg})}}var Dg={URLSearchParams:Cg,getState:Qf},Ng=Object.is||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t},$g=N,Ug=cr,Bg=ae,Vg=de,Fg=Ng,jg=Kd,Wg=Qe,qg=Em;om("search",(function(e,t,r){return[function(t){var r=Vg(this),i=Bg(t)?void 0:Wg(t,e);return i?$g(i,t,r):new RegExp(t)[e](jg(r))},function(e){var i=Ug(this),n=jg(e),s=r(t,i,n);if(s.done)return s.value;var o=i.lastIndex;Fg(o,0)||(i.lastIndex=0);var a=qg(i,n);return Fg(i.lastIndex,o)||(i.lastIndex=o),null===a?-1:a.index}]})),(new Date).getTime();var Gg=0,Hg=function(){return(new Date).getTime()+Gg},zg=function(){var e=new Date;return e.setTime(Hg()),e.toLocaleString()},Jg=N,Yg=cr,Kg=ae,Qg=Mi,Xg=Kd,Zg=de,ev=Qe,tv=cm,rv=Em;om("match",(function(e,t,r){return[function(t){var r=Zg(this),i=Kg(t)?void 0:ev(t,e);return i?Jg(i,t,r):new RegExp(t)[e](Xg(r))},function(e){var i=Yg(this),n=Xg(e),s=r(t,i,n);if(s.done)return s.value;if(!i.global)return rv(i,n);var o=i.unicode;i.lastIndex=0;for(var a,c=[],u=0;null!==(a=rv(i,n));){var d=Xg(a[0]);c[u]=d,""===d&&(i.lastIndex=tv(n,Qg(i.lastIndex),o)),u++}return 0===u?null:c}]}));var iv=be,nv=X,sv=Ot("match"),ov=function(e){var t;return iv(e)&&(void 0!==(t=e[sv])?!!t:"RegExp"==nv(e))},av=ir.f,cv=P,uv=C,dv=te,lv=pn,hv=ud,pv=_r,mv=_i.f,fv=Re,gv=ov,vv=Kd,yv=tf,_v=Tp,bv=function(e,t,r){r in e||av(e,r,{configurable:!0,get:function(){return t[r]},set:function(e){t[r]=e}})},Sv=yi,Iv=O,Ev=ft,Tv=ti.enforce,Rv=Pd,wv=Ap,Av=Mp,kv=Ot("match"),Cv=uv.RegExp,Mv=Cv.prototype,Ov=uv.SyntaxError,Pv=dv(Mv.exec),Lv=dv("".charAt),xv=dv("".replace),Dv=dv("".indexOf),Nv=dv("".slice),$v=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Uv=/a/g,Bv=/a/g,Vv=new Cv(Uv)!==Uv,Fv=_v.MISSED_STICKY,jv=_v.UNSUPPORTED_Y;if(lv("RegExp",cv&&(!Vv||Fv||wv||Av||Iv((function(){return Bv[kv]=!1,Cv(Uv)!=Uv||Cv(Bv)==Bv||"/a/i"!=Cv(Uv,"i")}))))){for(var Wv=function(e,t){var r,i,n,s,o,a,c=fv(Mv,this),u=gv(e),d=void 0===t,l=[],h=e;if(!c&&u&&d&&e.constructor===Wv)return e;if((u||fv(Mv,e))&&(e=e.source,d&&(t=yv(h))),e=void 0===e?"":vv(e),t=void 0===t?"":vv(t),h=e,wv&&"dotAll"in Uv&&(i=!!t&&Dv(t,"s")>-1)&&(t=xv(t,/s/g,"")),r=t,Fv&&"sticky"in Uv&&(n=!!t&&Dv(t,"y")>-1)&&jv&&(t=xv(t,/y/g,"")),Av&&(e=(s=function(e){for(var t,r=e.length,i=0,n="",s=[],o={},a=!1,c=!1,u=0,d="";i<=r;i++){if("\\"===(t=Lv(e,i)))t+=Lv(e,++i);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:Pv($v,Nv(e,i+1))&&(i+=2,c=!0),n+=t,u++;continue;case">"===t&&c:if(""===d||Ev(o,d))throw new Ov("Invalid capture group name");o[d]=!0,s[s.length]=[d,u],c=!1,d="";continue}c?d+=t:n+=t}return[n,s]}(e))[0],l=s[1]),o=hv(Cv(e,t),c?this:Mv,Wv),(i||n||l.length)&&(a=Tv(o),i&&(a.dotAll=!0,a.raw=Wv(function(e){for(var t,r=e.length,i=0,n="",s=!1;i<=r;i++)"\\"!==(t=Lv(e,i))?s||"."!==t?("["===t?s=!0:"]"===t&&(s=!1),n+=t):n+="[\\s\\S]":n+=t+Lv(e,++i);return n}(e),r)),n&&(a.sticky=!0),l.length&&(a.groups=l)),e!==h)try{pv(o,"source",""===h?"(?:)":h)}catch(e){}return o},qv=mv(Cv),Gv=0;qv.length>Gv;)bv(Wv,Cv,qv[Gv++]);Mv.constructor=Wv,Wv.prototype=Mv,Sv(uv,"RegExp",Wv,{constructor:!0})}Rv("RegExp");var Hv=te(1..valueOf),zv="\t\n\v\f\r                 \u2028\u2029\ufeff",Jv=de,Yv=Kd,Kv=te("".replace),Qv="[\t\n\v\f\r                 \u2028\u2029\ufeff]",Xv=RegExp("^"+Qv+Qv+"*"),Zv=RegExp(Qv+Qv+"*$"),ey=function(e){return function(t){var r=Yv(Jv(t));return 1&e&&(r=Kv(r,Xv,"")),2&e&&(r=Kv(r,Zv,"")),r}},ty={start:ey(1),end:ey(2),trim:ey(3)},ry=P,iy=C,ny=te,sy=pn,oy=yi,ay=ft,cy=ud,uy=Re,dy=je,ly=Ut,hy=O,py=_i.f,my=M.f,fy=ir.f,gy=Hv,vy=ty.trim,yy=iy.Number,_y=yy.prototype,by=iy.TypeError,Sy=ny("".slice),Iy=ny("".charCodeAt),Ey=function(e){var t=ly(e,"number");return"bigint"==typeof t?t:Ty(t)},Ty=function(e){var t,r,i,n,s,o,a,c,u=ly(e,"number");if(dy(u))throw by("Cannot convert a Symbol value to a number");if("string"==typeof u&&u.length>2)if(u=vy(u),43===(t=Iy(u,0))||45===t){if(88===(r=Iy(u,2))||120===r)return NaN}else if(48===t){switch(Iy(u,1)){case 66:case 98:i=2,n=49;break;case 79:case 111:i=8,n=55;break;default:return+u}for(o=(s=Sy(u,2)).length,a=0;a<o;a++)if((c=Iy(s,a))<48||c>n)return NaN;return parseInt(s,i)}return+u};if(sy("Number",!yy(" 0o1")||!yy("0b1")||yy("+0x1"))){for(var Ry,wy=function(e){var t=arguments.length<1?0:yy(Ey(e)),r=this;return uy(_y,r)&&hy((function(){gy(r)}))?cy(Object(t),r,wy):t},Ay=ry?py(yy):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),ky=0;Ay.length>ky;ky++)ay(yy,Ry=Ay[ky])&&!ay(wy,Ry)&&fy(wy,Ry,my(yy,Ry));wy.prototype=_y,_y.constructor=wy,oy(iy,"Number",wy,{constructor:!0})}var Cy=Sn,My=$i.indexOf,Oy=yh,Py=te([].indexOf),Ly=!!Py&&1/Py([1],1,-0)<0,xy=Oy("indexOf");Cy({target:"Array",proto:!0,forced:Ly||!xy},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return Ly?Py(this,e,t)||0:My(this,e,t)}});var Dy=ht,Ny=wa,$y=ya;Sn({target:"Object",stat:!0,forced:O((function(){Ny(1)})),sham:!$y},{getPrototypeOf:function(e){return Ny(Dy(e))}});var Uy=Ll,By=Je,Vy=cr;Sn({target:"Reflect",stat:!0,forced:!O((function(){Reflect.apply((function(){}))}))},{apply:function(e,t,r){return Uy(By(e),t,Vy(r))}});var Fy=P,jy=wr.EXISTS,Wy=te,qy=ir.f,Gy=Function.prototype,Hy=Wy(Gy.toString),zy=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,Jy=Wy(zy.exec);Fy&&!jy&&qy(Gy,"name",{configurable:!0,get:function(){try{return Jy(zy,Hy(this))[1]}catch(e){return""}}});var Yy=Sn,Ky=Date,Qy=te(Ky.prototype.getTime);Yy({target:"Date",stat:!0},{now:function(){return Qy(new Ky)}});var Xy,Zy,e_,t_,r_="process"==X(C.process),i_=Kn,n_=qe,s_=TypeError,o_=function(e){if(i_(e))return e;throw s_(n_(e)+" is not a constructor")},a_=cr,c_=o_,u_=ae,d_=Ot("species"),l_=function(e,t){var r,i=a_(e).constructor;return void 0===i||u_(r=a_(i)[d_])?t:c_(r)},h_=/(?:ipad|iphone|ipod).*applewebkit/i.test(we),p_=C,m_=Ll,f_=Rn,g_=ve,v_=ft,y_=O,__=Yo,b_=xl,S_=Gt,I_=Nl,E_=h_,T_=r_,R_=p_.setImmediate,w_=p_.clearImmediate,A_=p_.process,k_=p_.Dispatch,C_=p_.Function,M_=p_.MessageChannel,O_=p_.String,P_=0,L_={};try{Xy=p_.location}catch(e){}var x_=function(e){if(v_(L_,e)){var t=L_[e];delete L_[e],t()}},D_=function(e){return function(){x_(e)}},N_=function(e){x_(e.data)},$_=function(e){p_.postMessage(O_(e),Xy.protocol+"//"+Xy.host)};R_&&w_||(R_=function(e){I_(arguments.length,1);var t=g_(e)?e:C_(e),r=b_(arguments,1);return L_[++P_]=function(){m_(t,void 0,r)},Zy(P_),P_},w_=function(e){delete L_[e]},T_?Zy=function(e){A_.nextTick(D_(e))}:k_&&k_.now?Zy=function(e){k_.now(D_(e))}:M_&&!E_?(t_=(e_=new M_).port2,e_.port1.onmessage=N_,Zy=f_(t_.postMessage,t_)):p_.addEventListener&&g_(p_.postMessage)&&!p_.importScripts&&Xy&&"file:"!==Xy.protocol&&!y_($_)?(Zy=$_,p_.addEventListener("message",N_,!1)):Zy="onreadystatechange"in S_("script")?function(e){__.appendChild(S_("script")).onreadystatechange=function(){__.removeChild(this),x_(e)}}:function(e){setTimeout(D_(e),0)});var U_,B_,V_,F_,j_,W_,q_,G_,H_={set:R_,clear:w_},z_=C,J_=/ipad|iphone|ipod/i.test(we)&&void 0!==z_.Pebble,Y_=/web0s(?!.*chrome)/i.test(we),K_=C,Q_=Rn,X_=M.f,Z_=H_.set,eb=h_,tb=J_,rb=Y_,ib=r_,nb=K_.MutationObserver||K_.WebKitMutationObserver,sb=K_.document,ob=K_.process,ab=K_.Promise,cb=X_(K_,"queueMicrotask"),ub=cb&&cb.value;ub||(U_=function(){var e,t;for(ib&&(e=ob.domain)&&e.exit();B_;){t=B_.fn,B_=B_.next;try{t()}catch(e){throw B_?F_():V_=void 0,e}}V_=void 0,e&&e.enter()},eb||ib||rb||!nb||!sb?!tb&&ab&&ab.resolve?((q_=ab.resolve(void 0)).constructor=ab,G_=Q_(q_.then,q_),F_=function(){G_(U_)}):ib?F_=function(){ob.nextTick(U_)}:(Z_=Q_(Z_,K_),F_=function(){Z_(U_)}):(j_=!0,W_=sb.createTextNode(""),new nb(U_).observe(W_,{characterData:!0}),F_=function(){W_.data=j_=!j_}));var db=ub||function(e){var t={fn:e,next:void 0};V_&&(V_.next=t),B_||(B_=t,F_()),V_=t},lb=C,hb=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},pb=function(){this.head=null,this.tail=null};pb.prototype={add:function(e){var t={item:e,next:null};this.head?this.tail.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return this.head=e.next,this.tail===e&&(this.tail=null),e.item}};var mb=pb,fb=C.Promise,gb="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,vb=!gb&&!r_&&"object"==typeof window&&"object"==typeof document,yb=C,_b=fb,bb=ve,Sb=pn,Ib=Lr,Eb=Ot,Tb=vb,Rb=gb,wb=Le;_b&&_b.prototype;var Ab=Eb("species"),kb=!1,Cb=bb(yb.PromiseRejectionEvent),Mb={CONSTRUCTOR:Sb("Promise",(function(){var e=Ib(_b),t=e!==String(_b);if(!t&&66===wb)return!0;if(!wb||wb<51||!/native code/.test(e)){var r=new _b((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((r.constructor={})[Ab]=i,!(kb=r.then((function(){}))instanceof i))return!0}return!t&&(Tb||Rb)&&!Cb})),REJECTION_EVENT:Cb,SUBCLASSING:kb},Ob={},Pb=Je,Lb=TypeError,xb=function(e){var t,r;this.promise=new e((function(e,i){if(void 0!==t||void 0!==r)throw Lb("Bad Promise constructor");t=e,r=i})),this.resolve=Pb(t),this.reject=Pb(r)};Ob.f=function(e){return new xb(e)};var Db,Nb,$b,Ub=Sn,Bb=r_,Vb=C,Fb=N,jb=yi,Wb=Qa,qb=Ua,Gb=Pd,Hb=Je,zb=ve,Jb=be,Yb=ed,Kb=l_,Qb=H_.set,Xb=db,Zb=hb,eS=mb,tS=ti,rS=fb,iS=Ob,nS="Promise",sS=Mb.CONSTRUCTOR,oS=Mb.REJECTION_EVENT,aS=Mb.SUBCLASSING,cS=tS.getterFor(nS),uS=tS.set,dS=rS&&rS.prototype,lS=rS,hS=dS,pS=Vb.TypeError,mS=Vb.document,fS=Vb.process,gS=iS.f,vS=gS,yS=!!(mS&&mS.createEvent&&Vb.dispatchEvent),_S="unhandledrejection",bS=function(e){var t;return!(!Jb(e)||!zb(t=e.then))&&t},SS=function(e,t){var r,i,n,s=t.value,o=1==t.state,a=o?e.ok:e.fail,c=e.resolve,u=e.reject,d=e.domain;try{a?(o||(2===t.rejection&&wS(t),t.rejection=1),!0===a?r=s:(d&&d.enter(),r=a(s),d&&(d.exit(),n=!0)),r===e.promise?u(pS("Promise-chain cycle")):(i=bS(r))?Fb(i,r,c,u):c(r)):u(s)}catch(e){d&&!n&&d.exit(),u(e)}},IS=function(e,t){e.notified||(e.notified=!0,Xb((function(){for(var r,i=e.reactions;r=i.get();)SS(r,e);e.notified=!1,t&&!e.rejection&&TS(e)})))},ES=function(e,t,r){var i,n;yS?((i=mS.createEvent("Event")).promise=t,i.reason=r,i.initEvent(e,!1,!0),Vb.dispatchEvent(i)):i={promise:t,reason:r},!oS&&(n=Vb["on"+e])?n(i):e===_S&&function(e,t){var r=lb.console;r&&r.error&&(1==arguments.length?r.error(e):r.error(e,t))}("Unhandled promise rejection",r)},TS=function(e){Fb(Qb,Vb,(function(){var t,r=e.facade,i=e.value;if(RS(e)&&(t=Zb((function(){Bb?fS.emit("unhandledRejection",i,r):ES(_S,r,i)})),e.rejection=Bb||RS(e)?2:1,t.error))throw t.value}))},RS=function(e){return 1!==e.rejection&&!e.parent},wS=function(e){Fb(Qb,Vb,(function(){var t=e.facade;Bb?fS.emit("rejectionHandled",t):ES("rejectionhandled",t,e.value)}))},AS=function(e,t,r){return function(i){e(t,i,r)}},kS=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=2,IS(e,!0))},CS=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw pS("Promise can't be resolved itself");var i=bS(t);i?Xb((function(){var r={done:!1};try{Fb(i,t,AS(CS,r,e),AS(kS,r,e))}catch(t){kS(r,t,e)}})):(e.value=t,e.state=1,IS(e,!1))}catch(t){kS({done:!1},t,e)}}};if(sS&&(hS=(lS=function(e){Yb(this,hS),Hb(e),Fb(Db,this);var t=cS(this);try{e(AS(CS,t),AS(kS,t))}catch(e){kS(t,e)}}).prototype,(Db=function(e){uS(this,{type:nS,done:!1,notified:!1,parent:!1,reactions:new eS,rejection:!1,state:0,value:void 0})}).prototype=jb(hS,"then",(function(e,t){var r=cS(this),i=gS(Kb(this,lS));return r.parent=!0,i.ok=!zb(e)||e,i.fail=zb(t)&&t,i.domain=Bb?fS.domain:void 0,0==r.state?r.reactions.add(i):Xb((function(){SS(i,r)})),i.promise})),Nb=function(){var e=new Db,t=cS(e);this.promise=e,this.resolve=AS(CS,t),this.reject=AS(kS,t)},iS.f=gS=function(e){return e===lS||void 0===e?new Nb(e):vS(e)},zb(rS)&&dS!==Object.prototype)){$b=dS.then,aS||jb(dS,"then",(function(e,t){var r=this;return new lS((function(e,t){Fb($b,r,e,t)})).then(e,t)}),{unsafe:!0});try{delete dS.constructor}catch(e){}Wb&&Wb(dS,hS)}Ub({global:!0,constructor:!0,wrap:!0,forced:sS},{Promise:lS}),qb(lS,nS,!1),Gb(nS);var MS=fb,OS=Mb.CONSTRUCTOR||!sd((function(e){MS.all(e).then(void 0,(function(){}))})),PS=N,LS=Je,xS=Ob,DS=hb,NS=Qu;Sn({target:"Promise",stat:!0,forced:OS},{all:function(e){var t=this,r=xS.f(t),i=r.resolve,n=r.reject,s=DS((function(){var r=LS(t.resolve),s=[],o=0,a=1;NS(e,(function(e){var c=o++,u=!1;a++,PS(r,t,e).then((function(e){u||(u=!0,s[c]=e,--a||i(s))}),n)})),--a||i(s)}));return s.error&&n(s.value),r.promise}});var $S=Sn,US=Mb.CONSTRUCTOR,BS=fb,VS=Te,FS=ve,jS=yi,WS=BS&&BS.prototype;if($S({target:"Promise",proto:!0,forced:US,real:!0},{catch:function(e){return this.then(void 0,e)}}),FS(BS)){var qS=VS("Promise").prototype.catch;WS.catch!==qS&&jS(WS,"catch",qS,{unsafe:!0})}var GS=N,HS=Je,zS=Ob,JS=hb,YS=Qu;Sn({target:"Promise",stat:!0,forced:OS},{race:function(e){var t=this,r=zS.f(t),i=r.reject,n=JS((function(){var n=HS(t.resolve);YS(e,(function(e){GS(n,t,e).then(r.resolve,i)}))}));return n.error&&i(n.value),r.promise}});var KS=N,QS=Ob;Sn({target:"Promise",stat:!0,forced:Mb.CONSTRUCTOR},{reject:function(e){var t=QS.f(this);return KS(t.reject,void 0,e),t.promise}});var XS=cr,ZS=be,eI=Ob,tI=Sn,rI=Mb.CONSTRUCTOR;Te("Promise"),tI({target:"Promise",stat:!0,forced:rI},{resolve:function(e){return function(e,t){if(XS(e),ZS(t)&&t.constructor===e)return t;var r=eI.f(e);return(0,r.resolve)(t),r.promise}(this,e)}});var iI=C,nI=O,sI=Kd,oI=ty.trim,aI=te("".charAt),cI=iI.parseFloat,uI=iI.Symbol,dI=uI&&uI.iterator,lI=1/cI("\t\n\v\f\r                 \u2028\u2029\ufeff-0")!=-1/0||dI&&!nI((function(){cI(Object(dI))}))?function(e){var t=oI(sI(e)),r=cI(t);return 0===r&&"-"==aI(t,0)?-0:r}:cI;Sn({global:!0,forced:parseFloat!=lI},{parseFloat:lI});var hI=window.navigator&&window.navigator.userAgent||"",pI=/AppleWebKit\/([\d.]+)/i.exec(hI);pI&&parseFloat(pI.pop());var mI=/iPad/i.test(hI),fI=navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/Macintosh/.test(hI),gI=/iPhone/i.test(hI)&&!mI,vI=/iPod/i.test(hI),yI=gI||mI||vI||fI,_I=/Android/i.test(hI);_I&&function(){var e=hI.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;var t=e[1]&&parseFloat(e[1]),r=e[2]&&parseFloat(e[2]);t&&r&&parseFloat(e[1]+"."+e[2])}(),_I&&/webkit/i.test(hI);var bI=/Firefox/i.test(hI),SI=bI&&function(){var e=hI.match(/Firefox\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),II=/Edge\//i.test(hI),EI=II&&function(){var e=hI.match(/Edge\/(\d+)/i);if(e&&e[1])return e[1]}(),TI=/Edg\//i.test(hI),RI=TI&&function(){var e=hI.match(/Edg\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),wI=/SogouMobileBrowser\//i.test(hI),AI=wI&&function(){var e=hI.match(/SogouMobileBrowser\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),kI=/MetaSr\s/i.test(hI),CI=kI&&function(){var e=hI.match(/MetaSr(\s\d+(\.\d+)+)/);return e&&e[1]?parseFloat(e[1]):null}(),MI=/TBS\/\d+/i.test(hI),OI=MI&&function(){var e=hI.match(/TBS\/(\d+)/i);if(e&&e[1])return e[1]}(),PI=/XWEB\/\d+/i.test(hI),LI=PI&&function(){var e=hI.match(/XWEB\/(\d+)/i);if(e&&e[1])return e[1]}();/MSIE\s8\.0/.test(hI),/MSIE\/\d+/i.test(hI)&&function(){var e=/MSIE\s(\d+)\.\d/.exec(hI),t=e&&parseFloat(e[1]);!t&&/Trident\/7.0/i.test(hI)&&/rv:11.0/.test(hI)&&(t=11)}();var xI=/(micromessenger|webbrowser)/i.test(hI),DI=xI&&function(){var e=hI.match(/MicroMessenger\/(\d+)/i);if(e&&e[1])return e[1]}(),NI=!MI&&/MQQBrowser\/\d+/i.test(hI)&&/COVC\/\d+/i.test(hI),$I=!MI&&/MQQBrowser\/\d+/i.test(hI)&&!/COVC\/\d+/i.test(hI),UI=($I||NI)&&function(){var e=hI.match(/ MQQBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),BI=!MI&&/ QQBrowser\/\d+/i.test(hI),VI=BI&&function(){var e=hI.match(/ QQBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),FI=!MI&&/QQBrowserLite\/\d+/i.test(hI),jI=FI&&function(){var e=hI.match(/QQBrowserLite\/([\d.]+)/);return e&&e[1]?e[1]:null}(),WI=!MI&&/MQBHD\/\d+/i.test(hI),qI=WI&&function(){var e=hI.match(/MQBHD\/([\d.]+)/);return e&&e[1]?e[1]:null}(),GI=/Windows/i.test(hI),HI=!yI&&/MAC OS X/i.test(hI),zI=!_I&&/Linux/i.test(hI);/MicroMessenger/i.test(hI);var JI=/UCBrowser/i.test(hI);/Electron/i.test(hI);var YI,KI,QI=/MiuiBrowser/i.test(hI),XI=QI&&function(){var e=hI.match(/MiuiBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),ZI=/HuaweiBrowser/i.test(hI),eE=/Huawei/i.test(hI),tE=ZI&&function(){var e=hI.match(/HuaweiBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),rE=/SamsungBrowser/i.test(hI),iE=rE&&function(){var e=hI.match(/SamsungBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),nE=/HeyTapBrowser/i.test(hI),sE=nE&&function(){var e=hI.match(/HeyTapBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),oE=/VivoBrowser/i.test(hI),aE=oE&&function(){var e=hI.match(/VivoBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),cE=function(){var e=hI.match(/Chrome\/(\d+)/);return e&&e[1]?Number(e[1]):null},uE=/Chrome/i.test(hI),dE=!II&&!kI&&!wI&&!MI&&!PI&&!TI&&!BI&&!QI&&!ZI&&!rE&&!nE&&!oE&&/Chrome/i.test(hI),lE=dE&&cE(),hE=dE&&function(){var e=hI.match(/Chrome\/([\d.]+)/);return e&&e[1]?e[1]:null}(),pE=!uE&&!$I&&!NI&&!FI&&!WI&&/Safari/i.test(hI),mE=function(){if(pE){var e=hI.match(/Version\/([\d.]+)/);if(e&&e[1])return e[1]}return""}(),fE=/Android.*(wv|.0.0.0)/.test(hI),gE=function(){if(fI)return mE;if(yI){var e=hI.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){var t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""}(),vE="15.1"===mE,yE="15.1"===gE,_E=14===(YI=Number(gE.split(".")[0]))||13===YI,bE="file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname,SE=function(){if(iw(KI))try{KI=window.localStorage}catch(e){Lw.warn(e),KI=!1}return KI},IE=new Map([[bI,["Firefox",SI]],[TI,["Edg",RI]],[dE,["Chrome",hE]],[pE,["Safari",mE]],[MI,["TBS",OI]],[PI,["XWEB",LI]],[xI&&gI,["WeChat",DI]],[BI,["QQ(Win)",VI]],[$I,["QQ(Mobile)",UI]],[NI,["QQ(Mobile X5)",UI]],[FI,["QQ(Mac)",jI]],[WI,["QQ(iPad)",qI]],[QI,["MI",XI]],[ZI,["HW",tE]],[rE,["Samsung",iE]],[nE,["OPPO",sE]],[oE,["VIVO",aE]],[II,["EDGE",EI]],[wI,["SogouMobile",AI]],[kI,["Sogou",CI]]]);function EE(){var e="unknown",t="unknown";return IE.get(!0)&&(e=IE.get(!0)[0],t=IE.get(!0)[1]),{name:e,version:t}}var TE=ht,RE=Fo;Sn({target:"Object",stat:!0,forced:O((function(){RE(1)}))},{keys:function(e){return RE(TE(e))}});var wE="audio",AE="video",kE="auxiliary",CE="smallVideo",ME="environment",OE="mute",PE="unmute",LE="ended",xE="playing",DE="pause",NE="error",$E="loadeddata",UE="audioinput",BE="videoinput",VE="main",FE="backup",jE="sei-message",WE="PLAYING",qE="PAUSED",GE="STOPPED",HE="qcloud",zE="",JE="jssdk_log",YE="live",KE="anchor",QE="audience",XE="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ZE="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",eT=VE,tT=kE,rT="unknown",iT="DISCONNECTED",nT="CONNECTING",sT="RECONNECTING",oT="CONNECTED",aT="connecting",cT="closed",uT="connected",dT="publish",lT="unpublish",hT="subscribe",pT="unsubscribe",mT="uplink-connection",fT="uplink-reconnection",gT="downlink-connection",vT="downlink-reconnection",yT="setLocalDescription",_T="setRemoteDescription",bT="iceConnectionState",ST="stream-initialize",IT="websocketConnectionState",ET="websocketReconnectionState",TT="update-stream",RT="recover-subscription",wT="start-mix-transcode",AT="stop-mix-transcode",kT="player-error",CT="schedule",MT="load-worklet",OT="unsubscribe",PT="subscribe_change",LT="unified-plan",xT="manual",DT="preset-layout",NT="$PLACE_HOLDER_REMOTE$",$T=0,UT=4,BT="string",VT="number",FT="boolean",jT="object",WT="add",qT="remove",GT={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5},HT=6048e5,zT="schedule.rtc.qq.com",JT="schedule.rtc.qcloud.com",YT="schedule.rtc.tencentcloud.com",KT="schedule-ecdn.rtc.tencentcloud.com",QT="LocalStream",XT="RemoteStream",ZT="web.sdk.qcloud.com",eR="web.sdk.tencent.cn",tR="web.sdk.cloud.tencent.cn",rR="https://console.cloud.tencent.com/trtc",iR="https://".concat(ZT,"/trtc/webrtc/doc"),nR="".concat(iR,"/zh-cn/"),sR="trtc_error_assistance",oR="default",aR="communications",cR={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,NONE:5},uR=Object.keys(cR),dR=["normal leave","timeout leave","kick","role change"],lR="ric",hR="raf",pR="interval",mR="timeout",fR=de,gR=Kd,vR=/"/g,yR=te("".replace),_R=function(e,t,r,i){var n=gR(fR(e)),s="<"+t;return""!==r&&(s+=" "+r+'="'+yR(gR(i),vR,"&quot;")+'"'),s+">"+n+"</"+t+">"},bR=O,SR=function(e){return bR((function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}))},IR=_R;Sn({target:"String",proto:!0,forced:SR("link")},{link:function(e){return IR(this,"a","href",e)}}),Sn({target:"Array",stat:!0},{isArray:An});var ER="AVOID_REPEATED_CALL",TR="INVALID_PARAMETER_TYPE",RR="INVALID_PARAMETER_INSTANCE",wR="SIGNAL_CHANNEL_RECONNECTION_FAILED",AR="JOIN_ROOM_FAILED",kR="INVALID_REMOTE_STREAM",CR="INVALID_OPERATION_START_PUBLISH_CDN",MR="START_PUBLISH_CDN_FAILED",OR="STOP_PUBLISH_CDN_FAILED",PR="INVALID_AUDIO_VOLUME",LR="INVALID_REPLACE_TRACK",xR="INVALID_STREAM_INITIALIZED",DR="CLIENT_DESTROYED",NR="PLAY_FAILED",$R="NOT_SUPPORTED_HTTP",UR="NOT_SUPPORTED_WEBRTC",BR="NOT_SUPPORTED_H264ENCODE",VR="NOT_SUPPORTED_H264DECODE",FR="SIGNAL_RESPONSE_FAILED",jR="CATCH_HANDLER_ERROR",WR="SEI_NOT_SUPPORT",qR="CALL_FREQUENCY_LIMIT",GR="CONNECTION_ABORED",HR={AVOID_REPEATED_CALL:function(e){return"previous ".concat(e.name,"() is ongoing, please avoid repeated calls.")},INVALID_PARAMETER_REQUIRED:function(e){var t=e.key,r=e.rule,i=e.fnName,n=e.value;return"'".concat(t||r.name,"' is a required param when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE:function(e){var t,r=e.key,i=e.rule,n=e.fnName,s=e.value,o="".concat(r||i.name);return t=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be types of ").concat(t," when calling ").concat(n,"(), received types: ").concat(dw(s),".")},INVALID_PARAMETER_EMPTY:function(e){var t=e.key,r=e.rule,i=e.fnName,n=e.value;return"'".concat(t||r.name,"' cannot be '").concat(n,"' when calling ").concat(i,"().")},INVALID_PARAMETER_INSTANCE:function(e){var t=e.key,r=e.rule,i=e.fnName,n=e.value,s="".concat(t||r.name),o="".concat(r.instanceOf.name||r.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(i,"(), received types: ").concat(dw(n),".")},INVALID_PARAMETER_RANGE:function(e){var t=e.key,r=e.rule,i=e.fnName,n=e.value;return"'".concat(t||r.name,"' must be one of ").concat(r.values.join("|")," when calling ").concat(i,"(), received: ").concat(n,".")},API_CALL_TIMEOUT:function(e){return"".concat(e.commandDesc||e.command," timeout observed.")},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:function(e){return"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," }).")},ERROR_MESSAGE:function(e){var t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:function(e){return"exchange sdp failed ".concat(e.errMsg,".")},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:function(e){return"'".concat(e,"' must be validate string when useStringRoomId is true.")},INVALID_ROOMID_INTEGER:function(e){return"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false.")},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:function(e){var t=e.error,r=e.code;return"Failed to join room - ".concat(t," code: ").concat(r)},REJOIN_ROOM_FAILED:function(e){return"reJoin room: ".concat(e.roomId," failed, please check your network.")},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat(QE,', please call switchRole("').concat(KE,'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:"duplicate publishing, please unpublish and then re-publish.",INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:function(e){var t=e.message,r=e.stream;return"failed to subscribe ".concat(r.getUserId()," ").concat(r.getType()," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat(KE," or ").concat(QE,"."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:function(e){return"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,".")},CLIENT_BANNED:function(e){return"client was banned because of "+e.message+"."},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:function(e){return"startPublishCDNStream failed, errMsg: ".concat(e.message,".")},STOP_PUBLISH_CDN_FAILED:function(e){return"stopPublishCDNStream failed, errMsg: ".concat(e.message,".")},INVALID_STREAM_ID:function(e){return"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"the track to be removed is not being publishing.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REMOVE_TRACK_NOT_PUBLISHED:function(e){return"try to replace ".concat(e.kind," track but there's no previous ").concat(e.kind," being published.")},START_MIX_TRANSCODE_FAILED:function(e){return"startMixTranscode failed, errMsg: ".concat(e.message,".")},STOP_MIX_TRANSCODE_FAILED:function(e){return"stopMixTranscode failed, errMsg: ".concat(e.message,".")},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:function(e){var t=e.key,r=e.rule,i=e.fnName;return e.value,"'".concat(t||r.name,"' cannot be less than 0 when calling ").concat(i,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:function(e){return"'".concat(e,"' is required and must be between 1 and 15.")},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:function(e){var t=e.key,r=e.fnName;return"'".concat(t,"' is not found in the document object when calling ").concat(r,"().")},INVALID_ELEMENT_ID_TYPE:function(e){var t=e.key,r=e.fnName,i=e.type;return"the element corresponding to '".concat(t,"' must be instanceof HTMLDivElement when calling ").concat(r,"(), received: ").concat(i,".")},PLAY_FAILED:function(e){return"".concat(e.media," play failed,browser exception: ").concat(e.error.toString())},INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_REPLACE_TRACK:"replaceTrack is not supported in this browser, please use switchDevice or addTrack instead.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone and the configuration on TRTC.createStream.",CAMERA_NOT_FOUND:"no camera detected, please check your camera and the configuration on TRTC.createStream.",SIGNAL_RESPONSE_FAILED:function(e){return"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,".")},CATCH_HANDLER_ERROR:function(e){var t=e.name,r=e.event;return"an error was caught on ".concat(t,".on('").concat(r,"', handler), please check your code on 'handler'.")},API_NOT_EXIST:function(e){var t=e.name;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:function(e){return"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join.")},STREAM_UNSUBSCRIBED:"stream has been unsubscribed, please call client.unsubscribe after last client.subscribe finished.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:function(e){var t=e.funName;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:function(e){return"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":"")},SEI_DISABLED:"SEI is disabled, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:function(e){return"buffer size(".concat(e,") is over 1000 Bytes")},SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:function(e){var t=e.isSize,r=e.name,i=e.timesInSecond,n=e.maxSizeInSecond;return"api ".concat(r," call ").concat(t?"size":"times"," is over ").concat(t?n+" bytes":i," in a second.")},CONNECTION_ABORED:function(e){return"connection aborted due to: "+e}},zR=function(e,t){return t?iR+"/"+e+"/"+t:iR+"/"+e+"/index.html"};function JR(e){var t=e.key,r=e.data,i=e.link,n=e.addDocLink,s=void 0===n||n,o="",a="",c="";rw(HR[t])?o=HR[t](r):nw(HR[t])&&(o=HR[t]);var u=function(){if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};var e=localStorage.getItem(sR);if(e){e=JSON.parse(e);var t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);var r=window.TRTC_ERROR_INFO,i=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:r,TRTC_ERROR_LINK:i}}return{}}(),d=u.TRTC_ERROR_INFO,l=u.TRTC_ERROR_LINK;i?c="".concat(i.className,".html#").concat(i.fnName):l&&l[t]&&(c=l[t]);var h=o;return gw()&&(d&&d[t]&&(rw(d[t])?a=d[t](r):nw(d[t])&&(a=d[t])),a&&(h=s?a+"\n请查看文档: "+zR("zh-cn",c)+"\n\n":a+"\n\n",h+=o)),s&&(h+=" \nRefer to: "+zR("en",c)+"\n"),h}var YR=function(){return function(e){var t=window.location.search.match(new RegExp("(\\?|&)trtc_env=([^&]*)(&|$)"));return t?decodeURIComponent(t[2]):""}()},KR=function(e){return(e=Number(e))>0&&e<14e8},QR=function(e,t){var r;r=zE||(KR(e)?"https://apisgp.my-imcloud.com":"https://yun.tim.qq.com");var i=Math.floor(Math.random()*Math.pow(2,31));return"".concat(r,"/v5/AVQualityReportSvc/C2S?random=").concat(i,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function XR(){var e=navigator.userAgent,t=navigator.connection,r=e.match(/NetType\/\w+/)?e.match(/NetType\/\w+/)[0]:"";"3gnet"===(r=r.toLowerCase().replace("nettype/",""))&&(r="3g");var i=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();"slow-2"===n&&(n="2g");var s=r||"unknown";if(i)switch(i){case"cellular":case"wimax":s=n||"unknown";break;case"wifi":s="wifi";break;case"ethernet":s="wired";break;case"none":case"other":case"unknown":s="unknown"}return s}var ZR=function(e){if(!e||"object"!==n(e)||"[object Object]"!=Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function ew(e){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:ew(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function tw(e){var t=Math.round(e/2)+1;return t>6?13e3:1e3*ew(t)}var rw=function(e){return"function"==typeof e},iw=function(e){return void 0===e},nw=function(e){return"string"==typeof e},sw=function(e){return"number"==typeof e},ow=function(e){return"boolean"==typeof e},aw=function(e){return"object"===dw(e)},cw=function(e){return"array"===dw(e)},uw=function(e){return dw(e)==="MediaStreamTrack".toLowerCase()};function dw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}function lw(e){var t={};return t.urls="turn:".concat(e.url),iw(e.username)||iw(e.credential)||(t.username=e.username,t.credential=e.credential,t.credentialType="password",iw(e.credentialType)||(t.credentialType=e.credentialType)),t}function hw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}function pw(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"big";if(!nw(e))return 0;var r=e.split(".");return"big"===t?(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0:(Number(r[3])<<24|Number(r[2])<<16|Number(r[1])<<8|Number(r[0]))>>>0}var mw,fw,gw=function(){return"zh"===(navigator.language||navigator.userLanguage).substr(0,2)},vw=(mw=!1,fw=document.visibilityState,function(){document.visibilityState!==fw&&Lw.info("visibility change: ".concat(document.visibilityState)),mw||(document.addEventListener("visibilitychange",(function(){Lw.info("visibility change: "+document.visibilityState),fw=document.visibilityState})),mw=!0)});window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext;var yw=function(){var e;return function(){return e||((e=new window.AudioContext).onstatechange=function(){Lw.info("gain context state: ".concat(e.state)),"suspended"===e.state?(e.resume(),document.addEventListener("click",e.resume)):"interrupted"===e.state?e.resume():document.removeEventListener("click",e.resume)},e)}}(),_w=!!window.AudioWorkletNode,bw=function(e,t){var r=e.emit;return e.emit=function(){for(var i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];try{r.apply(e,n)}catch(e){var o=JR({key:jR,data:{name:t,event:n[0]},addDocLink:!1});Lw.warn(o+"\n\n"+e.stack)}},e},Sw=function(e){return+e<10?"0".concat(e):e},Iw=function(e){var t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;var r=t.split("."),i=Sw(r[1])+Sw(r[2]);return r[1]-15>0&&(r[1]="15"),r[2]-15>0&&(r[2]="15"),r.join(".")+"."+i};function Ew(e){var t=e.url,r=e.body,i=e.method,n=e.timeout,s=new XMLHttpRequest;return new Promise((function(e,o){s.onload=function(t){if(s.status>=200&&s.status<300&&s.responseText.length>0)try{var r=JSON.parse(s.response);e({data:r})}catch(t){e({data:s.response})}else s.status>0&&o({code:s.status,message:"request failed, readyState:".concat(s.readyState," status:").concat(s.status," loaded size:").concat(t.loaded)})};var a=function(e){o({code:s.readyState,message:"request ".concat(e.type,", readyState:").concat(s.readyState," status:").concat(s.status," loaded size:").concat(e.loaded)})};s.onerror=a,s.onabort=a,s.ontimeout=a,s.timeout=n||5e3,s.open(i||"POST",t,!0),s.send(r)}))}var Tw={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,i,s,o){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new n(i,s||e,o),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 o(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,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},a.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,o=new Array(s);n<s;n++)o[n]=i[n].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,n,s,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,u,d=this._events[a],l=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,s),!0;case 6:return d.fn.call(d.context,t,i,n,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var h,p=d.length;for(u=0;u<p;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,i);break;case 4:d[u].fn.call(d[u].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,i,n){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||n&&!a.once||i&&a.context!==i||o(this,s);else{for(var c=0,u=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||i&&a[c].context!==i)&&u.push(a[c]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(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}(Tw);var Rw=Tw.exports,ww=new Rw,Aw=110,kw=113,Cw=114;function Mw(e){var t=e.retryFunction,r=e.settings,n=e.onError,s=e.onRetrying,a=e.onRetryFailed,c=e.context;return function(){for(var e=this,u=arguments.length,d=new Array(u),l=0;l<u;l++)d[l]=arguments[l];var h=r.retries||5,p=0,m=-1,f=0,g=function(){var u=o(i().mark((function o(u,l){var v,y,_,b;return i().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return v=c||e,i.prev=1,i.next=4,t.apply(v,d);case 4:y=i.sent,p=0,u(y),i.next=14;break;case 9:i.prev=9,i.t0=i.catch(1),_=function(){clearTimeout(m),p=0,f=2,l(i.t0)},b=function(){2!==f&&p<h?(p++,f=1,rw(s)&&s.call(v,p,_),m=setTimeout((function(){m=-1,g(u,l)}),iw(r.timeout)?1e3:r.timeout)):(_(),rw(a)&&a.call(v,i.t0))},rw(n)?n.call(v,i.t0,b,l):b();case 14:case"end":return i.stop()}}),o,null,[[1,9]])})));return function(e,t){return u.apply(this,arguments)}}();return new Promise(g)}}var Ow=u((function e(t){a(this,e),this.log=t.log,this.level=t.level,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.forAllJoinedClients=t.forAllJoinedClients,this.uploaded=!1})),Pw=function(){function e(t){a(this,e),this.id_=t.id,this.userId_=t.userId,this.sdkAppId_=t.sdkAppId,this.type_=t.type,this.isLocal_=!ow(t.isLocal)||t.isLocal}return u(e,[{key:"setUserId",value:function(e){this.userId_=e}},{key:"setSdkAppId",value:function(e){this.sdkAppId_=e}},{key:"log",value:function(e,t){Lw.log({log:"[".concat(this.isLocal_?"↑":"↓").concat(this.id_,"] ").concat(this.type_?this.type_+" ":"").concat(t),level:e,forAllJoinedClients:iw(this.userId_),userId:this.userId_,sdkAppId:this.sdkAppId_})}},{key:"info",value:function(e){this.log(cR.INFO,e)}},{key:"debug",value:function(e){this.log(cR.DEBUG,e)}},{key:"warn",value:function(e){this.log(cR.WARN,e)}},{key:"error",value:function(e){this.log(cR.ERROR,e)}}]),e}(),Lw=new(function(){function e(){var t=this;a(this,e),this.clients_=new Set,this.queue_=[],this.timeoutId_=-1,this.logLevel_=cR.DEBUG,this.logLevelToUpload_=cR.INFO,this.enableUploadLog_=!0,this.isAbleToUpload_=!1,this.startUpload(),this.checkURLParam(),ww.on(30,(function(e){var r=e.client;return t.clients_.add(r)})),ww.on(33,(function(e){var r=e.client;return t.clients_.delete(r)})),ww.on(31,(function(e){e&&ZR(e.config)&&uR[e.config.logLevelToUpload]&&(t.logLevelToUpload_=e.config.logLevelToUpload)})),ww.on(4,this.setIsAbleToUpload,this),ww.on(5,this.setIsAbleToUpload,this)}var t,r;return u(e,[{key:"getIsAbleToUpload",value:function(){return this.isAbleToUpload_}},{key:"setIsAbleToUpload",value:function(){this.isAbleToUpload_=!0,ww.off(4,this.setIsAbleToUpload,this),ww.off(5,this.setIsAbleToUpload,this)}},{key:"startUpload",value:(r=o(i().mark((function e(){var t=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.upload();case 3:e.next=7;break;case 5:e.prev=5,e.t0=e.catch(0);case 7:this.timeoutId_=setTimeout((function(){return t.startUpload()}),2e3);case 8:case"end":return e.stop()}}),e,this,[[0,5]])}))),function(){return r.apply(this,arguments)})},{key:"stopUpload",value:function(){-1!==this.timeoutId_&&(clearTimeout(this.timeoutId_),this.timeoutId_=-1)}},{key:"getLogsToUpload",value:function(){var e=this,t={map:new Map,splicedQueue:[]};if(this.queue_[0].forAllJoinedClients&&0===this.clients_.size)return t;for(var r=0,i=function(){if(50===r)return"break";var i=e.queue_[r];i.forAllJoinedClients?e.clients_.forEach((function(e){if(e.getIsJoined()){var r=e.getUserId(),n=e.getSDKAppId();t.map.has(r)?t.map.get(r).logs.push(i):t.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}})):t.map.has(i.userId)?t.map.get(i.userId).logs.push(i):t.map.set(i.userId,{userId:i.userId,sdkAppId:i.sdkAppId,logs:[i]})};r<this.queue_.length&&"break"!==i();r++);return t.map.size>0&&(t.splicedQueue=this.queue_.splice(0,r)),t}},{key:"upload",value:(t=o(i().mark((function e(){var t,r,n,s,o,a,c,u,d,l;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this.queue_.length&&this.isAbleToUpload_){e.next=2;break}return e.abrupt("return");case 2:if(t=this.getLogsToUpload(),r=t.map,n=t.splicedQueue,0!==r.size){e.next=5;break}return e.abrupt("return");case 5:e.prev=5,s=I(r.values()),o=0;case 8:if(!(o<s.length)){e.next=16;break}return a=s[o],c=a.userId,u=a.sdkAppId,d=a.logs,e.next=12,this.uploadLogWithRetry(JSON.stringify({timestamp:zg(),sdkAppId:String(u),userId:c,version:$o,log:d.map((function(e){return e.log})).join("\n")}),u);case 12:d.forEach((function(e){return e.uploaded=!0}));case 13:o++,e.next=8;break;case 16:e.next=20;break;case 18:e.prev=18,e.t0=e.catch(5);case 20:(l=n.filter((function(e){return!e.uploaded}))).length>0&&(this.queue_=l.concat(this.queue_));case 22:case"end":return e.stop()}}),e,this,[[5,18]])}))),function(){return t.apply(this,arguments)})},{key:"uploadLogWithRetry",value:function(e,t){return Mw({retryFunction:function(){return Ew({url:QR(t,JE),body:e,timeout:5e3})},settings:{retries:3,timeout:1e3},onError:function(e,t){t()}})()}},{key:"getPrefix",value:function(e){var t=new Date;return t.setTime(Hg()),String.prototype.padStart?"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t.getMilliseconds().toString().padStart(3,"0"),"] <").concat(uR[e],">"):"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t.getMilliseconds(),"] <").concat(uR[e],">")}},{key:"getLogLevel",value:function(){return this.logLevel_}},{key:"setLogLevel",value:function(e){iw(uR[e])||(this.logLevel_!==e&&this.info("setLogLevel ".concat(e)),this.logLevel_=e)}},{key:"enableUploadLog",value:function(){this.enableUploadLog_=!0}},{key:"disableUploadLog",value:function(){this.enableUploadLog_=!1}},{key:"log",value:function(e){var t=e.log,r=e.level,i=e.forAllJoinedClients,n=void 0===i||i,s=e.userId,o=e.sdkAppId;if(t="".concat(this.getPrefix(r)," ").concat(t),this.enableUploadLog_&&r>=this.logLevelToUpload_&&this.queue_.push(new Ow({log:t,level:r,userId:s,sdkAppId:o,forAllJoinedClients:n})),!(r<this.logLevel_)){var a=uR[r]?uR[r].toLowerCase():"info";console[a](t)}}},{key:"debug",value:function(e){this.log({log:e,level:cR.DEBUG})}},{key:"info",value:function(e){this.log({log:e,level:cR.INFO})}},{key:"warn",value:function(e){this.log({log:e,level:cR.WARN})}},{key:"error",value:function(e){this.log({log:e,level:cR.ERROR})}},{key:"createLogger",value:function(e){return new Pw(e)}},{key:"checkURLParam",value:function(){var e=new URLSearchParams(location.search).get("logLevelToUpload");uR[e]&&(this.logLevelToUpload_=e)}}]),e}()),xw=!0,Dw=be,Nw=Math.floor,$w=Number.isInteger||function(e){return!Dw(e)&&isFinite(e)&&Nw(e)===e};Sn({target:"Number",stat:!0},{isInteger:$w});var Uw,Bw=ov,Vw=TypeError,Fw=function(e){if(Bw(e))throw Vw("The method doesn't accept regular expressions");return e},jw=Ot("match"),Ww=function(e){var t=/./;try{"/./"[e](t)}catch(r){try{return t[jw]=!1,"/./"[e](t)}catch(e){}}return!1},qw=Sn,Gw=te,Hw=M.f,zw=Mi,Jw=Kd,Yw=Fw,Kw=de,Qw=Ww,Xw=Gw("".startsWith),Zw=Gw("".slice),eA=Math.min,tA=Qw("startsWith");qw({target:"String",proto:!0,forced:!(!tA&&(Uw=Hw(String.prototype,"startsWith"),Uw&&!Uw.writable)||tA)},{startsWith:function(e){var t=Jw(Kw(this));Yw(e);var r=zw(eA(arguments.length>1?arguments[1]:void 0,t.length)),i=Jw(e);return Xw?Xw(t,i,r):Zw(t,r,r+i.length)===i}});var rA=P,iA=te,nA=N,sA=O,oA=Fo,aA=zi,cA=$,uA=ht,dA=oe,lA=Object.assign,hA=Object.defineProperty,pA=iA([].concat),mA=!lA||sA((function(){if(rA&&1!==lA({b:1},lA(hA({},"a",{enumerable:!0,get:function(){hA(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach((function(e){t[e]=e})),7!=lA({},e)[r]||oA(lA({},t)).join("")!=i}))?function(e,t){for(var r=uA(e),i=arguments.length,n=1,s=aA.f,o=cA.f;i>n;)for(var a,c=dA(arguments[n++]),u=s?pA(oA(c),s(c)):oA(c),d=u.length,l=0;d>l;)a=u[l++],rA&&!nA(o,c,a)||(r[a]=c[a]);return r}:lA,fA=mA;Sn({target:"Object",stat:!0,arity:2,forced:Object.assign!==fA},{assign:fA});var gA=te,vA=Je,yA=be,_A=ft,bA=xl,SA=L,IA=Function,EA=gA([].concat),TA=gA([].join),RA={},wA=function(e,t,r){if(!_A(RA,t)){for(var i=[],n=0;n<t;n++)i[n]="a["+n+"]";RA[t]=IA("C,a","return new C("+TA(i,",")+")")}return RA[t](e,r)},AA=SA?IA.bind:function(e){var t=vA(this),r=t.prototype,i=bA(arguments,1),n=function(){var r=EA(i,bA(arguments));return this instanceof n?wA(t,r.length,r):t.apply(e,r)};return yA(r)&&(n.prototype=r),n};Sn({target:"Function",proto:!0,forced:Function.bind!==AA},{bind:AA});var kA=Sn,CA=ds.findIndex,MA=ga,OA="findIndex",PA=!0;OA in[]&&Array(1).findIndex((function(){PA=!1})),kA({target:"Array",proto:!0,forced:PA},{findIndex:function(e){return CA(this,e,arguments.length>1?arguments[1]:void 0)}}),MA(OA);var LA=P,xA=te,DA=Fo,NA=pe,$A=xA($.f),UA=xA([].push),BA=function(e){return function(t){for(var r,i=NA(t),n=DA(i),s=n.length,o=0,a=[];s>o;)r=n[o++],LA&&!$A(i,r)||UA(a,e?[r,i[r]]:i[r]);return a}},VA=BA(!1);Sn({target:"Object",stat:!0},{values:function(e){return VA(e)}});var FA=$i.includes,jA=ga;Sn({target:"Array",proto:!0,forced:O((function(){return!Array(1).includes()}))},{includes:function(e){return FA(this,e,arguments.length>1?arguments[1]:void 0)}}),jA("includes");var WA=Sn,qA=Fw,GA=de,HA=Kd,zA=Ww,JA=te("".indexOf);WA({target:"String",proto:!0,forced:!zA("includes")},{includes:function(e){return!!~JA(HA(GA(this)),HA(qA(e)),arguments.length>1?arguments[1]:void 0)}});var YA="DISCONNECTED",KA="CONNECTING",QA="RECONNECTING",XA="CONNECTED",ZA={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772},ek=[ZA.UPDATE_REMOTE_MUTE_STAT,ZA.UPLINK_NETWORK_STATS,ZA.USER_LIST_RES,ZA.MUTE_RESULT],tk={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res"},rk="unpublish",ik={INVALID_PARAMETER:4096,INVALID_OPERATION:4097,NOT_SUPPORTED:4098,DEVICE_NOT_FOUND:4099,INITIALIZE_FAILED:4100,SIGNAL_CHANNEL_SETUP_FAILED:16385,SIGNAL_CHANNEL_ERROR:16386,ICE_TRANSPORT_ERROR:16387,JOIN_ROOM_FAILED:16388,CREATE_OFFER_FAILED:16389,SIGNAL_CHANNEL_RECONNECTION_FAILED:16390,UPLINK_RECONNECTION_FAILED:16391,DOWNLINK_RECONNECTION_FAILED:16392,REMOTE_STREAM_NOT_EXIST:16400,CLIENT_BANNED:16448,SERVER_TIMEOUT:16449,SUBSCRIPTION_TIMEOUT:16450,PLAY_NOT_ALLOWED:16451,DEVICE_AUTO_RECOVER_FAILED:16452,START_PUBLISH_CDN_FAILED:16453,STOP_PUBLISH_CDN_FAILED:16454,START_MIX_TRANSCODE_FAILED:16455,STOP_MIX_TRANSCODE_FAILED:16456,NOT_SUPPORTED_H264:16457,SWITCH_ROLE_FAILED:16458,API_CALL_TIMEOUT:16459,SCHEDULE_FAILED:16460,API_CALL_ABORTED:16461,UNKNOWN:65535},nk=function(e){l(r,e);var t=y(r);function r(e){var i,n=e.name,s=void 0===n?"RtcError":n,o=e.message,c=e.code,u=void 0===c?ik.UNKNOWN:c,d=e.extraCode,l=void 0===d?0:d,h=e.constraint;a(this,r);var p="<".concat(function(e){for(var t in ik)if(ik[t]===e)return t;return"UNKNOWN"}(u)," 0x").concat(u.toString(16),">");return(i=t.call(this,o+"".concat(h?" constraint: ".concat(h):"")+"".concat(null!=o&&o.includes(p)?"":" "+p))).code_=u,i.extraCode_=l,i.name=s,i.message_=o,h&&(i.constraint=h),i}return u(r,[{key:"getCode",value:function(){return this.code_}},{key:"getExtraCode",value:function(){return this.extraCode_}}]),r}(g(Error)),sk=new Map,ok=function(e,t){var r=sk.get(e);r||(sk.set(e,[]),r=sk.get(e)),r.push(t)},ak=function(e){var t=sk.get(e),r=[];return t?(sk.delete(e),r=t.map((function(e){return{uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}}))):r=[],r},ck=Object.prototype.hasOwnProperty;function uk(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(ZR(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(var t in e)if(ck.call(e,t))return!1;return!0}return!1}var dk=new(function(){function e(){a(this,e);var t=EE(),r=t.name,i=t.version;this.roomIdMap_=new Map,this.configs_={sdkAppId:"",userId:"",version:$o,env:HE,browserVersion:r+i,ua:navigator.userAgent}}return u(e,[{key:"setConfig",value:function(e){var t=e.sdkAppId,r=e.env,i=e.userId,n=e.roomId;t!==this.configs_.sdkAppId&&(this.configs_.sdkAppId=String(t)),this.configs_.env=r,this.configs_.userId=i,this.roomIdMap_.set(i,String(n))}},{key:"logEvent",value:function(e){if(!bE){var t=r(r(r({},e),this.configs_),{},{userId:e.userId||this.configs_.userId});iw(t.code)&&(t.code="failed"===t.result?ik.UNKNOWN:0),this.sendRequest(QR(this.configs_.sdkAppId,"jssdk_event"),t)}}},{key:"logSuccessEvent",value:function(e){bE||(this.logEvent(r(r({},e),{},{result:"success",roomId:this.roomIdMap_.get(e.userId)})),this.configs_.env===HE&&this.uploadEventToKibana(r(r({},e),{},{result:"success"})))}},{key:"logFailedEvent",value:function(e){if(!bE){var t=e.eventType,i=e.code,n=e.error,s=e.userId,o={roomId:this.roomIdMap_.get(s),userId:s,eventType:t,result:"failed",code:i||(n instanceof nk?n.getExtraCode()||n.getCode():ik.UNKNOWN)};this.logEvent(o),this.configs_.env===HE&&this.uploadEventToKibana(r(r({},o),{},{error:n}))}}},{key:"uploadEventToKibana",value:function(e){var t="stat-".concat(e.eventType,"-").concat(e.result);"delta-join"!==e.eventType&&"delta-leave"!==e.eventType&&"delta-publish"!==e.eventType||(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}},{key:"uploadEvent",value:function(e){var t=e.log,r=e.userId,i=e.error,n={timestamp:zg(),sdkAppId:this.configs_.sdkAppId,userId:r||this.configs_.userId,version:this.configs_.version,log:t};i&&(n.errorInfo=i.message),this.sendRequest(QR(this.configs_.sdkAppId,JE),n)}},{key:"sendRequest",value:function(e,t){var r=this;Lw.getIsAbleToUpload()?Ew({url:e,body:JSON.stringify(t)}).catch((function(){})):setTimeout((function(){r.sendRequest(e,t)}),1e3)}}]),e}()),lk=function(){function e(t){a(this,e),this.client_=t.client,this.sdkAppId_=t.sdkAppId,this.userId_=t.userId,this.userSig_=t.userSig,this.url_=t.url,this.backupUrl_=t.backupUrl;var r="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId_),"&userId=").concat(encodeURIComponent(this.userId_),"&userSig=").concat(encodeURIComponent(this.userSig_));this.urlWithParam_="".concat(this.url_).concat(r),this.backupUrlWithParam_="".concat(this.backupUrl_).concat(r),this.isConnected_=!1,this.isConnecting_=!1,this.socketInUse_=null,this.socket_=null,this.backupSocket_=null,this.backupTimer_=-1,this.signalInfo_={},this.currentState_=YA,this.reconnectionCount_=0,this.reconnectionTimer_=-1,this.seq_=0,this.log_=Lw.createLogger({id:"ws|"+this.userId_,userId:this.userId_,sdkAppId:this.sdkAppId_}),this.emitter_=new Rw}return u(e,[{key:"connect",value:function(){var e=this;return new Promise((function(t,r){e.log_.info("connect to url: ".concat(e.urlWithParam_)),e.emitConnectionStateChanged(KA),e.socket_=new WebSocket(e.urlWithParam_),e.bindSocket(e.socket_),e.backupTimer_=setTimeout((function(){e.isConnected_||(e.log_.info("trying to connect to backupUrl"),e.tryConnectBackup())}),5e3),e.once(3,t),e.once(4,r)}))}},{key:"tryConnectBackup",value:function(){this.backupSocket_||(this.unbindAndCloseSocket(VE),this.log_.debug("try to connect to url: ".concat(this.backupUrlWithParam_)),this.backupSocket_=new WebSocket(this.backupUrlWithParam_),this.bindSocket(this.backupSocket_))}},{key:"bindSocket",value:function(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this)}},{key:"unbindSocket",value:function(e){e.onopen=function(){},e.onclose=function(){},e.onerror=function(){},e.onmessage=function(){}}},{key:"unbindAndCloseSocket",value:function(e){if(e===VE){if(this.socket_){this.unbindSocket(this.socket_);try{this.socket_.close(1e3)}catch(e){}this.socket_=null}}else if(this.backupSocket_){this.unbindSocket(this.backupSocket_);try{this.backupSocket_.close(1e3)}catch(e){}this.backupSocket_=null}}},{key:"clearBackupTimer",value:function(){-1!==this.backupTimer_&&(clearTimeout(this.backupTimer_),this.backupTimer_=-1)}},{key:"clearReconnectionTimer",value:function(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}},{key:"onopen",value:function(e){if(!this.isConnected_){this.isConnected_=!0,this.isConnecting_=!1,this.clearBackupTimer(),e.target===this.socket_?(this.unbindAndCloseSocket(FE),this.socketInUse_=this.socket_):(this.unbindAndCloseSocket(VE),this.socketInUse_=this.backupSocket_);var t=e.target.url;this.log_.info("websocket[".concat(t,"] is connected")),this.currentState_===KA?this.addSignalEvent(32791,"signal channel is connected"):this.currentState_===QA&&this.addSignalEvent(32795,"signal channel reconnect success"),this.emitConnectionStateChanged(XA),this.emitter_.emit(3)}}},{key:"onclose",value:function(e){var t=e.target.url,r=e.target===this.socketInUse_;this.log_.info("websocket[".concat(t," InUse: ").concat(r,"] is closed with code: ").concat(e.code)),e.target===this.socketInUse_&&(this.isConnected_=!1,this.emitConnectionStateChanged(YA),this.addSignalEvent(32790,"signal channel is disconnected"),e.wasClean&&1e3===e.code||(this.log_.warn("onclose code:".concat(e.code," reason:").concat(e.reason)),this.log_.warn("close current websocket and schedule a reconnect timeout"),this.socketInUse_.onclose=function(){},this.socketInUse_.close(4011),this.socket_=this.backupSocket_=this.socketInUse_=null,this.reconnect(VE)))}},{key:"onerror",value:function(e){var t=e.target.url;this.log_.error("websocket[".concat(t,"] error observed")),this.isConnected_?e.target===this.socketInUse_&&(this.isConnected_=!1,this.unbindAndCloseSocket(VE),this.unbindAndCloseSocket(FE),this.socketInUse_=null,this.reconnect(VE)):(this.isReconnecting_||dk.logFailedEvent({userId:this.client_.getUserId(),eventType:IT,code:ik.UNKNOWN}),e.target==this.socket_?(this.unbindAndCloseSocket(VE),this.reconnect(FE)):(this.unbindAndCloseSocket(FE),this.reconnect(VE))),this.isConnecting_=!1,this.isConnected_=!1}},{key:"onmessage",value:function(e){if(this.isConnected_){var t=JSON.parse(e.data),r=t.cmd,i=t.data,n=Object.values(ZA),s=Object.keys(ZA)[n.indexOf(r)],o=tk[s];switch(ek.includes(r)||(this.log_.debug("received msg: ".concat(e.data)),this.log_.info("Received event: [ ".concat(o||"unknown cmd: "+r," ]"))),r){case ZA.CHANNEL_SETUP_RESULT:if(0===t.code)this.signalInfo_.clientIp=i.clientIp,this.signalInfo_.signalIp=i.signalInnerIp,this.signalInfo_.tinyId=t.tinyId,i.svrTime&&function(e){Gg=e-(new Date).getTime();var t=new Date;t.setTime(e),Lw.info("baseTime from server: "+t+" offset: "+Gg)}(i.svrTime),this.log_.info("ChannelSetup Success"),dk.logSuccessEvent({userId:this.userId_,eventType:IT}),this.emitter_.emit(1,{signalInfo:this.signalInfo_});else{var a=new nk({code:ik.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:JR({key:"SIGNAL_CHANNEL_SETUP_FAILED",data:{errorCode:t.code,errorMsg:t.message}})});this.log_.error("".concat(t.code,", ").concat(t.message)),this.close(),dk.logFailedEvent({userId:this.userId_,eventType:IT,error:a}),this.emitter_.emit(5,a)}break;case ZA.JOIN_ROOM_RESULT:0===t.code&&(this.signalInfo_.relayIp=i.relayOuterIp,this.signalInfo_.relayInnerIp=i.relayInnerIp,this.signalInfo_.relayPort=i.relayPort,this.log_.info("signalIp:".concat(this.signalInfo_.signalIp," clientIp:").concat(this.signalInfo_.clientIp," relayIp: ").concat(this.signalInfo_.relayIp))),this.emitter_.emit(o,{data:t});break;case ZA.CHANNEL_RECONNECT_RESULT:0===t.code?(this.log_.warn("reconnect success"),this.stopReconnection(),dk.logSuccessEvent({userId:this.userId_,eventType:ET}),this.client_.syncUserList(),this.client_.checkConnectionsToReconnect()):(this.log_.warn("reconnect failed, ".concat(t.code," ").concat(t.message)),this.client_.reJoin());break;default:this.emitter_.emit(o,{data:t})}}}},{key:"addSignalEvent",value:function(e,t){ok(this.userId_,{eventId:e,eventDesc:t,timestamp:Hg(),userId:this.userId_,tinyId:this.signalInfo_.tinyId})}},{key:"reconnect",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:VE;if(this.isConnecting_||-1!==this.reconnectionTimer_)this.log_.info("signal channel is reconnecting, ignoring current reconnection");else{if(this.reconnectionCount_>=30){this.log_.warn("SDK has tried reconnect signal channel for ".concat(30," times, but all failed. please check your network"));var r=new nk({code:ik.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:JR({key:wR})});return dk.logFailedEvent({userId:this.client_.getUserId(),eventType:ET,error:r}),this.addSignalEvent(32796,"signal channel reconnect fail"),void this.emitter_.emit(4,r)}this.isConnecting_=!0,this.reconnectionCount_++,this.currentState_!==QA&&(this.emitConnectionStateChanged(QA),this.addSignalEvent(32794,"signal channel is reconnecting")),this.log_.warn("reconnecting to ".concat(t," signal channel [").concat(this.reconnectionCount_,"/").concat(30,"]"));var i=this.getReconnectionUrl(t);t===VE?(this.socket_=new WebSocket(i),this.bindSocket(this.socket_)):(this.backupSocket_=new WebSocket(i),this.bindSocket(this.backupSocket_));var n=tw(this.reconnectionCount_);this.reconnectionTimer_=setTimeout((function(){e.log_.warn("reconnect ".concat(t," signal channel timeout(").concat(n/1e3,"s), close and try again")),e.isConnecting_=!1,e.clearReconnectionTimer(),e.unbindAndCloseSocket(t),e.reconnect(t===VE?FE:VE)}),n)}}},{key:"isConnected",value:function(){return this.isConnected_}},{key:"isReconnecting_",get:function(){return-1!==this.reconnectionTimer_}},{key:"getReconnectionUrl",value:function(e){var t=e===VE?this.urlWithParam_:this.backupUrlWithParam_;if(!uk(this.signalInfo_)&&-1===t.indexOf("&rc=1")){var r=this.client_.getRoomId(),i=this.client_.getUseStringRoomId();t+="&rc=1&relayInnerIp=".concat(this.signalInfo_.relayInnerIp,"&relayOuterIp=").concat(this.signalInfo_.relayIp,"&relayPort=").concat(this.signalInfo_.relayPort,"&roomId=").concat(r,"&useStringRoomId=").concat(i)}return t}},{key:"send",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected_){var r={cmd:e,data:t,userId:this.userId_,tinyId:this.signalInfo_.tinyId,seq:++this.seq_};return this.socketInUse_.send(JSON.stringify(r)),r.seq}}},{key:"sendWaitForResponse",value:function(e){var t=this,r=e.command,i=e.data,n=e.timeout,s=void 0===n?5e3:n,o=e.responseCommand,a=e.commandDesc,c=e.enableLog,u=void 0===c||c;return new Promise((function(e,n){var c=setTimeout((function(){t.off(o,d);var e=new nk({code:ik.API_CALL_TIMEOUT,message:JR({key:"API_CALL_TIMEOUT",data:{commandDesc:a,command:r}})});u&&t.log_.warn(e),n(e)}),s),d=function r(i){i.data.seq===l&&(clearTimeout(c),t.off(o,r),e(i))};t.on(o,d);var l=t.send(r,i)}))}},{key:"sendWaitForResponseWithRetry",value:function(){var e=this,t=arguments.length<=0?void 0:arguments[0],r=t.commandDesc,i=t.command,n=t.retries,s=void 0===n?0:n,o=t.retryTimeout,a=void 0===o?0:o;return Mw({retryFunction:this.sendWaitForResponse,onRetrying:function(t){e.log_.warn("".concat(r||i," timeout observed, retrying [").concat(t,"/").concat(s,"]"))},settings:{retries:s,timeout:a},context:this}).apply(void 0,arguments)}},{key:"getCurrentState",value:function(){return this.currentState_}},{key:"getSignalInfo",value:function(){return this.signalInfo_}},{key:"stopReconnection",value:function(){this.isReconnecting_&&(this.reconnectionCount_=0,this.clearReconnectionTimer())}},{key:"close",value:function(){this.log_.info("close SignalChannel"),this.clearBackupTimer(),this.stopReconnection(),this.isConnecting_=!1,this.isConnected_=!1,this.socketInUse_=null,this.unbindAndCloseSocket(VE),this.unbindAndCloseSocket(FE),this.emitConnectionStateChanged(YA)}},{key:"on",value:function(e,t,r){this.emitter_.on(e,t,r)}},{key:"removeListener",value:function(e,t,r){this.emitter_.removeListener(e,t,r)}},{key:"once",value:function(e,t,r){this.emitter_.once(e,t,r)}},{key:"off",value:function(e,t,r){this.emitter_.off(e,t,r)}},{key:"emitConnectionStateChanged",value:function(e){e!==this.currentState_&&(this.emitter_.emit(2,{prevState:this.currentState_,state:e}),this.currentState_=e)}}]),e}(),hk=Sn,pk=ds.find,mk=ga,fk=!0;"find"in[]&&Array(1).find((function(){fk=!1})),hk({target:"Array",proto:!0,forced:fk},{find:function(e){return pk(this,e,arguments.length>1?arguments[1]:void 0)}}),mk("find");var gk={},vk={},yk={exports:{}},_k=yk.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(_k).forEach((function(e){_k[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(r[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},i=yk.exports,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,o,n)}})),t.media=s,t};var s=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}}(vk);var bk=yk.exports,Sk=/%[sdv%]/g,Ik=function(e){var t=1,r=arguments,i=r.length;return e.replace(Sk,(function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},Ek=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?i.push(r[t.name][s]):i.push(r[t.names[n]])}else i.push(r[t.name]);return Ik.apply(null,i)},Tk=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Rk=["i","c","b","a"],wk=vk;gk.write=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||Tk,i=t.innerOrder||Rk,n=[];return r.forEach((function(t){bk[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(Ek(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(Ek(t,r,e))}))}))})),e.media.forEach((function(e){n.push(Ek("m",bk.m[0],e)),i.forEach((function(t){bk[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(Ek(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(Ek(t,r,e))}))}))}))})),n.join("\r\n")+"\r\n"},gk.parse=wk.parse,gk.parseParams=wk.parseParams,gk.parseFmtpConfig=wk.parseFmtpConfig,gk.parsePayloads=wk.parsePayloads,gk.parseRemoteCandidates=wk.parseRemoteCandidates,gk.parseImageAttributes=wk.parseImageAttributes,gk.parseSimulcastStreamList=wk.parseSimulcastStreamList;var Ak=function(e){return gk.parse(e)},kk=function(e){return gk.write(e)},Ck=function(e){var t=Ak(e);return t.media.forEach((function(e){e.type===wE&&e.fmtp.forEach((function(e){e.config+=";sprop-stereo=1;stereo=1"}))})),kk(t)};function Mk(e){var t=Ak(e);return t.media.forEach((function(e){if(e.type===AE){var t=new Set;e.rtp.forEach((function(e){var r=e.payload;return"H264"===e.codec&&t.add(r)})),e.fmtp.forEach((function(e){var r=e.payload,i=e.config.match(/apt=(\d+)/);i&&i[1]&&t.has(Number(i[1]))&&t.add(r)}));var r=function(e){var r=e.payload;return!t.has(r)};e.rtp=e.rtp.filter(r),e.rtcpFb=e.rtcpFb.filter(r),e.fmtp=e.fmtp.filter(r),e.payloads=e.payloads.split(" ").filter((function(e){return!t.has(Number(e))})).join(" ")}})),kk(t)}var Ok,Pk,Lk,xk,Dk=Sn,Nk=te,$k=Ei,Uk=Hv,Bk=op,Vk=O,Fk=RangeError,jk=String,Wk=Math.floor,qk=Nk(Bk),Gk=Nk("".slice),Hk=Nk(1..toFixed),zk=function(e,t,r){return 0===t?r:t%2==1?zk(e,t-1,r*e):zk(e*e,t/2,r)},Jk=function(e,t,r){for(var i=-1,n=r;++i<6;)n+=t*e[i],e[i]=n%1e7,n=Wk(n/1e7)},Yk=function(e,t){for(var r=6,i=0;--r>=0;)i+=e[r],e[r]=Wk(i/t),i=i%t*1e7},Kk=function(e){for(var t=6,r="";--t>=0;)if(""!==r||0===t||0!==e[t]){var i=jk(e[t]);r=""===r?i:r+qk("0",7-i.length)+i}return r};Dk({target:"Number",proto:!0,forced:Vk((function(){return"0.000"!==Hk(8e-5,3)||"1"!==Hk(.9,0)||"1.25"!==Hk(1.255,2)||"1000000000000000128"!==Hk(0xde0b6b3a7640080,0)}))||!Vk((function(){Hk({})}))},{toFixed:function(e){var t,r,i,n,s=Uk(this),o=$k(e),a=[0,0,0,0,0,0],c="",u="0";if(o<0||o>20)throw Fk("Incorrect fraction digits");if(s!=s)return"NaN";if(s<=-1e21||s>=1e21)return jk(s);if(s<0&&(c="-",s=-s),s>1e-21)if(r=(t=function(e){for(var t=0,r=e;r>=4096;)t+=12,r/=4096;for(;r>=2;)t+=1,r/=2;return t}(s*zk(2,69,1))-69)<0?s*zk(2,-t,1):s/zk(2,t,1),r*=4503599627370496,(t=52-t)>0){for(Jk(a,0,r),i=o;i>=7;)Jk(a,1e7,0),i-=7;for(Jk(a,zk(10,i,1),0),i=t-1;i>=23;)Yk(a,1<<23),i-=23;Yk(a,1<<i),Jk(a,1,1),Yk(a,2),u=Kk(a)}else Jk(a,0,r),Jk(a,1<<-t,0),u=Kk(a)+qk("0",o);return o>0?c+((n=u.length)<=o?"0."+qk("0",o-n)+u:Gk(u,0,n-o)+"."+Gk(u,n-o)):c+u}});var Qk=(null===(Ok=window)||void 0===Ok?void 0:Ok.requestIdleCallback)||function(e){var t=Date.now();return setTimeout((function(){e({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})}),1e3)},Xk=(null===(Pk=window)||void 0===Pk?void 0:Pk.cancelIdleCallback)||function(e){clearTimeout(e)},Zk=(null===(Lk=window)||void 0===Lk?void 0:Lk.cancelAnimationFrame)||(null===(xk=window)||void 0===xk?void 0:xk.mozCancelAnimationFrame),eC=function(){function e(){a(this,e)}return u(e,null,[{key:"generateTaskID",value:function(){return this.currentTaskID++}},{key:"run",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mR,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=r(r({},e===pR?{delay:2e3,count:0,backgroundTask:!0}:e===lR?{delay:1e4,count:0}:e===hR?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0}),i),aw(t)&&(i=r(r({},i),t)),rw(e)&&(t=e,e=mR);var n=r({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID}},{key:"interval",value:function(e){var t=this;return e.intervalID=setInterval((function(){e.callback(),e.loopCount+=1,t.isBreakLoop(e)}),e.delay)}},{key:"timeout",value:function(e){var t=this;return e.timeoutID=setTimeout((function r(){if(e.callback(),e.loopCount+=1,!t.isBreakLoop(e))return e.timeoutID=setTimeout(r,e.delay)}),e.delay)}},{key:"ric",value:function(e){var t,r=this,i=hw();return e.ricID=Qk((function n(){if((t=hw()-i)>=e.delay&&(i=hw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!r.isBreakLoop(e))return e.ricID=Qk(n,{timeout:e.delay})}),{timeout:e.delay})}},{key:"raf",value:function(e){var t=this;e.delay=(1e3/e.fps).toFixed(2);var r,i=hw(),n=function n(){if(document.hidden&&e.backgroundTask){if(r=hw()-i,i=hw(),e.callback(),e.loopCount+=1,t.isBreakLoop(e))return;return e.timeoutID=setTimeout(n,e.delay-Math.floor(r%e.delay))}if((r=hw()-i)>=e.delay&&(i=hw()-Math.floor(r%e.delay),e.callback(),e.loopCount+=1),!t.isBreakLoop(e))return e.rafID=requestAnimationFrame(n)};if(e.rafID=requestAnimationFrame(n),e.backgroundTask){var s=function(){if(document.hidden){var t=hw()-i;t>=e.delay?n():e.timeoutID=setTimeout(n,e.delay-t)}};document.addEventListener("visibilitychange",s),e.onVisibilitychange=s,document.hidden&&s()}return e.taskID}},{key:"hasTask",value:function(e){return this.taskMap.has(e)}},{key:"clearTask",value:function(e){if(!this.taskMap.has(e))return!0;var t=this.taskMap.get(e),r=t.intervalID,i=t.timeoutID,n=t.rafID,s=t.ricID,o=t.onVisibilitychange;return r&&clearInterval(r),i&&clearTimeout(i),n&&Zk(n),s&&Xk(s),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}},{key:"isBreakLoop",value:function(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}}]),e}();d(eC,"taskMap",new Map),d(eC,"currentTaskID",1);var tC=new(function(){function e(){a(this,e),this.prefix_="TRTC",this.queue_=new Map,this.checkStorage()}return u(e,[{key:"getRealKey",value:function(e){return"".concat(this.prefix_,"_").concat(e)}},{key:"checkStorage",value:function(){var e=this;SE()&&Object.keys(localStorage).filter((function(t){if(t.startsWith(e.prefix_)){var r=JSON.parse(localStorage.getItem(t));if(r&&r.expiresIn<Date.now())return!0}return!1})).forEach((function(e){return localStorage.removeItem(e)}))}},{key:"doFlush",value:function(){if(SE())try{var e,t=R(this.queue_);try{for(t.s();!(e=t.n()).done;){var r=S(e.value,2),i=r[0],n=r[1];localStorage.setItem(i,JSON.stringify(n))}}catch(e){t.e(e)}finally{t.f()}}catch(e){Lw.warn(e)}}},{key:"getItem",value:function(e){if(!SE())return null;try{var t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){Lw.warn(e)}}},{key:"setItem",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(SE())try{var i={expiresIn:Date.now()+HT,value:t};r?localStorage.setItem(this.getRealKey(e),JSON.stringify(i)):(this.queue_.set(this.getRealKey(e),i),eC.hasTask(this.intervalId_)||(this.intervalId_=eC.run(lR,this.doFlush.bind(this),{count:1})))}catch(e){Lw.warn(e)}}},{key:"deleteItem",value:function(e){if(!SE())return!1;try{return e=this.getRealKey(e),this.queue_.delete(e),localStorage.removeItem(e),!0}catch(e){return Lw.warn(e),!1}}},{key:"clear",value:function(){if(SE())try{localStorage.clear()}catch(e){Lw.warn(e)}}}]),e}()),rC={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isMediaDevicesSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},iC="checkResult",nC=function(){return!(JI||II||TI&&RI<80||bI&&SI<56)},sC=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((function(e){return e in window})).length>0},oC=function(){if(!navigator.mediaDevices)return!1;var e=["getUserMedia","enumerateDevices"];return e.filter((function(e){return e in navigator.mediaDevices})).length===e.length},aC=function(){var e=o(i().mark((function e(){var t,r,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!rC.detail.isH264EncodeSupported||!rC.detail.isVp8EncodeSupported){e.next=2;break}return e.abrupt("return",{isH264EncodeSupported:rC.detail.isH264EncodeSupported,isVp8EncodeSupported:rC.detail.isVp8EncodeSupported});case 2:return t="",r=!1,n=!1,e.prev=5,s=new RTCPeerConnection,(o=document.createElement("canvas")).getContext("2d"),a=o.captureStream(0),s.addTrack(a.getVideoTracks()[0],a),e.next=13,s.createOffer();case 13:return-1!==(t=e.sent).sdp.toLowerCase().indexOf("h264")&&(r=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(n=!0),s.close(),rC.detail.isH264EncodeSupported=r,rC.detail.isVp8EncodeSupported=n,e.abrupt("return",{isH264EncodeSupported:rC.detail.isH264EncodeSupported,isVp8EncodeSupported:rC.detail.isVp8EncodeSupported});case 22:return e.prev=22,e.t0=e.catch(5),e.abrupt("return",{isH264EncodeSupported:!1,isVp8EncodeSupported:!1});case 25:case"end":return e.stop()}}),e,null,[[5,22]])})));return function(){return e.apply(this,arguments)}}();function cC(){return uC.apply(this,arguments)}function uC(){return(uC=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",new Promise(function(){var e=o(i().mark((function e(t){var r,n,s,a,c,u,d,l,h,p,m,f,g,v;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={encode:!1,decode:!1},n=null,e.prev=2,s=document.createElement("canvas"),a=s.getContext("2d"),s.width=640,s.height=480,c=setInterval((function(){a.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),33),u=-1,d=-1,n=function(){clearInterval(u),clearInterval(c),clearTimeout(d),h.close(),p.close(),l.getTracks().forEach((function(e){return e.stop()}))},d=setTimeout((function(){n(),t(r)}),3e3),l=s.captureStream(),h=new RTCPeerConnection({}),p=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),h.addEventListener("icecandidate",(function(e){return p.addIceCandidate(e.candidate)})),p.addEventListener("icecandidate",(function(e){return h.addIceCandidate(e.candidate)})),h.addTrack(l.getVideoTracks()[0],l),e.next=20,h.createOffer();case 20:return m=e.sent,e.next=23,h.setLocalDescription(m);case 23:return e.next=25,p.setRemoteDescription(m);case 25:return e.next=27,p.createAnswer();case 27:return f=e.sent,g=Ak(f.sdp),v=g.media[0].rtp.findIndex((function(e){return"H264"===e.codec})),g.media[0].rtp=[g.media[0].rtp[v]],g.media[0].fmtp=g.media[0].fmtp.filter((function(e){return e.payload===g.media[0].rtp[0].payload})),g.media[0].rtcpFb=g.media[0].rtcpFb.filter((function(e){return e.payload===g.media[0].rtp[0].payload})),f.sdp=kk(g),e.next=36,p.setLocalDescription(f);case 36:return e.next=38,h.setRemoteDescription(f);case 38:u=setInterval(o(i().mark((function e(){var s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r.encode&&r.decode&&(n(),t(r)),e.next=3,h.getStats();case 3:return s=e.sent,e.next=6,p.getStats();case 6:o=e.sent,r.encode||s.forEach((function(e){"outbound-rtp"===e.type&&e.mediaType===AE&&e.framesEncoded>0&&(r.encode=!0)})),r.decode||o.forEach((function(e){"inbound-rtp"===e.type&&e.mediaType===AE&&e.framesDecoded>0&&(r.decode=!0)}));case 9:case"end":return e.stop()}}),e)}))),500),e.next=46;break;case 41:e.prev=41,e.t0=e.catch(2),n(),Lw.warn(e.t0),t(r);case 46:case"end":return e.stop()}}),e,null,[[2,41]])})));return function(t){return e.apply(this,arguments)}}()));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var dC=function(){var e=o(i().mark((function e(){var t,r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!rC.detail.isH264DecodeSupported||!rC.detail.isVp8DecodeSupported){e.next=2;break}return e.abrupt("return",{isH264DecodeSupported:rC.detail.isH264DecodeSupported,isVp8DecodeSupported:rC.detail.isVp8DecodeSupported});case 2:return t="",r=!1,n=!1,e.prev=5,s=new RTCPeerConnection,e.next=9,s.createOffer({offerToReceiveAudio:1,offerToReceiveVideo:1});case 9:return-1!==(t=e.sent).sdp.toLowerCase().indexOf("h264")&&(r=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(n=!0),s.close(),e.abrupt("return",{isH264DecodeSupported:r,isVp8DecodeSupported:n});case 16:return e.prev=16,e.t0=e.catch(5),e.abrupt("return",{isH264DecodeSupported:!1,isVp8DecodeSupported:!1});case 19:case"end":return e.stop()}}),e,null,[[5,16]])})));return function(){return e.apply(this,arguments)}}(),lC=function(e,t){var r=null;return function(){if(r)return r;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return(r=e.apply(this,i)).then((function(e){return r=null,e})).catch((function(e){throw r=null,e})),r}}(function(){var e=o(i().mark((function e(){var t,r,n,s,o,a,c,u,d,l,h,p,m;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(hC()){e.next=2;break}return e.abrupt("return",rC);case 2:return t=nC(),r=sC(),n=oC(),e.next=7,aC();case 7:return s=e.sent,o=s.isH264EncodeSupported,a=s.isVp8EncodeSupported,e.next=12,dC();case 12:if(c=e.sent,u=c.isH264DecodeSupported,d=c.isVp8DecodeSupported,o&&a){e.next=21;break}return e.next=18,aC();case 18:l=e.sent,o=l.isH264EncodeSupported,a=l.isVp8EncodeSupported;case 21:if(!(o&&u&&(nE||oE||fE)&&!MI&&cE()<79)){e.next=29;break}return e.next=24,cC();case 24:h=e.sent,p=h.encode,m=h.decode,o=p,u=m;case 29:return rC.result=t&&r&&n&&(o||a)&&(u||d),rC.detail.isBrowserSupported=t,rC.detail.isWebRTCSupported=r,rC.detail.isMediaDevicesSupported=n,rC.detail.isH264EncodeSupported=o,rC.detail.isVp8EncodeSupported=a,rC.detail.isH264DecodeSupported=u,rC.detail.isVp8DecodeSupported=d,hC()&&(Lw.warn(JR({key:UR})),Lw.info("".concat(navigator.userAgent," ").concat(JSON.stringify(rC.detail)))),tC.setItem(iC,{ua:navigator.userAgent,checkResult:rC},!0),e.abrupt("return",rC);case 40:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}());function hC(){return Object.keys(rC.detail).findIndex((function(e){return!rC.detail[e]}))>=0}function pC(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)}function mC(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function fC(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function gC(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function vC(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function yC(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&fC()}function _C(){return!!iw(navigator.mediaDevices)&&(Lw.error(HR.NOT_SUPPORTED_MEDIA),!0)}function bC(){return"http:"===location.protocol&&!bE&&(Lw.warn(JR({key:$R})),!0)}var SC="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&cE()>=86;function IC(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state||ow(e.selected)&&!e.selected)}var EC=new Map([[_I,"Android"],[yI,"iOS"],[GI,"Windows"],[HI,"MacOS"],[zI,"Linux"]]);function TC(){var e="unknown";return EC.get(!0)&&(e=EC.get(!0)),e}function RC(){var e="";return screen.width&&(e+=(screen.width?screen.width*window.devicePixelRatio:"")+" * "+(screen.height?screen.height*window.devicePixelRatio:"")),e}function wC(){var e=!1;return(navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)&&(e=!0),e}function AC(){for(var e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"],r=0;r<t.length;r++)if(t[r]in window){e.isSupported=!0;break}return e.isSupported}function kC(){return!xI&&!yI&&!(!nC()||!("captureStream"in HTMLCanvasElement.prototype))}var CC=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,MC=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,OC=function(){var e,t,r;return(null===(e=window)||void 0===e?void 0:e.OffscreenCanvas)&&(null===(t=window)||void 0===t?void 0:t.MediaStreamTrackProcessor)&&(null===(r=window)||void 0===r?void 0:r.MediaStreamTrackGenerator)};!function(){bC();var e=tC.getItem(iC);e&&e.ua===navigator.userAgent&&(rC=e.checkResult),lC()}();var PC,LC="stream-added",xC="stream-removed",DC="stream-updated",NC="stream-subscribed",$C="error",UC="connection-state-changed",BC=jE,VC="stream-added",FC="stream-removed",jC="stream-updated",WC="stream-subscribed",qC="connection-state-changed",GC="peer-join",HC="peer-leave",zC="mute-audio",JC="mute-video",YC="unmute-audio",KC="unmute-video",QC="client-banned",XC="network-quality",ZC="audio-volume",eM=jE,tM="error",rM="player-state-changed",iM="error",nM="player-state-changed",sM=function(){function e(t){a(this,e);var r=t.getUserId();this.log_=Lw.createLogger({id:r,userId:r,sdkAppId:t.getSDKAppId()}),this.prevReportTime_=0,this.prevReport_={},this.prevEncoderImplementation_="",this.prevQualityLimitationReason_="",this.prevDecoderImplementationMap_=new Map}var t,r,n,s;return u(e,[{key:"statInterval",get:function(){return 0===this.prevReportTime_?2:(Date.now()-this.prevReportTime_)/1e3}},{key:"getSenderStats",value:(s=o(i().mark((function e(t){var r,n,s,o=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0,smallFramesEncoded:0,smallFPSCapture:0,smallFramesSent:0},rtt:0},n=t.getPeerConnection(),s=t.getSSRC(),!n){e.next=14;break}return e.prev=4,e.next=7,n.getStats();case 7:e.sent.forEach((function(e){if("outbound-rtp"===e.type)if(e.mediaType===AE){if(!bI&&iw(e.trackId))return;e.ssrc!==s.video||iw(e.encoderImplementation)||o.prevEncoderImplementation_===e.encoderImplementation||(o.log_.info("encoderImplementation change to ".concat(e.encoderImplementation)),o.prevEncoderImplementation_=e.encoderImplementation),e.ssrc!==s.video||iw(e.qualityLimitationReason)||o.prevQualityLimitationReason_===e.qualityLimitationReason||(o.log_.info("qualityLimitationReason change to ".concat(e.qualityLimitationReason)),o.prevQualityLimitationReason_=e.qualityLimitationReason);var i=t.getSSRC();e.ssrc===i.video?(r.video.bytesSent=e.bytesSent,r.video.packetsSent=e.packetsSent,r.video.framesEncoded=e.framesEncoded):(r.video.smallBytesSent=e.bytesSent,r.video.smallFramesEncoded=e.framesEncoded)}else e.mediaType===wE&&(r.audio.bytesSent=e.bytesSent,r.audio.packetsSent=e.packetsSent);else if("candidate-pair"===e.type)IC(e)&&sw(e.currentRoundTripTime)&&(r.rtt=Math.floor(1e3*e.currentRoundTripTime));else if("track"===e.type){var n;iw(e.frameWidth)||(e.trackIdentifier===t.getLocalStreamVideoTrackId()?(r.video.frameWidth=e.frameWidth,r.video.frameHeight=e.frameHeight,r.video.framesSent=e.framesSent):(r.video.smallFrameWidth=e.frameWidth,r.video.smallFrameHeight=e.frameHeight,r.video.smallFramesSent=e.framesSent)),iw(e.audioLevel)?pE&&(r.audio.audioLevel=(null===(n=t.getLocalStream())||void 0===n?void 0:n.getInternalAudioLevel())||0):r.audio.audioLevel=e.audioLevel||0}else"media-source"===e.type&&(e.kind===wE?(r.audio.audioLevel=e.audioLevel||0,r.audio.totalAudioEnergy=e.totalAudioEnergy||0):e.kind===AE&&(e.trackIdentifier===t.getLocalStreamVideoTrackId()?r.video.fpsCapture=e.framesPerSecond:r.video.smallFPSCapture=e.framesPerSecond))})),e.next=14;break;case 11:e.prev=11,e.t0=e.catch(4),this.log_.warn("failed to getStats on sender connection "+e.t0);case 14:return e.abrupt("return",r);case 15:case"end":return e.stop()}}),e,this,[[4,11]])}))),function(e){return s.apply(this,arguments)})},{key:"getReceiverStats",value:(n=o(i().mark((function e(t){var r,n,s=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r={tinyId:t.getTinyId(),userId:t.getUserId(),rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0}},!(n=t.getPeerConnection())){e.next=13;break}return e.prev=3,e.next=6,n.getStats();case 6:e.sent.forEach((function(e){if("inbound-rtp"===e.type){if(e.mediaType===wE)r.audio.packetsReceived=e.packetsReceived,r.audio.bytesReceived=e.bytesReceived,r.audio.packetsLost=e.packetsLost,r.audio.jitter=e.jitter,r.hasAudio=!0;else if(e.mediaType===AE){if(bI&&0===e.bytesReceived)return;var i=t.getSSRC();e.ssrc===i.video&&(r.video.packetsReceived=e.packetsReceived,r.video.bytesReceived=e.bytesReceived,r.video.packetsLost=e.packetsLost,r.video.framesReceived=e.framesReceived,r.video.framesDecoded=e.framesDecoded,r.video.fpsDecoded=e.framesPerSecond,r.hasVideo=!0,!e.decoderImplementation||s.prevDecoderImplementationMap_.has(r.userId)&&s.prevDecoderImplementationMap_.get(r.userId)===e.decoderImplementation||(s.log_.info("".concat(r.userId," decoderImplementation change to ").concat(e.decoderImplementation)),s.prevDecoderImplementationMap_.set(r.userId,e.decoderImplementation))),e.ssrc===i.auxiliary&&(r.auxiliary.packetsReceived=e.packetsReceived,r.auxiliary.bytesReceived=e.bytesReceived,r.auxiliary.packetsLost=e.packetsLost,r.auxiliary.framesReceived=e.framesReceived,r.auxiliary.framesDecoded=e.framesDecoded,r.auxiliary.fpsDecoded=e.framesPerSecond,r.hasAuxiliary=!0)}}else"track"===e.type?(iw(e.frameWidth)||(e.trackIdentifier===t.getMainStreamVideoTrackId()&&(r.video.frameWidth=e.frameWidth,r.video.frameHeight=e.frameHeight),e.trackIdentifier===t.getAuxStreamVideoTrackId()&&(r.auxiliary.frameWidth=e.frameWidth,r.auxiliary.frameHeight=e.frameHeight)),iw(e.audioLevel)||(r.audio.audioLevel=e.audioLevel||0,r.audio.totalAudioEnergy=e.totalAudioEnergy||0)):"candidate-pair"===e.type&&IC(e)&&sw(e.currentRoundTripTime)&&(r.rtt=Math.floor(1e3*e.currentRoundTripTime))})),e.next=13;break;case 10:e.prev=10,e.t0=e.catch(3),this.log_.warn("failed to getStats on receiver connection "+e.t0);case 13:return e.abrupt("return",r);case 14:case"end":return e.stop()}}),e,this,[[3,10]])}))),function(e){return n.apply(this,arguments)})},{key:"getStats",value:(r=o(i().mark((function e(t,r){var n,s,o,a,c,u,d;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n={},!t){e.next=5;break}return e.next=4,this.getSenderStats(t);case 4:n=e.sent;case 5:s=[],o=R(r),e.prev=7,o.s();case 9:if((a=o.n()).done){e.next=17;break}return(c=S(a.value,2))[0],u=c[1],e.next=13,this.getReceiverStats(u);case 13:d=e.sent,s.push(d);case 15:e.next=9;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(7),o.e(e.t0);case 22:return e.prev=22,o.f(),e.finish(22);case 25:return e.abrupt("return",{senderStats:n,receiverStats:s});case 26:case"end":return e.stop()}}),e,this,[[7,19,22,25]])}))),function(e,t){return r.apply(this,arguments)})},{key:"getDifferenceValue",value:function(e,t){if(uk(e))return t;var r=t-e;return r<0?0:r}},{key:"prepareReport",value:function(e){var t=this,r=e.stats,i=e.report,n=e.freezeMap;if(!uk(r.senderStats)){var s={uint32_audio_level:1e8*r.senderStats.audio.audioLevel,uint32_audio_energy:1e6*r.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:r.senderStats.audio.bytesSent,audioLevel:r.senderStats.audio.audioLevel},o=[],a={uint32_video_stream_type:2,uint32_video_codec_fps:r.senderStats.video.framesSent,uint32_video_capture_fps:r.senderStats.video.fpsCapture,uint32_video_width:r.senderStats.video.frameWidth,uint32_video_height:r.senderStats.video.frameHeight,uint32_video_codec_bitrate:r.senderStats.video.bytesSent,uint32_video_enc_fps:r.senderStats.video.framesEncoded};if(o.push(a),r.senderStats.video.smallBytesSent){var c={uint32_video_stream_type:3,uint32_video_codec_fps:r.senderStats.video.smallFramesSent||0,uint32_video_capture_fps:r.senderStats.video.smallFPSCapture||0,uint32_video_width:r.senderStats.video.smallFrameWidth||0,uint32_video_height:r.senderStats.video.smallFrameHeight||0,uint32_video_codec_bitrate:r.senderStats.video.smallBytesSent,uint32_video_enc_fps:r.senderStats.video.smallFramesEncoded||0};o.push(c)}var u={uint32_bitrate:"",uint32_rtt:r.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:s,msg_video_status:o,msg_network_status:u}}var d=this.statInterval;i.msg_down_stream_info=[],r.receiverStats.forEach((function(e){var t={};if(t.msg_user_info={str_identifier:e.userId,uint64_tinyid:e.tinyId},t.msg_network_status={uint32_rtt:e.rtt},t.msg_video_status={},e.hasAudio){var r={uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost,audioLevel:e.audio.audioLevel};t.msg_audio_status=r}if(t.msg_video_status=[],e.hasVideo){var s=n.get(e.userId+"_"+eT),o=s?s.duration:0,a={uint32_video_stream_type:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:o,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(a)}if(e.hasAuxiliary){var c=n.get(e.userId+"_"+tT),u=c?c.duration:0,d={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:u,uint32_video_dec_fps:e.auxiliary.framesDecoded};t.msg_video_status.push(d)}i.msg_down_stream_info.push(t)}));var l=this.prevReport_;this.prevReport_=JSON.parse(JSON.stringify(i));var h=l.msg_up_stream_info.msg_audio_status,p=i.msg_up_stream_info.msg_audio_status,m=this.getDifferenceValue(h.uint32_audio_codec_bitrate,p.uint32_audio_codec_bitrate);p.uint32_audio_codec_bitrate=Math.round(8*m/d);var f=l.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((function(e,r){var i=f[r],n=0,s=0,o=0;i&&(n=i.uint32_video_codec_bitrate,s=i.uint32_video_enc_fps,o=i.uint32_video_codec_fps);var a=t.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/d),e.uint32_video_enc_fps=Math.round(t.getDifferenceValue(s,e.uint32_video_enc_fps)/d),e.uint32_video_codec_fps=Math.round(t.getDifferenceValue(o,e.uint32_video_codec_fps)/d)}));var g=i.msg_down_stream_info,v=l.msg_down_stream_info;return g.forEach((function(e){var r=v.find((function(t){return t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid}));if(r){if(e.msg_audio_status&&r.msg_audio_status){var i=e.msg_audio_status,n=r.msg_audio_status;i.uint32_audio_origin_lost=t.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=t.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;var s=t.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*s/d),i.uint32_audio_total_bitrate=Math.round(8*s/d)}if(e.msg_video_status&&r.msg_video_status){var o=e.msg_video_status,a=r.msg_video_status;o.forEach((function(e,r){var i=a[r],n=0,s=0,o=0,c=0,u=0;i&&(n=i.uint32_video_receive,s=i.uint32_video_origin_lost,o=i.uint32_video_codec_bitrate,c=i.uint32_video_receive_fps,u=i.uint32_video_dec_fps),e.uint32_video_origin_lost=t.getDifferenceValue(s,e.uint32_video_origin_lost),e.uint32_video_receive=t.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;var l=t.getDifferenceValue(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/d);var h=t.getDifferenceValue(c,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(h/d),e.uint32_video_dec_fps=Math.round(t.getDifferenceValue(u,e.uint32_video_dec_fps)/d)}))}}})),i.msg_up_stream_info.msg_network_status.uint32_bitrate=i.msg_up_stream_info.msg_audio_status.uint32_audio_codec_bitrate+i.msg_up_stream_info.msg_video_status[0].uint32_video_codec_bitrate,i}},{key:"getStatsReport",value:(t=o(i().mark((function e(t){var r,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.uplinkConnection,n=t.downlinkConnections,s=t.freezeMap,o={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,audioLevel:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_codec_fps:0,uint32_video_capture_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_final_lost:0,uint32_video_enc_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0},msg_qos:[{uint32_video_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_bitrate:0,uint32_audio_bitrate:0,uint32_video_stream_type:0}]},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:""},msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0,audioLevel:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0,uint32_jitter:0},msg_qos:[{uint32_video_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_bitrate:0,uint32_audio_bitrate:0,uint32_video_stream_type:0}]}]},e.next=4,this.getStats(r,n);case 4:return a=e.sent,"{}"===JSON.stringify(this.prevReport_)&&(this.prevReport_=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:a,report:o,freezeMap:s}),this.prevReportTime_=Date.now(),e.abrupt("return",o);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"reset",value:function(){this.prevReportTime_=0,this.prevReport_={},this.prevEncoderImplementation_="",this.prevQualityLimitationReason_="",this.prevDecoderImplementationMap_=new Map}}]),e}(),oM=function(){function e(t){var r=t.signalChannel,i=t.connections,n=t.client;a(this,e),this.client_=n,this.signalChannel_=r,this.connections_=i,this.client_=n,this.log_=Lw.createLogger({id:"q|"+this.client_.getUserId(),userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId()}),this.uplinkConnection_=null,this.uplinkNetworkQuality_=0,this.uplinkRTT_=0,this.uplinkLoss_=0,this.downlinkNetworkQuality_=0,this.downlinkRTT_=0,this.downlinkLoss_=0,this.downlinkPrevStatMap_=new Map,this.downlinkLossAndRTTMap_=new Map,this.interval_=-1,this.emitter_=new Rw,this.initialize()}var t,r;return u(e,[{key:"uplinkNetworkQuality",get:function(){return this.uplinkNetworkQuality_},set:function(e){e!==this.uplinkNetworkQuality_&&this.log_.info("uplink network quality change ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT_,", loss: ").concat(this.uplinkLoss_)),this.uplinkNetworkQuality_=e}},{key:"downlinkNetworkQuality",get:function(){return this.downlinkNetworkQuality_},set:function(e){if(e!==this.downlinkNetworkQuality_){var t=this.getAverageLossAndRTT(I(this.downlinkLossAndRTTMap_.values())),r=t.rtt,i=t.loss;this.log_.info("downlink network quality change ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(r,", loss: ").concat(i))}this.downlinkNetworkQuality_=e}},{key:"initialize",value:function(){var e=this;this.signalChannel_.on(tk.UPLINK_NETWORK_STATS,(function(t){e.handleUplinkNetworkQuality(t)})),this.signalChannel_.on(2,this.handleSignalConnectionStateChange.bind(this)),this.start()}},{key:"handleUplinkNetworkQuality",value:function(e){if(!this.uplinkConnection_)return this.uplinkNetworkQuality=0,this.uplinkLoss_=0,void(this.uplinkRTT_=0);var t=this.uplinkConnection_.getPeerConnection();if(t&&this.isPeerConnectionDisconnected(t))return this.uplinkNetworkQuality=6,this.uplinkLoss_=0,void(this.uplinkRTT_=0);if(0===e.data.code){var r=e.data.data,i=r.expectAudPkg+r.expectVidPkg,n=r.recvAudPkg+r.recvVidPkg,s=i-n,o=r.delay;if(o&&this.updateDelay(o),0===i&&0===n)return;this.uplinkLoss_=s<=0?0:Math.round(s/i*100),this.uplinkRTT_=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss_,this.uplinkRTT_)}}},{key:"handleDownlinkNetworkQuality",value:(r=o(i().mark((function e(){var t,r,n,s,o,a,c,u,d,l,h,p,m,f,g,v=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.connections_&&0!==this.connections_.size){e.next=3;break}return this.downlinkNetworkQuality=0,e.abrupt("return");case 3:if(t=I(this.connections_.values()),r=t.filter((function(e){return e.getPeerConnection()&&e.getPeerConnection().connectionState===uT})),t.filter((function(e){return e.getPeerConnection()&&v.isPeerConnectionDisconnected(e.getPeerConnection())})).length!==t.length){e.next=9;break}return this.downlinkNetworkQuality=6,e.abrupt("return");case 9:n=0;case 10:if(!(n<r.length)){e.next=31;break}return s=r[n].getPeerConnection(),e.next=14,this.getStat(s);case 14:if(o=e.sent,a=o.rtt,c=o.totalPacketsLost,u=o.totalPacketsReceived,this.downlinkPrevStatMap_.has(s)){e.next=21;break}return this.downlinkPrevStatMap_.set(s,{totalPacketsLost:c,totalPacketsReceived:u}),e.abrupt("continue",28);case 21:l=this.downlinkPrevStatMap_.get(s),h=c-l.totalPacketsLost,p=u-l.totalPacketsReceived,d=h<=0||p<0?0:Math.round(h/(h+p)*100),this.downlinkPrevStatMap_.set(s,{totalPacketsLost:c,totalPacketsReceived:u}),this.downlinkLossAndRTTMap_.set(s,{rtt:a,loss:d,userId:r[n].getUserId()});case 28:n++,e.next=10;break;case 31:if(I(this.downlinkPrevStatMap_.keys()).forEach((function(e){v.isPeerConnectionDisconnected(e)&&(v.downlinkPrevStatMap_.delete(e),v.downlinkLossAndRTTMap_.delete(e))})),0!==this.downlinkLossAndRTTMap_.size){e.next=34;break}return e.abrupt("return");case 34:m=this.getAverageLossAndRTT(I(this.downlinkLossAndRTTMap_.values())),f=m.rtt,g=m.loss,this.downlinkRTT_=f,this.downlinkLoss_=g,this.downlinkNetworkQuality=this.getNetworkQuality(g,f);case 38:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"getStat",value:(t=o(i().mark((function e(t){var r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r={rtt:0,totalPacketsLost:0,totalPacketsReceived:0},t&&mC()){e.next=3;break}return e.abrupt("return",r);case 3:n=t.getReceivers(),e.prev=4,s=0;case 6:if(!(s<n.length)){e.next=15;break}return o=n[s],e.next=10,o.getStats();case 10:e.sent.forEach((function(e){"candidate-pair"===e.type&&sw(e.currentRoundTripTime)&&(r.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"!==e.type||e.mediaType!==wE&&e.mediaType!==AE||(r.totalPacketsLost+=e.packetsLost,r.totalPacketsReceived+=e.packetsReceived)}));case 12:s++,e.next=6;break;case 15:return e.abrupt("return",r);case 18:return e.prev=18,e.t0=e.catch(4),e.abrupt("return",r);case 21:case"end":return e.stop()}}),e,null,[[4,18]])}))),function(e){return t.apply(this,arguments)})},{key:"getAverageLossAndRTT",value:function(e){var t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((function(e){t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((function(r){t[r]=Math.round(t[r]/e.length)}))),t}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}},{key:"handleSignalConnectionStateChange",value:function(e){e.state===YA?(this.uplinkRTT_=0,this.uplinkLoss_=0,this.uplinkNetworkQuality=6):e.state===XA&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}},{key:"handleUplinkConnectionStateChange",value:function(e){var t=e.state;t===iT?(this.uplinkLoss_=0,this.uplinkRTT_=0,this.uplinkNetworkQuality=6):t===oT&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}},{key:"isPeerConnectionDisconnected",value:function(e){return!(!e||"disconnected"!==e.connectionState&&"failed"!==e.connectionState&&e.connectionState!==cT)}},{key:"setUplinkConnection",value:function(e){this.uplinkConnection_=e,this.uplinkConnection_?this.uplinkConnection_.on(UC,this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT_=0,this.uplinkLoss_=0)}},{key:"start",value:function(){var e=this;-1===this.interval_?(this.log_.info("start network quality calculating"),this.interval_=eC.run(lR,(function(){e.handleDownlinkNetworkQuality(),ww.emit(300,{client:e.client_,uplinkNetworkQuality:e.uplinkNetworkQuality,downlinkNetworkQuality:e.downlinkNetworkQuality,uplinkRTT:e.uplinkRTT_,uplinkLoss:e.uplinkLoss_,downlinkRTT:e.downlinkRTT_,downlinkLoss:e.downlinkLoss_,downlinkLossAndRTTMap:e.downlinkLossAndRTTMap_}),e.emitter_.emit(XC,{uplinkNetworkQuality:e.uplinkNetworkQuality,downlinkNetworkQuality:e.downlinkNetworkQuality,uplinkRTT:e.uplinkRTT_,uplinkLoss:e.uplinkLoss_,downlinkRTT:e.downlinkRTT_,downlinkLoss:e.downlinkLoss_})}),{delay:2e3})):this.log_.info("network quality calculating is already started")}},{key:"stop",value:function(){this.log_.info("stop network quality calculating"),-1!==this.interval_&&(eC.clearTask(this.interval_),this.interval_=-1),this.downlinkLossAndRTTMap_.clear(),this.downlinkPrevStatMap_.clear()}},{key:"on",value:function(e,t){this.emitter_.on(e,t)}},{key:"updateDelay",value:function(e){var t=this;e.forEach((function(e){var r=e.srcTinyId,i=e.videoDelay,n=e.audioDelay,s=t.connections_.get(r);s&&s.setDelay({videoDelay:i,audioDelay:n})}))}}]),e}(),aM=function(){function e(t){a(this,e),this.log_=Lw.createLogger({id:t.client.getUserId(),userId:t.client.getUserId(),sdkAppId:t.client.getSDKAppId()}),this.localStream_=null,this.prevDevices_=[],this.initialize()}var t,r;return u(e,[{key:"initialize",value:function(){navigator.mediaDevices&&(this.onDeviceChange=this.onDeviceChange.bind(this),navigator.mediaDevices.addEventListener("devicechange",this.onDeviceChange))}},{key:"destroy",value:function(){navigator.mediaDevices&&navigator.mediaDevices.removeEventListener("devicechange",this.onDeviceChange)}},{key:"onDeviceChange",value:(r=o(i().mark((function e(){var t,r,n,s=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.localStream_&&this.localStream_.getMediaStream()&&!this.localStream_.getScreen()){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,KF.getDevices();case 4:t=e.sent,r=t.filter((function(e){return s.prevDevices_.findIndex((function(t){var r=t.deviceId;return e.deviceId===r}))<0})),n=this.prevDevices_.filter((function(e){return t.findIndex((function(t){var r=t.deviceId;return e.deviceId===r}))<0})),r.length>0&&this.handleDeviceAdded(this.prevDevices_,r),n.length>0&&this.handleDeviceRemoved(t,n),this.prevDevices_=t;case 10:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"setLocalStream",value:(t=o(i().mark((function e(t){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t){e.next=4;break}return e.next=3,KF.getDevices();case 3:this.prevDevices_=e.sent;case 4:this.localStream_=t;case 5:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"handleDeviceAdded",value:function(e,t){var r,i;this.log_.warn("devicesAdded: ".concat(JSON.stringify(t))),this.localStream_.updateDeviceIdInUse();var n=t.filter((function(e){return e.kind===BE})),s=t.filter((function(e){return e.kind===UE})),o=e.filter((function(e){return e.kind===BE})),a=e.filter((function(e){return e.kind===UE})),c=n.length>0&&0===o.length&&"live"!==(null===(r=this.localStream_.getVideoTrack())||void 0===r?void 0:r.readyState),u=s.length>0&&0===a.length&&"live"!==(null===(i=this.localStream_.getAudioTrack())||void 0===i?void 0:i.readyState);if(u&&c)return this.log_.info("new microphone and camera detected, but there was no device before."),void this.localStream_.recoverCapture({audio:!0,video:!0,cameraId:n[0].deviceId,microphoneId:s[0].deviceId});c&&(this.log_.info("new camera detected, but there was no camera before."),this.localStream_.recoverCapture({audio:!1,video:!0,cameraId:n[0].deviceId})),u&&(this.log_.info("new microphone detected, but there was no microphone before."),this.localStream_.recoverCapture({audio:!0,video:!1,microphoneId:s[0].deviceId}))}},{key:"handleDeviceRemoved",value:function(e,t){this.log_.warn("devicesRemoved: ".concat(JSON.stringify(t))),this.localStream_.updateDeviceIdInUse();var r=!1,i=!1,n=this.localStream_.getCameraId(),s=this.localStream_.getMicrophoneId();if(s===oR){var o=this.localStream_.getMicrophoneGroupId(),a=e.filter((function(e){return e.deviceId===oR&&e.kind===UE}))[0];a&&a.groupId!==o&&(i=!0)}if(t.forEach((function(e){var t=e.deviceId;n.length>0&&t===n?r=!0:s.length>0&&t===s&&(i=!0)})),r&&i)return this.log_.warn("current camera and microphone in use is lost, cameraId: ".concat(n,", microphoneId: ").concat(s)),void((this.localStream_.getAudio()||this.localStream_.getVideo())&&this.localStream_.recoverCapture({video:!0,audio:!0}));r&&(this.log_.warn("current camera in use is lost, deviceId: ".concat(n)),this.localStream_.getVideo()&&this.localStream_.recoverCapture({video:!0,audio:!1})),i&&(this.log_.warn("current microphone in use is lost, deviceId: ".concat(s)),this.localStream_.getAudio()&&this.localStream_.recoverCapture({video:!1,audio:!0}))}}]),e}(),cM=br.exports,uM=ir,dM=cr,lM=$u,hM=Rn,pM=N,mM=ht,fM=function(e,t,r,i){try{return i?t(dM(r)[0],r[1]):t(r)}catch(t){lM(e,"throw",t)}},gM=bu,vM=Kn,yM=Pi,_M=Nc,bM=Lu,SM=wu,IM=Array,EM=te,TM=2147483647,RM=/[^\0-\u007E]/,wM=/[.\u3002\uFF0E\uFF61]/g,AM="Overflow: input needs wider integers to process",kM=RangeError,CM=EM(wM.exec),MM=Math.floor,OM=String.fromCharCode,PM=EM("".charCodeAt),LM=EM([].join),xM=EM([].push),DM=EM("".replace),NM=EM("".split),$M=EM("".toLowerCase),UM=function(e){return e+22+75*(e<26)},BM=function(e,t,r){var i=0;for(e=r?MM(e/700):e>>1,e+=MM(e/t);e>455;)e=MM(e/35),i+=36;return MM(i+36*e/(e+38))},VM=function(e){var t,r,i=[],n=(e=function(e){for(var t=[],r=0,i=e.length;r<i;){var n=PM(e,r++);if(n>=55296&&n<=56319&&r<i){var s=PM(e,r++);56320==(64512&s)?xM(t,((1023&n)<<10)+(1023&s)+65536):(xM(t,n),r--)}else xM(t,n)}return t}(e)).length,s=128,o=0,a=72;for(t=0;t<e.length;t++)(r=e[t])<128&&xM(i,OM(r));var c=i.length,u=c;for(c&&xM(i,"-");u<n;){var d=TM;for(t=0;t<e.length;t++)(r=e[t])>=s&&r<d&&(d=r);var l=u+1;if(d-s>MM((TM-o)/l))throw kM(AM);for(o+=(d-s)*l,s=d,t=0;t<e.length;t++){if((r=e[t])<s&&++o>TM)throw kM(AM);if(r==s){for(var h=o,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var f=h-m,g=36-m;xM(i,OM(UM(m+f%g))),h=MM(f/g),p+=36}xM(i,OM(UM(h))),a=BM(o,l,u==c),o=0,u++}}o++,s++}return LM(i,"")},FM=Sn,jM=P,WM=ff,qM=C,GM=Rn,HM=te,zM=yi,JM=function(e,t,r){return r.get&&cM(r.get,t,{getter:!0}),r.set&&cM(r.set,t,{setter:!0}),uM.f(e,t,r)},YM=ed,KM=ft,QM=mA,XM=function(e){var t=mM(e),r=vM(this),i=arguments.length,n=i>1?arguments[1]:void 0,s=void 0!==n;s&&(n=hM(n,i>2?arguments[2]:void 0));var o,a,c,u,d,l,h=SM(t),p=0;if(!h||this===IM&&gM(h))for(o=yM(t),a=r?new this(o):IM(o);o>p;p++)l=s?n(t[p],p):t[p],_M(a,p,l);else for(d=(u=bM(t,h)).next,a=r?new this:[];!(c=pM(d,u)).done;p++)l=s?fM(u,n,[c.value,p],!0):c.value,_M(a,p,l);return a.length=p,a},ZM=jc,eO=sl.codeAt,tO=Kd,rO=Ua,iO=Nl,nO=Dg,sO=ti,oO=sO.set,aO=sO.getterFor("URL"),cO=nO.URLSearchParams,uO=nO.getState,dO=qM.URL,lO=qM.TypeError,hO=qM.parseInt,pO=Math.floor,mO=Math.pow,fO=HM("".charAt),gO=HM(/./.exec),vO=HM([].join),yO=HM(1..toString),_O=HM([].pop),bO=HM([].push),SO=HM("".replace),IO=HM([].shift),EO=HM("".split),TO=HM("".slice),RO=HM("".toLowerCase),wO=HM([].unshift),AO="Invalid scheme",kO="Invalid host",CO="Invalid port",MO=/[a-z]/i,OO=/[\d+-.a-z]/i,PO=/\d/,LO=/^0x/i,xO=/^[0-7]+$/,DO=/^\d+$/,NO=/^[\da-f]+$/i,$O=/[\0\t\n\r #%/:<>?@[\\\]^|]/,UO=/[\0\t\n\r #/:<>?@[\\\]^|]/,BO=/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,VO=/[\t\n\r]/g,FO=function(e){var t,r,i,n;if("number"==typeof e){for(t=[],r=0;r<4;r++)wO(t,e%256),e=pO(e/256);return vO(t,".")}if("object"==typeof e){for(t="",i=function(e){for(var t=null,r=1,i=null,n=0,s=0;s<8;s++)0!==e[s]?(n>r&&(t=i,r=n),i=null,n=0):(null===i&&(i=s),++n);return n>r&&(t=i,r=n),t}(e),r=0;r<8;r++)n&&0===e[r]||(n&&(n=!1),i===r?(t+=r?":":"::",n=!0):(t+=yO(e[r],16),r<7&&(t+=":")));return"["+t+"]"}return e},jO={},WO=QM({},jO,{" ":1,'"':1,"<":1,">":1,"`":1}),qO=QM({},WO,{"#":1,"?":1,"{":1,"}":1}),GO=QM({},qO,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),HO=function(e,t){var r=eO(e,0);return r>32&&r<127&&!KM(t,e)?e:encodeURIComponent(e)},zO={ftp:21,file:null,http:80,https:443,ws:80,wss:443},JO=function(e,t){var r;return 2==e.length&&gO(MO,fO(e,0))&&(":"==(r=fO(e,1))||!t&&"|"==r)},YO=function(e){var t;return e.length>1&&JO(TO(e,0,2))&&(2==e.length||"/"===(t=fO(e,2))||"\\"===t||"?"===t||"#"===t)},KO=function(e){return"."===e||"%2e"===RO(e)},QO={},XO={},ZO={},eP={},tP={},rP={},iP={},nP={},sP={},oP={},aP={},cP={},uP={},dP={},lP={},hP={},pP={},mP={},fP={},gP={},vP={},yP=function(e,t,r){var i,n,s,o=tO(e);if(t){if(n=this.parse(o))throw lO(n);this.searchParams=null}else{if(void 0!==r&&(i=new yP(r,!0)),n=this.parse(o,null,i))throw lO(n);(s=uO(new cO)).bindURL(this),this.searchParams=s}};yP.prototype={type:"URL",parse:function(e,t,r){var i,n,s,o,a,c=this,u=t||QO,d=0,l="",h=!1,p=!1,m=!1;for(e=tO(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=SO(e,BO,"")),e=SO(e,VO,""),i=XM(e);d<=i.length;){switch(n=i[d],u){case QO:if(!n||!gO(MO,n)){if(t)return AO;u=ZO;continue}l+=RO(n),u=XO;break;case XO:if(n&&(gO(OO,n)||"+"==n||"-"==n||"."==n))l+=RO(n);else{if(":"!=n){if(t)return AO;l="",u=ZO,d=0;continue}if(t&&(c.isSpecial()!=KM(zO,l)||"file"==l&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=l,t)return void(c.isSpecial()&&zO[c.scheme]==c.port&&(c.port=null));l="","file"==c.scheme?u=dP:c.isSpecial()&&r&&r.scheme==c.scheme?u=eP:c.isSpecial()?u=nP:"/"==i[d+1]?(u=tP,d++):(c.cannotBeABaseURL=!0,bO(c.path,""),u=fP)}break;case ZO:if(!r||r.cannotBeABaseURL&&"#"!=n)return AO;if(r.cannotBeABaseURL&&"#"==n){c.scheme=r.scheme,c.path=ZM(r.path),c.query=r.query,c.fragment="",c.cannotBeABaseURL=!0,u=vP;break}u="file"==r.scheme?dP:rP;continue;case eP:if("/"!=n||"/"!=i[d+1]){u=rP;continue}u=sP,d++;break;case tP:if("/"==n){u=oP;break}u=mP;continue;case rP:if(c.scheme=r.scheme,n==PC)c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=ZM(r.path),c.query=r.query;else if("/"==n||"\\"==n&&c.isSpecial())u=iP;else if("?"==n)c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=ZM(r.path),c.query="",u=gP;else{if("#"!=n){c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=ZM(r.path),c.path.length--,u=mP;continue}c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=ZM(r.path),c.query=r.query,c.fragment="",u=vP}break;case iP:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,u=mP;continue}u=oP}else u=sP;break;case nP:if(u=sP,"/"!=n||"/"!=fO(l,d+1))continue;d++;break;case sP:if("/"!=n&&"\\"!=n){u=oP;continue}break;case oP:if("@"==n){h&&(l="%40"+l),h=!0,s=XM(l);for(var f=0;f<s.length;f++){var g=s[f];if(":"!=g||m){var v=HO(g,GO);m?c.password+=v:c.username+=v}else m=!0}l=""}else if(n==PC||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==l)return"Invalid authority";d-=XM(l).length+1,l="",u=aP}else l+=n;break;case aP:case cP:if(t&&"file"==c.scheme){u=hP;continue}if(":"!=n||p){if(n==PC||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==l)return kO;if(t&&""==l&&(c.includesCredentials()||null!==c.port))return;if(o=c.parseHost(l))return o;if(l="",u=pP,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),l+=n}else{if(""==l)return kO;if(o=c.parseHost(l))return o;if(l="",u=uP,t==cP)return}break;case uP:if(!gO(PO,n)){if(n==PC||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=l){var y=hO(l,10);if(y>65535)return CO;c.port=c.isSpecial()&&y===zO[c.scheme]?null:y,l=""}if(t)return;u=pP;continue}return CO}l+=n;break;case dP:if(c.scheme="file","/"==n||"\\"==n)u=lP;else{if(!r||"file"!=r.scheme){u=mP;continue}if(n==PC)c.host=r.host,c.path=ZM(r.path),c.query=r.query;else if("?"==n)c.host=r.host,c.path=ZM(r.path),c.query="",u=gP;else{if("#"!=n){YO(vO(ZM(i,d),""))||(c.host=r.host,c.path=ZM(r.path),c.shortenPath()),u=mP;continue}c.host=r.host,c.path=ZM(r.path),c.query=r.query,c.fragment="",u=vP}}break;case lP:if("/"==n||"\\"==n){u=hP;break}r&&"file"==r.scheme&&!YO(vO(ZM(i,d),""))&&(JO(r.path[0],!0)?bO(c.path,r.path[0]):c.host=r.host),u=mP;continue;case hP:if(n==PC||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&JO(l))u=mP;else if(""==l){if(c.host="",t)return;u=pP}else{if(o=c.parseHost(l))return o;if("localhost"==c.host&&(c.host=""),t)return;l="",u=pP}continue}l+=n;break;case pP:if(c.isSpecial()){if(u=mP,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=PC&&(u=mP,"/"!=n))continue}else c.fragment="",u=vP;else c.query="",u=gP;break;case mP:if(n==PC||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=RO(a=l))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||bO(c.path,"")):KO(l)?"/"==n||"\\"==n&&c.isSpecial()||bO(c.path,""):("file"==c.scheme&&!c.path.length&&JO(l)&&(c.host&&(c.host=""),l=fO(l,0)+":"),bO(c.path,l)),l="","file"==c.scheme&&(n==PC||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)IO(c.path);"?"==n?(c.query="",u=gP):"#"==n&&(c.fragment="",u=vP)}else l+=HO(n,qO);break;case fP:"?"==n?(c.query="",u=gP):"#"==n?(c.fragment="",u=vP):n!=PC&&(c.path[0]+=HO(n,jO));break;case gP:t||"#"!=n?n!=PC&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":HO(n,jO)):(c.fragment="",u=vP);break;case vP:n!=PC&&(c.fragment+=HO(n,WO))}d++}},parseHost:function(e){var t,r,i;if("["==fO(e,0)){if("]"!=fO(e,e.length-1))return kO;if(!(t=function(e){var t,r,i,n,s,o,a,c=[0,0,0,0,0,0,0,0],u=0,d=null,l=0,h=function(){return fO(e,l)};if(":"==h()){if(":"!=fO(e,1))return;l+=2,d=++u}for(;h();){if(8==u)return;if(":"!=h()){for(t=r=0;r<4&&gO(NO,h());)t=16*t+hO(h(),16),l++,r++;if("."==h()){if(0==r)return;if(l-=r,u>6)return;for(i=0;h();){if(n=null,i>0){if(!("."==h()&&i<4))return;l++}if(!gO(PO,h()))return;for(;gO(PO,h());){if(s=hO(h(),10),null===n)n=s;else{if(0==n)return;n=10*n+s}if(n>255)return;l++}c[u]=256*c[u]+n,2!=++i&&4!=i||u++}if(4!=i)return;break}if(":"==h()){if(l++,!h())return}else if(h())return;c[u++]=t}else{if(null!==d)return;l++,d=++u}}if(null!==d)for(o=u-d,u=7;0!=u&&o>0;)a=c[u],c[u--]=c[d+o-1],c[d+--o]=a;else if(8!=u)return;return c}(TO(e,1,-1))))return kO;this.host=t}else if(this.isSpecial()){if(e=function(e){var t,r,i=[],n=NM(DM($M(e),wM,"."),".");for(t=0;t<n.length;t++)r=n[t],xM(i,CM(RM,r)?"xn--"+VM(r):r);return LM(i,".")}(e),gO($O,e))return kO;if(null===(t=function(e){var t,r,i,n,s,o,a,c=EO(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(r=[],i=0;i<t;i++){if(""==(n=c[i]))return e;if(s=10,n.length>1&&"0"==fO(n,0)&&(s=gO(LO,n)?16:8,n=TO(n,8==s?1:2)),""===n)o=0;else{if(!gO(10==s?DO:8==s?xO:NO,n))return e;o=hO(n,s)}bO(r,o)}for(i=0;i<t;i++)if(o=r[i],i==t-1){if(o>=mO(256,5-t))return null}else if(o>255)return null;for(a=_O(r),i=0;i<r.length;i++)a+=r[i]*mO(256,3-i);return a}(e)))return kO;this.host=t}else{if(gO(UO,e))return kO;for(t="",r=XM(e),i=0;i<r.length;i++)t+=HO(r[i],jO);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return KM(zO,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&JO(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,r=e.username,i=e.password,n=e.host,s=e.port,o=e.path,a=e.query,c=e.fragment,u=t+":";return null!==n?(u+="//",e.includesCredentials()&&(u+=r+(i?":"+i:"")+"@"),u+=FO(n),null!==s&&(u+=":"+s)):"file"==t&&(u+="//"),u+=e.cannotBeABaseURL?o[0]:o.length?"/"+vO(o,"/"):"",null!==a&&(u+="?"+a),null!==c&&(u+="#"+c),u},setHref:function(e){var t=this.parse(e);if(t)throw lO(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new _P(e.path[0]).origin}catch(e){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+FO(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(tO(e)+":",QO)},getUsername:function(){return this.username},setUsername:function(e){var t=XM(tO(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var r=0;r<t.length;r++)this.username+=HO(t[r],GO)}},getPassword:function(){return this.password},setPassword:function(e){var t=XM(tO(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var r=0;r<t.length;r++)this.password+=HO(t[r],GO)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?FO(e):FO(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,aP)},getHostname:function(){var e=this.host;return null===e?"":FO(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,cP)},getPort:function(){var e=this.port;return null===e?"":tO(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=tO(e))?this.port=null:this.parse(e,uP))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+vO(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,pP))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=tO(e))?this.query=null:("?"==fO(e,0)&&(e=TO(e,1)),this.query="",this.parse(e,gP)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=tO(e))?("#"==fO(e,0)&&(e=TO(e,1)),this.fragment="",this.parse(e,vP)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var _P=function(e){var t=YM(this,bP),r=iO(arguments.length,1)>1?arguments[1]:void 0,i=oO(t,new yP(e,!1,r));jM||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},bP=_P.prototype,SP=function(e,t){return{get:function(){return aO(this)[e]()},set:t&&function(e){return aO(this)[t](e)},configurable:!0,enumerable:!0}};if(jM&&(JM(bP,"href",SP("serialize","setHref")),JM(bP,"origin",SP("getOrigin")),JM(bP,"protocol",SP("getProtocol","setProtocol")),JM(bP,"username",SP("getUsername","setUsername")),JM(bP,"password",SP("getPassword","setPassword")),JM(bP,"host",SP("getHost","setHost")),JM(bP,"hostname",SP("getHostname","setHostname")),JM(bP,"port",SP("getPort","setPort")),JM(bP,"pathname",SP("getPathname","setPathname")),JM(bP,"search",SP("getSearch","setSearch")),JM(bP,"searchParams",SP("getSearchParams")),JM(bP,"hash",SP("getHash","setHash"))),zM(bP,"toJSON",(function(){return aO(this).serialize()}),{enumerable:!0}),zM(bP,"toString",(function(){return aO(this).serialize()}),{enumerable:!0}),dO){var IP=dO.createObjectURL,EP=dO.revokeObjectURL;IP&&zM(_P,"createObjectURL",GM(IP,dO)),EP&&zM(_P,"revokeObjectURL",GM(EP,dO))}rO(_P,"URL"),FM({global:!0,constructor:!0,forced:!WM,sham:!jM},{URL:_P});var TP,RP,wP=new Blob(["class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.port.onmessage=event=>{const{data}=event;switch(data.name){case'setIntervalTime':this.intervalTime=data.intervalTime;break;case'stop':this.isStop=true;break}}}process(inputs){const input=inputs[0];if(this.isStop){return false}if(input.length>0){const firstChannel=input[0];let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i]}rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume})}}return true}}registerProcessor('volume-meter',VolumeMeter);"],{type:"application/javascript"}),AP=!1,kP=function(){function e(t){a(this,e),this.context_=t.context,this.addModuleToContext()}var t;return u(e,[{key:"addModuleToContext",value:(t=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.context_.audioWorklet.addModule(URL.createObjectURL(wP));case 3:Lw.info("worklet addModule success"),ww.emit(302),AP=!0,e.next=12;break;case 8:e.prev=8,e.t0=e.catch(0),Lw.info("worklet addModule catch error. ".concat(e.t0.message)),ww.emit(303);case 12:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return t.apply(this,arguments)})},{key:"initWorkletSuccess",get:function(){return AP}}]),e}(),CP=function(){function e(t){a(this,e);var r=t.track,i=t.log,n=t.stream;this.volume_=0,this.log_=i,this.track_=r,this.stream_=n,TP||(TP=new window.AudioContext),this.audioCtx_=TP,this.destination_=this.audioCtx_.destination;var s=new MediaStream;s.addTrack(this.track_),this.streamSource_=this.audioCtx_.createMediaStreamSource(s),this.audioWorkletNode_=null,this.scriptProcessorNode_=null,this.interval_=200,ww.on(301,this.resume,this),ww.on(32,this.handleAudioLevelInterval,this),_w?(ww.on(302,this.initAudioWorklet,this),ww.on(303,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor()}return u(e,[{key:"preload",value:function(){RP?RP.initWorkletSuccess&&this.initAudioWorklet():RP=new kP({context:TP})}},{key:"initAudioWorklet",value:function(){var e=this;if(!this.audioWorkletNode_)try{this.audioWorkletNode_=new AudioWorkletNode(this.audioCtx_,"volume-meter"),this.audioWorkletNode_.port.onmessage=function(t){e.volume_=t.data.volume||0},this.streamSource_.connect(this.audioWorkletNode_).connect(this.destination_),this.handleAudioLevelInterval({interval:this.interval_}),dk.logSuccessEvent({userId:this.stream_.getUserId(),eventType:MT})}catch(e){dk.logFailedEvent({userId:this.stream_.getUserId(),eventType:MT}),this.initScriptProcessor()}}},{key:"initScriptProcessor",value:function(){var e=this;if(!this.scriptProcessorNode_)try{this.scriptProcessorNode_=this.audioCtx_.createScriptProcessor(2048,1,1),this.scriptProcessorNode_.onaudioprocess=function(t){for(var r=t.inputBuffer.getChannelData(0),i=0,n=0;n<r.length;++n)i+=r[n]*r[n];e.volume_=Math.sqrt(i/r.length)||0},this.streamSource_.connect(this.scriptProcessorNode_),this.scriptProcessorNode_.connect(this.destination_)}catch(e){this.log_.error("volumeMeter init script processor error: "+e)}}},{key:"destroy",value:function(){this.streamSource_&&this.streamSource_.disconnect(),this.scriptProcessorNode_&&(this.scriptProcessorNode_.onaudioprocess=null,this.scriptProcessorNode_.disconnect()),this.audioWorkletNode_&&(this.audioWorkletNode_.port.postMessage({name:"stop"}),this.audioWorkletNode_.port.onmessage=null,this.audioWorkletNode_.disconnect()),this.audioWorkletNode_=null,this.scriptProcessorNode_=null,this.audioCtx_=null,ww.off(301,this.resume,this),ww.off(32,this.handleAudioLevelInterval,this),ww.off(302,this.initAudioWorklet,this),ww.off(303,this.initScriptProcessor,this)}},{key:"resume",value:function(){var e;null===(e=TP)||void 0===e||e.resume()}},{key:"getInternalAudioLevel",value:function(){return this.volume_}},{key:"getCalculatedVolume",value:function(){return this.volume_.toFixed(2)}},{key:"handleAudioLevelInterval",value:function(e){var t,r=e.interval;this.interval_=r,null===(t=this.audioWorkletNode_)||void 0===t||t.port.postMessage({name:"setIntervalTime",intervalTime:r})}}]),e}(),MP=function(){function e(t){a(this,e),this.stream_=t.stream,this.userId_=t.stream.getUserId(),this.log_=this.stream_.getLogger(),this.track_=t.track,t.gainedTrack&&(this.gainedTrack_=t.gainedTrack),this.div_=t.div,this.muted_=t.muted,this.outputDeviceId_=t.outputDeviceId,this.volume_=t.volume,this.pausedRetryCount_=5,this.emitter_=new Rw,this.initializeElement(),this.state_="NONE",this.volumeMeter_=new CP({stream:this.stream_,track:this.gainedTrack_||this.track_,log:this.log_})}var t,r,n,s;return u(e,[{key:"isPlaying",get:function(){return this.state_===WE}},{key:"initializeElement",value:function(){if(this.isAudioElementInit()){var e=new MediaStream;e.addTrack(this.gainedTrack_||this.track_);var t=document.createElement(wE);t.srcObject=e,t.muted=this.muted_,t.setAttribute("id","audio_".concat(this.stream_.getId())),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.div_.appendChild(t),this.element_=t}this.handleEvents()}},{key:"setMuted",value:function(e){this.element_&&(this.element_.muted=e,this.muted_=e)}},{key:"play",value:(s=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.outputDeviceId_||!this.element_){e.next=3;break}return e.next=3,this.element_.setSinkId(this.outputDeviceId_);case 3:if(this.setVolume(this.volume_),e.prev=4,!this.element_){e.next=8;break}return e.next=8,this.element_.play();case 8:e.next=16;break;case 10:if(e.prev=10,e.t0=e.catch(4),t=JR({key:NR,data:{media:"Audio",error:e.t0}}),this.log_.warn(t),!t.includes("NotAllowedError")){e.next=16;break}throw new nk({code:ik.PLAY_NOT_ALLOWED,message:t});case 16:case"end":return e.stop()}}),e,this,[[4,10]])}))),function(){return s.apply(this,arguments)})},{key:"handleEvents",value:function(){this.handleElementEvent=this.handleElementEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.element_&&(this.element_.addEventListener(xE,this.handleElementEvent),this.element_.addEventListener(LE,this.handleElementEvent),this.element_.addEventListener(DE,this.handleElementEvent),this.element_.addEventListener(NE,this.handleElementEvent)),this.track_.addEventListener(LE,this.handleTrackEvent),this.track_.addEventListener(OE,this.handleTrackEvent),this.track_.addEventListener(PE,this.handleTrackEvent),this.track_.readyState===LE&&this.handleTrackEvent({type:LE}),this.track_.muted&&this.handleTrackEvent({type:OE})}},{key:"handleElementEvent",value:(n=o(i().mark((function e(t){var r,n,s,o,a,c,u,d=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=t.type,e.t0=r,e.next=e.t0===xE?4:e.t0===LE?9:e.t0===DE?12:e.t0===NE?21:32;break;case 4:return this.log_.info("audio player is playing"),this.state_=WE,ww.emit(103,{stream:this.stream_}),this.emitter_.emit(nM,{state:this.state_,reason:xE}),e.abrupt("break",32);case 9:return this.log_.info("audio player is ended"),this.state_!==GE&&(this.state_=GE,this.emitter_.emit(nM,{state:this.state_,reason:LE})),e.abrupt("break",32);case 12:return this.log_.info("audio player is paused"),this.state_=qE,this.emitter_.emit(nM,{state:this.state_,reason:DE}),(n=this.div_&&document.getElementById(this.div_.id))||this.log_.warn("audio player has been remove, element ID: ".concat(this.div_.id)),s=cE(),this.pausedRetryCount_>0&&(sw(s)&&s<=70||!n)&&(this.resume(),this.pausedRetryCount_--),yI&&(this.interval_=eC.run((function(){d.element_&&d.state_===qE&&d.resume()}),{delay:3e3})),e.abrupt("break",32);case 21:if(!this.element_||!this.element_.error){e.next=31;break}return o="".concat(TC(),"/").concat(EE().name,"/").concat(EE().version),e.next=25,KF.getSpeakers();case 25:a=e.sent,c=a[0].label,(u=a.find((function(e){return e.deviceId===d.outputDeviceId_})))&&(c=u.label),this.log_.error("audio player error observed. code: ".concat(this.element_.error.code," message: ").concat(this.element_.error.message," deviceInfo: ").concat(o," speaker: ").concat(c)),dk.uploadEvent("stat-".concat(this.stream_.getType(),"-audio-").concat(kT,"-").concat(this.element_.error.code,"-").concat(o,"-").concat(c),this.element_.error);case 31:return e.abrupt("break",32);case 32:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"handleTrackEvent",value:function(e){var t=e.type;switch(t){case LE:this.log_.info("audio player track is ended"),this.state_!==GE&&(this.state_=GE,this.emitter_.emit(nM,{state:this.state_,reason:LE})),ww.emit(137,{stream:this.stream_,type:t});break;case OE:this.log_.info("audio track is unable to provide media output"),this.stream_.isRemote()||vw(),this.state_!==qE&&(this.state_=qE,this.emitter_.emit(nM,{state:this.state_,reason:OE})),ww.emit(136,{stream:this.stream_,type:t});break;case PE:this.log_.info("audio track is able to provide media output"),this.state_===qE&&(this.state_=WE,this.emitter_.emit(nM,{state:this.state_,reason:PE}))}}},{key:"unbindEvents",value:function(){this.element_&&(this.element_.removeEventListener(xE,this.handleElementEvent),this.element_.removeEventListener(LE,this.handleElementEvent),this.element_.removeEventListener(DE,this.handleElementEvent),this.element_.removeEventListener(NE,this.handleElementEvent)),this.track_&&(this.track_.removeEventListener(LE,this.handleTrackEvent),this.track_.removeEventListener(OE,this.handleTrackEvent),this.track_.removeEventListener(PE,this.handleTrackEvent))}},{key:"setSinkId",value:(r=o(i().mark((function e(t){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.outputDeviceId_===t){e.next=5;break}if(!this.element_){e.next=4;break}return e.next=4,this.element_.setSinkId(t);case 4:this.outputDeviceId_=t;case 5:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"setVolume",value:function(e){this.element_&&(this.log_.info("audioElement setVolume to : ".concat(e)),this.element_.volume=e)}},{key:"getAudioLevel",value:function(){return this.volumeMeter_.getCalculatedVolume()}},{key:"getInternalAudioLevel",value:function(){return this.volumeMeter_.getInternalAudioLevel()}},{key:"stop",value:function(){this.unbindEvents(),this.element_&&(this.div_.removeChild(this.element_),this.element_.srcObject=null,this.element_=null),this.volumeMeter_&&(this.volumeMeter_.destroy(),this.volumeMeter_=null),this.interval_>0&&eC.clearTask(this.interval_)}},{key:"resume",value:(t=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.volumeMeter_&&this.volumeMeter_.resume(),!this.element_){e.next=5;break}return e.next=5,this.element_.play();case 5:e.next=13;break;case 7:if(e.prev=7,e.t0=e.catch(0),t=JR({key:NR,data:{media:"Audio",error:e.t0}}),this.log_.warn(t),!t.includes("NotAllowedError")){e.next=13;break}throw new nk({code:ik.PLAY_NOT_ALLOWED,message:t});case 13:case"end":return e.stop()}}),e,this,[[0,7]])}))),function(){return t.apply(this,arguments)})},{key:"on",value:function(e,t){this.emitter_.on(e,t)}},{key:"isAudioElementInit",value:function(){return!("15.2"===gE||"15.3"===gE||"15.4"===gE)||"local"!==this.stream_.getType()||!this.muted_||(this.log_.info("audioElement is muted."),!1)}}]),e}(),OP=wr.PROPER,PP=O,LP=zv,xP=ty.trim;Sn({target:"String",proto:!0,forced:function(e){return PP((function(){return!!LP[e]()||"​…᠎"!=="​…᠎"[e]()||OP&&LP[e].name!==e}))}("trim")},{trim:function(){return xP(this)}});var DP="trtc_autoplay",NP="".concat(DP,"_mask"),$P="".concat(DP,"_wrapper"),UP="".concat(DP,"_header"),BP="".concat(DP,"_content"),VP="".concat(DP,"_action_wrapper"),FP="".concat(DP,"_question"),jP="".concat(DP,"_collapse"),WP="".concat(DP,"_action_confirm"),qP="".concat(DP,"_detail"),GP="#2473E8",HP="dialog",zP="".concat(HP,"-show"),JP="".concat(HP,"-1"),YP="".concat(HP,"-2"),KP=!1,QP=function(){return!!document.querySelector(".".concat($P))},XP="".concat(iR,"/").concat(gw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),ZP="<br><a href='".concat(XP,"' target='_blank'>").concat(gw()?"其他方案?":"Any other solution?","</a>"),eL="".concat(gw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(ZP):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(ZP)),tL=function(){function e(){if(a(this,e),this.dialogNode_=null,this.bodyPosition_="",this.content="音视频播放被浏览器拦截,请点击“恢复播放”。",gw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!KP){var t=document.createElement("style");t.innerHTML=".".concat(NP,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(NP," div:not(.").concat(VP,"){display:block !important;}.").concat($P,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat($P," a{color:").concat(GP,";}.").concat(UP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(BP,"{margin:8px 0;}.").concat(VP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(jP,"{margin-right:auto;cursor:pointer}.").concat(FP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(WP,"{margin-left:8px;color:#fff;background:").concat(GP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(WP,":hover{opacity:0.9;}.").concat(jP,",.").concat(WP,",.").concat(BP,",.").concat(FP,"{font-size:14px;}@media screen and (max-width:750px){.").concat($P,"{width:80vw;}}"),document.head.appendChild(t),KP=!0}this.showDetail_=!1,this.isCollapseClicked_=!1,this.isQuestionClicked_=!1,this.addDiaLog()}return u(e,[{key:"createDiaLog",value:function(){var e=document.createElement("template");e.innerHTML='<div class="'.concat(NP,"\"><div class='").concat($P,"'><div class='").concat(UP,"'>").concat(location.host,"</div><div class='").concat(BP,"'>").concat(this.content,"</div><div class='").concat(qP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(eL,"</div><div class='").concat(VP,"'></div></div></div>").trim();var t=document.createElement("button");t.className=WP,t.innerText=gw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);var r=document.createElement("div");r.className=FP,r.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',r.onclick=this.onQuestionClick.bind(this);var i=document.createElement("div");i.className=jP,i.innerText="".concat(gw()?"详情 >":"Detail >"),i.onclick=this.onCollapseClick.bind(this);var n=e.content.firstChild,s=n.querySelector(".".concat(VP));return s.appendChild(i),s.appendChild(r),s.appendChild(t),n}},{key:"addDiaLog",value:function(){QP()||(this.dialogNode_=this.createDiaLog(),document.body.appendChild(this.dialogNode_),this.dialogNode_.onclick=this.onConfirm.bind(this),this.dialogNode_.querySelector(".".concat($P)).onclick=function(e){return e.stopPropagation()},this.bodyPosition_=document.body.style.position,document.body.style.position="fixed",Lw.info("show autoplay dialog"),dk.uploadEvent({log:zP}))}},{key:"deleteDiaLog",value:function(){this.dialogNode_&&(document.body.removeChild(this.dialogNode_),document.body.style.position=this.bodyPosition_,this.dialogNode_=null)}},{key:"onConfirm",value:function(){Lw.warn("confirm clicked, try resume stream"),ww.emit(301),this.deleteDiaLog()}},{key:"onCollapseClick",value:function(){var e=this.dialogNode_.querySelector(".".concat(qP));e.style.visibility="".concat(this.showDetail_?"hidden":"visible"),e.style.height="".concat(this.showDetail_?0:"fit-content"),this.showDetail_=!this.showDetail_,this.isCollapseClicked_||dk.uploadEvent({log:JP}),this.isCollapseClicked_=!0}},{key:"onQuestionClick",value:function(){window.open(XP,"_blank"),this.isQuestionClicked_||dk.uploadEvent({log:YP}),this.isQuestionClicked_=!0}}]),e}(),rL=function(){function e(t){a(this,e),this.stream_=t.stream,this.userId_=t.stream.getUserId(),this.log_=this.stream_.getLogger(),this.track_=t.track,this.div_=t.div,this.muted_=t.muted,this.objectFit_=t.objectFit,this.mirror_=t.mirror,this.emitter_=new Rw,this.initializeElement(),this.state_="NONE",this.pausedRetryCount_=5}var t;return u(e,[{key:"isPlaying",get:function(){return this.state_===WE}},{key:"initializeElement",value:function(){var e=new MediaStream;e.addTrack(this.track_);var t=document.createElement(AE);t.srcObject=e,t.muted=!0;var r="width: 100%; height: 100%; object-fit: ".concat(this.objectFit_,";");this.mirror_&&(r+="transform: scaleX(-1);"),t.setAttribute("id","video_".concat(this.stream_.getId())),t.setAttribute("style",r),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.div_&&this.div_.appendChild(t),this.element_=t,this.handleEvents()}},{key:"setRect",value:function(e){var t=e.width,r=e.height;this.element_&&(this.element_.style.width=t+"px",this.element_.style.height=r+"px")}},{key:"setMirror",value:function(e){this.element_&&(this.element_.style.transform=e?"scaleX(-1)":"",this.mirror_=e)}},{key:"setObjectFit",value:function(e){this.element_&&(this.element_.style.objectFit="".concat(e),this.objectFit_=e)}},{key:"play",value:(t=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.element_.play();case 3:e.next=11;break;case 5:if(e.prev=5,e.t0=e.catch(0),t=JR({key:NR,data:{media:"Video",error:e.t0}}),this.log_.warn(t),!t.includes("NotAllowedError")){e.next=11;break}throw new nk({code:ik.PLAY_NOT_ALLOWED,message:t});case 11:case"end":return e.stop()}}),e,this,[[0,5]])}))),function(){return t.apply(this,arguments)})},{key:"handleEvents",value:function(){this.handleElementEvent=this.handleElementEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.element_.addEventListener(xE,this.handleElementEvent),this.element_.addEventListener(LE,this.handleElementEvent),this.element_.addEventListener(DE,this.handleElementEvent),this.element_.addEventListener(NE,this.handleElementEvent),this.element_.addEventListener($E,this.handleElementEvent),this.track_.addEventListener(LE,this.handleTrackEvent),this.track_.addEventListener(OE,this.handleTrackEvent),this.track_.addEventListener(PE,this.handleTrackEvent),this.track_.readyState===LE&&this.handleTrackEvent({type:LE}),this.track_.muted&&this.handleTrackEvent({type:OE})}},{key:"handleElementEvent",value:function(e){var t=this;switch(e.type){case xE:this.log_.info("video player is playing"),this.state_=WE,ww.emit(102,{stream:this.stream_}),this.emitter_.emit(nM,{state:this.state_,reason:xE}),this.interval_&&(eC.clearTask(this.interval_),this.interval_=null);break;case LE:this.log_.info("video player is ended"),this.state_!==GE&&(this.state_=GE,this.emitter_.emit(nM,{state:this.state_,reason:LE}));break;case DE:this.log_.info("video player is paused"),this.div_&&!document.getElementById(this.div_.id)&&this.log_.warn("video player has been remove, element ID: ".concat(this.div_.id)),this.state_=qE,this.emitter_.emit(nM,{state:this.state_,reason:DE}),this.pausedRetryCount_>0&&!QP()&&(this.log_.info("video player auto resume when video paused"),this.resume(),this.pausedRetryCount_--),yI&&(this.interval_=eC.run((function(){t.element_&&t.state_===qE&&t.resume()}),{delay:3e3}));break;case NE:if(this.element_&&this.element_.error){var r="".concat(TC(),"/").concat(EE().name,"/").concat(EE().version);this.log_.error("video player error observed. code: ".concat(this.element_.error.code," message: ").concat(this.element_.error.message," deviceInfo: ").concat(r)),dk.uploadEvent("stat-".concat(this.stream_.getType(),"-video-").concat(kT,"-").concat(this.element_.error.code,"-").concat(r),this.element_.error)}break;case $E:ww.emit(133,{stream:this.stream_})}}},{key:"handleTrackEvent",value:function(e){var t=e.type;switch(t){case LE:this.log_.info("video track is ended"),ww.emit(135,{stream:this.stream_,type:t}),this.state_!==GE&&(this.state_=GE,this.emitter_.emit(nM,{state:this.state_,reason:LE}));break;case OE:this.log_.info("video track is unable to provide media output"),this.stream_.isRemote()||vw(),ww.emit(130,{stream:this.stream_,type:t}),this.state_!==qE&&(this.state_=qE,this.emitter_.emit(nM,{state:this.state_,reason:OE}));break;case PE:this.log_.info("video track is able to provide media output"),ww.emit(131,{stream:this.stream_}),this.state_===qE&&(this.state_=WE,this.emitter_.emit(nM,{state:this.state_,reason:PE}))}}},{key:"unbindEvents",value:function(){this.element_&&(this.element_.removeEventListener(xE,this.handleElementEvent),this.element_.removeEventListener(LE,this.handleElementEvent),this.element_.removeEventListener(DE,this.handleElementEvent),this.element_.removeEventListener(NE,this.handleElementEvent),this.element_.removeEventListener($E,this.handleElementEvent)),this.track_&&(this.track_.removeEventListener(LE,this.handleTrackEvent),this.track_.removeEventListener(OE,this.handleTrackEvent),this.track_.removeEventListener(PE,this.handleTrackEvent))}},{key:"stop",value:function(){this.unbindEvents(),this.div_&&this.div_.removeChild(this.element_),this.element_.srcObject=null,this.element_=null,this.interval_&&eC.clearTask(this.interval_)}},{key:"resume",value:function(){return this.play()}},{key:"getVideoFrame",value:function(){var e=document.createElement("canvas");return e.width=this.element_.videoWidth,e.height=this.element_.videoHeight,e.getContext("2d").drawImage(this.element_,0,0),e.toDataURL("image/png")}},{key:"on",value:function(e,t){this.emitter_.on(e,t)}},{key:"getElement",value:function(){return this.element_?this.element_:null}}]),e}(),iL="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,nL=Ei,sL=Mi,oL=RangeError,aL=function(e){if(void 0===e)return 0;var t=nL(e),r=sL(t);if(t!==r)throw oL("Wrong length or index");return r},cL=Array,uL=Math.abs,dL=Math.pow,lL=Math.floor,hL=Math.log,pL=Math.LN2,mL=ht,fL=Ai,gL=Pi,vL=function(e){for(var t=mL(this),r=gL(t),i=arguments.length,n=fL(i>1?arguments[1]:void 0,r),s=i>2?arguments[2]:void 0,o=void 0===s?r:fL(s,r);o>n;)t[n++]=e;return t},yL=C,_L=te,bL=P,SL=iL,IL=wr,EL=_r,TL=Ad,RL=O,wL=ed,AL=Ei,kL=Mi,CL=aL,ML={pack:function(e,t,r){var i,n,s,o=cL(r),a=8*r-t-1,c=(1<<a)-1,u=c>>1,d=23===t?dL(2,-24)-dL(2,-77):0,l=e<0||0===e&&1/e<0?1:0,h=0;for((e=uL(e))!=e||1/0===e?(n=e!=e?1:0,i=c):(i=lL(hL(e)/pL),e*(s=dL(2,-i))<1&&(i--,s*=2),(e+=i+u>=1?d/s:d*dL(2,1-u))*s>=2&&(i++,s/=2),i+u>=c?(n=0,i=c):i+u>=1?(n=(e*s-1)*dL(2,t),i+=u):(n=e*dL(2,u-1)*dL(2,t),i=0));t>=8;)o[h++]=255&n,n/=256,t-=8;for(i=i<<t|n,a+=t;a>0;)o[h++]=255&i,i/=256,a-=8;return o[--h]|=128*l,o},unpack:function(e,t){var r,i=e.length,n=8*i-t-1,s=(1<<n)-1,o=s>>1,a=n-7,c=i-1,u=e[c--],d=127&u;for(u>>=7;a>0;)d=256*d+e[c--],a-=8;for(r=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)r=256*r+e[c--],a-=8;if(0===d)d=1-o;else{if(d===s)return r?NaN:u?-1/0:1/0;r+=dL(2,t),d-=o}return(u?-1:1)*r*dL(2,d-t)}},OL=wa,PL=Qa,LL=_i.f,xL=ir.f,DL=vL,NL=jc,$L=Ua,UL=IL.PROPER,BL=IL.CONFIGURABLE,VL=ti.get,FL=ti.set,jL="ArrayBuffer",WL="Wrong index",qL=yL.ArrayBuffer,GL=qL,HL=GL&&GL.prototype,zL=yL.DataView,JL=zL&&zL.prototype,YL=Object.prototype,KL=yL.Array,QL=yL.RangeError,XL=_L(DL),ZL=_L([].reverse),ex=ML.pack,tx=ML.unpack,rx=function(e){return[255&e]},ix=function(e){return[255&e,e>>8&255]},nx=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},sx=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},ox=function(e){return ex(e,23,4)},ax=function(e){return ex(e,52,8)},cx=function(e,t){xL(e.prototype,t,{get:function(){return VL(this)[t]}})},ux=function(e,t,r,i){var n=CL(r),s=VL(e);if(n+t>s.byteLength)throw QL(WL);var o=VL(s.buffer).bytes,a=n+s.byteOffset,c=NL(o,a,a+t);return i?c:ZL(c)},dx=function(e,t,r,i,n,s){var o=CL(r),a=VL(e);if(o+t>a.byteLength)throw QL(WL);for(var c=VL(a.buffer).bytes,u=o+a.byteOffset,d=i(+n),l=0;l<t;l++)c[u+l]=d[s?l:t-l-1]};if(SL){var lx=UL&&qL.name!==jL;if(RL((function(){qL(1)}))&&RL((function(){new qL(-1)}))&&!RL((function(){return new qL,new qL(1.5),new qL(NaN),1!=qL.length||lx&&!BL})))lx&&BL&&EL(qL,"name",jL);else{(GL=function(e){return wL(this,HL),new qL(CL(e))}).prototype=HL;for(var hx,px=LL(qL),mx=0;px.length>mx;)(hx=px[mx++])in GL||EL(GL,hx,qL[hx]);HL.constructor=GL}PL&&OL(JL)!==YL&&PL(JL,YL);var fx=new zL(new GL(2)),gx=_L(JL.setInt8);fx.setInt8(0,2147483648),fx.setInt8(1,2147483649),!fx.getInt8(0)&&fx.getInt8(1)||TL(JL,{setInt8:function(e,t){gx(this,e,t<<24>>24)},setUint8:function(e,t){gx(this,e,t<<24>>24)}},{unsafe:!0})}else HL=(GL=function(e){wL(this,HL);var t=CL(e);FL(this,{bytes:XL(KL(t),0),byteLength:t}),bL||(this.byteLength=t)}).prototype,JL=(zL=function(e,t,r){wL(this,JL),wL(e,HL);var i=VL(e).byteLength,n=AL(t);if(n<0||n>i)throw QL("Wrong offset");if(n+(r=void 0===r?i-n:kL(r))>i)throw QL("Wrong length");FL(this,{buffer:e,byteLength:r,byteOffset:n}),bL||(this.buffer=e,this.byteLength=r,this.byteOffset=n)}).prototype,bL&&(cx(GL,"byteLength"),cx(zL,"buffer"),cx(zL,"byteLength"),cx(zL,"byteOffset")),TL(JL,{getInt8:function(e){return ux(this,1,e)[0]<<24>>24},getUint8:function(e){return ux(this,1,e)[0]},getInt16:function(e){var t=ux(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ux(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return sx(ux(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return sx(ux(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return tx(ux(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return tx(ux(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){dx(this,1,e,rx,t)},setUint8:function(e,t){dx(this,1,e,rx,t)},setInt16:function(e,t){dx(this,2,e,ix,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){dx(this,2,e,ix,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){dx(this,4,e,nx,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){dx(this,4,e,nx,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){dx(this,4,e,ox,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){dx(this,8,e,ax,t,arguments.length>2?arguments[2]:void 0)}});$L(GL,jL),$L(zL,"DataView");var vx={ArrayBuffer:GL,DataView:zL},yx=Sn,_x=te,bx=O,Sx=cr,Ix=Ai,Ex=Mi,Tx=l_,Rx=vx.ArrayBuffer,wx=vx.DataView,Ax=wx.prototype,kx=_x(Rx.prototype.slice),Cx=_x(Ax.getUint8),Mx=_x(Ax.setUint8);yx({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:bx((function(){return!new Rx(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(kx&&void 0===t)return kx(Sx(this),e);for(var r=Sx(this).byteLength,i=Ix(e,r),n=Ix(void 0===t?r:t,r),s=new(Tx(this,Rx))(Ex(n-i)),o=new wx(this),a=new wx(s),c=0;i<n;)Mx(a,c++,Cx(o,i++));return s}}),Sn({global:!0,constructor:!0,forced:!iL},{DataView:vx.DataView});var Ox=Sn,Px=An,Lx=te([].reverse),xx=[1,2];Ox({target:"Array",proto:!0,forced:String(xx)===String(xx.reverse())},{reverse:function(){return Px(this)&&(this.length=this.length),Lx(this)}});var Dx=Je,Nx=ht,$x=oe,Ux=Pi,Bx=TypeError,Vx=function(e){return function(t,r,i,n){Dx(r);var s=Nx(t),o=$x(s),a=Ux(s),c=e?a-1:0,u=e?-1:1;if(i<2)for(;;){if(c in o){n=o[c],c+=u;break}if(c+=u,e?c<0:a<=c)throw Bx("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=u)c in o&&(n=r(n,o[c],c,s));return n}},Fx={left:Vx(!1),right:Vx(!0)},jx=Fx.left,Wx=Le,qx=r_;Sn({target:"Array",proto:!0,forced:!yh("reduce")||!qx&&Wx>79&&Wx<83},{reduce:function(e){var t=arguments.length;return jx(this,e,t,t>1?arguments[1]:void 0)}});var Gx=Pd,Hx=vx.ArrayBuffer;Sn({global:!0,constructor:!0,forced:C.ArrayBuffer!==Hx},{ArrayBuffer:Hx}),Gx("ArrayBuffer");var zx=Sn,Jx=An,Yx=Kn,Kx=be,Qx=Ai,Xx=Pi,Zx=pe,eD=Nc,tD=Ot,rD=xl,iD=ms("slice"),nD=tD("species"),sD=Array,oD=Math.max;zx({target:"Array",proto:!0,forced:!iD},{slice:function(e,t){var r,i,n,s=Zx(this),o=Xx(s),a=Qx(e,o),c=Qx(void 0===t?o:t,o);if(Jx(s)&&(r=s.constructor,(Yx(r)&&(r===sD||Jx(r.prototype))||Kx(r)&&null===(r=r[nD]))&&(r=void 0),r===sD||void 0===r))return rD(s,a,c);for(i=new(void 0===r?sD:r)(oD(c-a,0)),n=0;a<c;a++,n++)a in s&&eD(i,n,s[a]);return i.length=n,i}});var aD=C,cD=O,uD=te,dD=Kd,lD=ty.trim,hD=zv,pD=aD.parseInt,mD=aD.Symbol,fD=mD&&mD.iterator,gD=/^[+-]?0x/i,vD=uD(gD.exec),yD=8!==pD(hD+"08")||22!==pD(hD+"0x16")||fD&&!cD((function(){pD(Object(fD))}))?function(e,t){var r=lD(dD(e));return pD(r,t>>>0||(vD(gD,r)?16:10))}:pD;Sn({global:!0,forced:parseInt!=yD},{parseInt:yD});var _D,bD,SD,ID={exports:{}},ED=iL,TD=P,RD=C,wD=ve,AD=be,kD=ft,CD=Nn,MD=qe,OD=_r,PD=yi,LD=ir.f,xD=Re,DD=wa,ND=Qa,$D=Ot,UD=bt,BD=ti.enforce,VD=ti.get,FD=RD.Int8Array,jD=FD&&FD.prototype,WD=RD.Uint8ClampedArray,qD=WD&&WD.prototype,GD=FD&&DD(FD),HD=jD&&DD(jD),zD=Object.prototype,JD=RD.TypeError,YD=$D("toStringTag"),KD=UD("TYPED_ARRAY_TAG"),QD=ED&&!!ND&&"Opera"!==CD(RD.opera),XD=!1,ZD={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},eN={BigInt64Array:8,BigUint64Array:8},tN=function(e){var t=DD(e);if(AD(t)){var r=VD(t);return r&&kD(r,"TypedArrayConstructor")?r.TypedArrayConstructor:tN(t)}},rN=function(e){if(!AD(e))return!1;var t=CD(e);return kD(ZD,t)||kD(eN,t)};for(_D in ZD)(SD=(bD=RD[_D])&&bD.prototype)?BD(SD).TypedArrayConstructor=bD:QD=!1;for(_D in eN)(SD=(bD=RD[_D])&&bD.prototype)&&(BD(SD).TypedArrayConstructor=bD);if((!QD||!wD(GD)||GD===Function.prototype)&&(GD=function(){throw JD("Incorrect invocation")},QD))for(_D in ZD)RD[_D]&&ND(RD[_D],GD);if((!QD||!HD||HD===zD)&&(HD=GD.prototype,QD))for(_D in ZD)RD[_D]&&ND(RD[_D].prototype,HD);if(QD&&DD(qD)!==HD&&ND(qD,HD),TD&&!kD(HD,YD))for(_D in XD=!0,LD(HD,YD,{get:function(){return AD(this)?this[KD]:void 0}}),ZD)RD[_D]&&OD(RD[_D],KD,_D);var iN={NATIVE_ARRAY_BUFFER_VIEWS:QD,TYPED_ARRAY_TAG:XD&&KD,aTypedArray:function(e){if(rN(e))return e;throw JD("Target is not a typed array")},aTypedArrayConstructor:function(e){if(wD(e)&&(!ND||xD(GD,e)))return e;throw JD(MD(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,r,i){if(TD){if(r)for(var n in ZD){var s=RD[n];if(s&&kD(s.prototype,e))try{delete s.prototype[e]}catch(r){try{s.prototype[e]=t}catch(e){}}}HD[e]&&!r||PD(HD,e,r?t:QD&&jD[e]||t,i)}},exportTypedArrayStaticMethod:function(e,t,r){var i,n;if(TD){if(ND){if(r)for(i in ZD)if((n=RD[i])&&kD(n,e))try{delete n[e]}catch(e){}if(GD[e]&&!r)return;try{return PD(GD,e,r?t:QD&&GD[e]||t)}catch(e){}}for(i in ZD)!(n=RD[i])||n[e]&&!r||PD(n,e,t)}},getTypedArrayConstructor:tN,isView:function(e){if(!AD(e))return!1;var t=CD(e);return"DataView"===t||kD(ZD,t)||kD(eN,t)},isTypedArray:rN,TypedArray:GD,TypedArrayPrototype:HD},nN=C,sN=O,oN=sd,aN=iN.NATIVE_ARRAY_BUFFER_VIEWS,cN=nN.ArrayBuffer,uN=nN.Int8Array,dN=!aN||!sN((function(){uN(1)}))||!sN((function(){new uN(-1)}))||!oN((function(e){new uN,new uN(null),new uN(1.5),new uN(e)}),!0)||sN((function(){return 1!==new uN(new cN(2),1,void 0).length})),lN=Ei,hN=RangeError,pN=RangeError,mN=function(e,t){var r=function(e){var t=lN(e);if(t<0)throw hN("The argument can't be less than 0");return t}(e);if(r%t)throw pN("Wrong offset");return r},fN=Nn,gN=te("".slice),vN=Ut,yN=TypeError,_N=function(e){var t=vN(e,"number");if("number"==typeof t)throw yN("Can't convert number to bigint");return BigInt(t)},bN=Rn,SN=N,IN=o_,EN=ht,TN=Pi,RN=Lu,wN=wu,AN=bu,kN=function(e){return"Big"===gN(fN(e),0,3)},CN=iN.aTypedArrayConstructor,MN=_N,ON=Sn,PN=C,LN=N,xN=P,DN=dN,NN=iN,$N=vx,UN=ed,BN=W,VN=_r,FN=$w,jN=Mi,WN=aL,qN=mN,GN=Ft,HN=ft,zN=Nn,JN=be,YN=je,KN=aa,QN=Re,XN=Qa,ZN=_i.f,e$=function(e){var t,r,i,n,s,o,a,c,u=IN(this),d=EN(e),l=arguments.length,h=l>1?arguments[1]:void 0,p=void 0!==h,m=wN(d);if(m&&!AN(m))for(c=(a=RN(d,m)).next,d=[];!(o=SN(c,a)).done;)d.push(o.value);for(p&&l>2&&(h=bN(h,arguments[2])),r=TN(d),i=new(CN(u))(r),n=kN(i),t=0;r>t;t++)s=p?h(d[t],t):d[t],i[t]=n?MN(s):+s;return i},t$=ds.forEach,r$=Pd,i$=ir,n$=M,s$=ud,o$=ti.get,a$=ti.set,c$=ti.enforce,u$=i$.f,d$=n$.f,l$=Math.round,h$=PN.RangeError,p$=$N.ArrayBuffer,m$=p$.prototype,f$=$N.DataView,g$=NN.NATIVE_ARRAY_BUFFER_VIEWS,v$=NN.TYPED_ARRAY_TAG,y$=NN.TypedArray,_$=NN.TypedArrayPrototype,b$=NN.aTypedArrayConstructor,S$=NN.isTypedArray,I$="BYTES_PER_ELEMENT",E$="Wrong length",T$=function(e,t){b$(e);for(var r=0,i=t.length,n=new e(i);i>r;)n[r]=t[r++];return n},R$=function(e,t){u$(e,t,{get:function(){return o$(this)[t]}})},w$=function(e){var t;return QN(m$,e)||"ArrayBuffer"==(t=zN(e))||"SharedArrayBuffer"==t},A$=function(e,t){return S$(e)&&!YN(t)&&t in e&&FN(+t)&&t>=0},k$=function(e,t){return t=GN(t),A$(e,t)?BN(2,e[t]):d$(e,t)},C$=function(e,t,r){return t=GN(t),!(A$(e,t)&&JN(r)&&HN(r,"value"))||HN(r,"get")||HN(r,"set")||r.configurable||HN(r,"writable")&&!r.writable||HN(r,"enumerable")&&!r.enumerable?u$(e,t,r):(e[t]=r.value,e)};xN?(g$||(n$.f=k$,i$.f=C$,R$(_$,"buffer"),R$(_$,"byteOffset"),R$(_$,"byteLength"),R$(_$,"length")),ON({target:"Object",stat:!0,forced:!g$},{getOwnPropertyDescriptor:k$,defineProperty:C$}),ID.exports=function(e,t,r){var i=e.match(/\d+$/)[0]/8,n=e+(r?"Clamped":"")+"Array",s="get"+e,o="set"+e,a=PN[n],c=a,u=c&&c.prototype,d={},l=function(e,t){u$(e,t,{get:function(){return function(e,t){var r=o$(e);return r.view[s](t*i+r.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var s=o$(e);r&&(n=(n=l$(n))<0?0:n>255?255:255&n),s.view[o](t*i+s.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};g$?DN&&(c=t((function(e,t,r,n){return UN(e,u),s$(JN(t)?w$(t)?void 0!==n?new a(t,qN(r,i),n):void 0!==r?new a(t,qN(r,i)):new a(t):S$(t)?T$(c,t):LN(e$,c,t):new a(WN(t)),e,c)})),XN&&XN(c,y$),t$(ZN(a),(function(e){e in c||VN(c,e,a[e])})),c.prototype=u):(c=t((function(e,t,r,n){UN(e,u);var s,o,a,d=0,h=0;if(JN(t)){if(!w$(t))return S$(t)?T$(c,t):LN(e$,c,t);s=t,h=qN(r,i);var p=t.byteLength;if(void 0===n){if(p%i)throw h$(E$);if((o=p-h)<0)throw h$(E$)}else if((o=jN(n)*i)+h>p)throw h$(E$);a=o/i}else a=WN(t),s=new p$(o=a*i);for(a$(e,{buffer:s,byteOffset:h,byteLength:o,length:a,view:new f$(s)});d<a;)l(e,d++)})),XN&&XN(c,y$),u=c.prototype=KN(_$)),u.constructor!==c&&VN(u,"constructor",c),c$(u).TypedArrayConstructor=c,v$&&VN(u,v$,n);var h=c!=a;d[n]=c,ON({global:!0,constructor:!0,forced:h,sham:!g$},d),I$ in c||VN(c,I$,i),I$ in u||VN(u,I$,i),r$(n)}):ID.exports=function(){},(0,ID.exports)("Uint8",(function(e){return function(t,r,i){return e(this,t,r,i)}}));var M$=ht,O$=Ai,P$=Pi,L$=ih,x$=Math.min,D$=iN,N$=te([].copyWithin||function(e,t){var r=M$(this),i=P$(r),n=O$(e,i),s=O$(t,i),o=arguments.length>2?arguments[2]:void 0,a=x$((void 0===o?i:O$(o,i))-s,i-n),c=1;for(s<n&&n<s+a&&(c=-1,s+=a-1,n+=a-1);a-- >0;)s in r?r[n]=r[s]:L$(r,n),n+=c,s+=c;return r}),$$=D$.aTypedArray;(0,D$.exportTypedArrayMethod)("copyWithin",(function(e,t){return N$($$(this),e,t,arguments.length>2?arguments[2]:void 0)}));var U$=ds.every,B$=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("every",(function(e){return U$(B$(this),e,arguments.length>1?arguments[1]:void 0)}));var V$=vL,F$=_N,j$=Nn,W$=N,q$=O,G$=iN.aTypedArray,H$=iN.exportTypedArrayMethod,z$=te("".slice);H$("fill",(function(e){var t=arguments.length;G$(this);var r="Big"===z$(j$(this),0,3)?F$(e):+e;return W$(V$,this,r,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),q$((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var J$=Pi,Y$=l_,K$=iN.aTypedArrayConstructor,Q$=iN.getTypedArrayConstructor,X$=function(e){return K$(Y$(e,Q$(e)))},Z$=X$,eU=ds.filter,tU=function(e,t){return function(e,t){for(var r=0,i=J$(t),n=new e(i);i>r;)n[r]=t[r++];return n}(Z$(e),t)},rU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("filter",(function(e){var t=eU(rU(this),e,arguments.length>1?arguments[1]:void 0);return tU(this,t)}));var iU=ds.find,nU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("find",(function(e){return iU(nU(this),e,arguments.length>1?arguments[1]:void 0)}));var sU=ds.findIndex,oU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("findIndex",(function(e){return sU(oU(this),e,arguments.length>1?arguments[1]:void 0)}));var aU=ds.forEach,cU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("forEach",(function(e){aU(cU(this),e,arguments.length>1?arguments[1]:void 0)}));var uU=$i.includes,dU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("includes",(function(e){return uU(dU(this),e,arguments.length>1?arguments[1]:void 0)}));var lU=$i.indexOf,hU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("indexOf",(function(e){return lU(hU(this),e,arguments.length>1?arguments[1]:void 0)}));var pU=C,mU=O,fU=te,gU=iN,vU=Cc,yU=Ot("iterator"),_U=pU.Uint8Array,bU=fU(vU.values),SU=fU(vU.keys),IU=fU(vU.entries),EU=gU.aTypedArray,TU=gU.exportTypedArrayMethod,RU=_U&&_U.prototype,wU=!mU((function(){RU[yU].call([1])})),AU=!!RU&&RU.values&&RU[yU]===RU.values&&"values"===RU.values.name,kU=function(){return bU(EU(this))};TU("entries",(function(){return IU(EU(this))}),wU),TU("keys",(function(){return SU(EU(this))}),wU),TU("values",kU,wU||!AU,{name:"values"}),TU(yU,kU,wU||!AU,{name:"values"});var CU=iN.aTypedArray,MU=iN.exportTypedArrayMethod,OU=te([].join);MU("join",(function(e){return OU(CU(this),e)}));var PU=Ll,LU=pe,xU=Ei,DU=Pi,NU=yh,$U=Math.min,UU=[].lastIndexOf,BU=!!UU&&1/[1].lastIndexOf(1,-0)<0,VU=NU("lastIndexOf"),FU=Ll,jU=BU||!VU?function(e){if(BU)return PU(UU,this,arguments)||0;var t=LU(this),r=DU(t),i=r-1;for(arguments.length>1&&(i=$U(i,xU(arguments[1]))),i<0&&(i=r+i);i>=0;i--)if(i in t&&t[i]===e)return i||0;return-1}:UU,WU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("lastIndexOf",(function(e){var t=arguments.length;return FU(jU,WU(this),t>1?[e,arguments[1]]:[e])}));var qU=ds.map,GU=X$,HU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("map",(function(e){return qU(HU(this),e,arguments.length>1?arguments[1]:void 0,(function(e,t){return new(GU(e))(t)}))}));var zU=Fx.left,JU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("reduce",(function(e){var t=arguments.length;return zU(JU(this),e,t,t>1?arguments[1]:void 0)}));var YU=Fx.right,KU=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("reduceRight",(function(e){var t=arguments.length;return YU(KU(this),e,t,t>1?arguments[1]:void 0)}));var QU=iN.aTypedArray,XU=iN.exportTypedArrayMethod,ZU=Math.floor;XU("reverse",(function(){for(var e,t=this,r=QU(t).length,i=ZU(r/2),n=0;n<i;)e=t[n],t[n++]=t[--r],t[r]=e;return t}));var eB=C,tB=N,rB=iN,iB=Pi,nB=mN,sB=ht,oB=O,aB=eB.RangeError,cB=eB.Int8Array,uB=cB&&cB.prototype,dB=uB&&uB.set,lB=rB.aTypedArray,hB=rB.exportTypedArrayMethod,pB=!oB((function(){var e=new Uint8ClampedArray(2);return tB(dB,e,{length:1,0:3},1),3!==e[1]})),mB=pB&&rB.NATIVE_ARRAY_BUFFER_VIEWS&&oB((function(){var e=new cB(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));hB("set",(function(e){lB(this);var t=nB(arguments.length>1?arguments[1]:void 0,1),r=sB(e);if(pB)return tB(dB,this,r,t);var i=this.length,n=iB(r),s=0;if(n+t>i)throw aB("Wrong length");for(;s<n;)this[t+s]=r[s++]}),!pB||mB);var fB=X$,gB=xl,vB=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("slice",(function(e,t){for(var r=gB(vB(this),e,t),i=fB(this),n=0,s=r.length,o=new i(s);s>n;)o[n]=r[n++];return o}),O((function(){new Int8Array(1).slice()})));var yB=ds.some,_B=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("some",(function(e){return yB(_B(this),e,arguments.length>1?arguments[1]:void 0)}));var bB=we.match(/firefox\/(\d+)/i),SB=!!bB&&+bB[1],IB=/MSIE|Trident/.test(we),EB=we.match(/AppleWebKit\/(\d+)\./),TB=!!EB&&+EB[1],RB=te,wB=O,AB=Je,kB=Sf,CB=SB,MB=IB,OB=Le,PB=TB,LB=iN.aTypedArray,xB=iN.exportTypedArrayMethod,DB=C.Uint16Array,NB=DB&&RB(DB.prototype.sort),$B=!(!NB||wB((function(){NB(new DB(2),null)}))&&wB((function(){NB(new DB(2),{})}))),UB=!!NB&&!wB((function(){if(OB)return OB<74;if(CB)return CB<67;if(MB)return!0;if(PB)return PB<602;var e,t,r=new DB(516),i=Array(516);for(e=0;e<516;e++)t=e%4,r[e]=515-e,i[e]=e-2*t+3;for(NB(r,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(r[e]!==i[e])return!0}));xB("sort",(function(e){return void 0!==e&&AB(e),UB?NB(this,e):kB(LB(this),function(e){return function(t,r){return void 0!==e?+e(t,r)||0:r!=r?-1:t!=t?1:0===t&&0===r?1/t>0&&1/r<0?1:-1:t>r}}(e))}),!UB||$B);var BB=Mi,VB=Ai,FB=X$,jB=iN.aTypedArray;(0,iN.exportTypedArrayMethod)("subarray",(function(e,t){var r=jB(this),i=r.length,n=VB(e,i);return new(FB(r))(r.buffer,r.byteOffset+n*r.BYTES_PER_ELEMENT,BB((void 0===t?i:VB(t,i))-n))}));var WB=Ll,qB=iN,GB=O,HB=xl,zB=C.Int8Array,JB=qB.aTypedArray,YB=qB.exportTypedArrayMethod,KB=[].toLocaleString,QB=!!zB&&GB((function(){KB.call(new zB(1))}));YB("toLocaleString",(function(){return WB(KB,QB?HB(JB(this)):JB(this),HB(arguments))}),GB((function(){return[1,2].toLocaleString()!=new zB([1,2]).toLocaleString()}))||!GB((function(){zB.prototype.toLocaleString.call([1,2])})));var XB=iN.exportTypedArrayMethod,ZB=O,eV=te,tV=C.Uint8Array,rV=tV&&tV.prototype||{},iV=[].toString,nV=eV([].join);ZB((function(){iV.call({})}))&&(iV=function(){return nV(this)});var sV=rV.toString!=iV;XB("toString",iV,sV);var oV=function(){function e(t,r,i){a(this,e),this.isUplink_=i,this.connection_=t,this.log_=r,this.seiMessageList_=[],this.seiPayloadType_=243,this.senderOrReceiver_=null,this.abortController_=null,this.abortMap_=new Map,this.onSEIMessage=null}return u(e,[{key:"isRunning",get:function(){return!!this.abortController_}},{key:"start",value:function(e){this.senderOrReceiver_=e;var t=e.createEncodedStreams(),r=t.readable,i=t.writable,n=new TransformStream({transform:this.isUplink_?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this.abortController_=new AbortController,r.pipeThrough(n).pipeTo(i,{signal:this.abortController_.signal}).catch((function(){}))}},{key:"restart",value:function(e){this.stop(),this.start(e)}},{key:"stop",value:function(){var e;null===(e=this.abortController_)||void 0===e||e.abort(),this.abortController_=null}},{key:"destory",value:function(){this.stop(),this.abortMap_.forEach((function(e){return e.abort()})),this.abortMap_.clear(),this.log_=null,this.onSEIMessage=null,this.senderOrReceiver_=null,this.connection_=null}},{key:"handleEncodedStreams",value:function(){var e=this;try{var t=this.connection_.getPeerConnection();if(this.clearUnusedSenderOrReceiver(t),this.isUplink_){var r,i=null===(r=this.connection_.getLocalStream())||void 0===r?void 0:r.getVideoTrack();t.getSenders().forEach((function(t){e.abortMap_.has(t)||t===e.senderOrReceiver_||(t.track&&t.track===i?e.isRunning?e.restart(t):e.start(t):e.pipeSenderOrReceiver(t))}))}else t.getReceivers().forEach((function(t,r){var i;e.abortMap_.has(t)||t===e.senderOrReceiver_||(1===r&&(null===(i=t.track)||void 0===i?void 0:i.kind)===AE?e.isRunning?e.restart(t):e.start(t):e.pipeSenderOrReceiver(t))}))}catch(e){this.log_.warn(e)}}},{key:"pipeSenderOrReceiver",value:function(e){var t=e.createEncodedStreams(),r=t.readable,i=t.writable,n=new AbortController;this.abortMap_.set(e,n),r.pipeTo(i,{signal:n.signal}).catch((function(){}))}},{key:"clearUnusedSenderOrReceiver",value:function(e){var t=this;this.abortMap_.forEach((function(r,i){(t.isUplink_?e.getSenders():e.getReceivers()).find((function(e){return e===i}))||(r.abort(),t.abortMap_.delete(i))}))}},{key:"push",value:function(e,t){t&&t.seiPayloadType&&(this.seiPayloadType_=t.seiPayloadType),this.seiMessageList_.push(e)}},{key:"hasSEI",value:function(e){var t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}},{key:"isEmptyFrame",value:function(e){return"empty"===e.type||0===e.data.byteLength}},{key:"getNaluCount",value:function(e){for(var t=0,r=0,i=new DataView(e),n=0;n<e.byteLength;n++)switch(i.getUint8(n)){case 0:t++;break;case 1:2!==t&&3!==t||r++,t=0;break;default:t=0}return r}},{key:"encodeVideoFrame",value:function(e,t){try{if(this.connection_.isH264&&this.seiMessageList_.length>0&&!this.isEmptyFrame(e)){var r=9-this.getNaluCount(e.data);if(r<=0)return;for(var i=this.seiMessageList_.splice(0,r).reverse().map(this.encodeSEINalu.bind(this)),n=i.reduce((function(e,t){return e+t.dataView.byteLength}),0),s=new ArrayBuffer(n+e.data.byteLength),o=new DataView(s),a=new DataView(e.data),c=0,u=0;u<i.length;u++)for(var d=0;d<i[u].dataView.byteLength;d++)o.setInt8(c++,i[u].dataView.getInt8(d));for(var l=0;l<e.data.byteLength;l++)o.setInt8(c++,a.getInt8(l));e.data=s,this.log_.debug("".concat(i.length," sei sent"))}}catch(e){this.log_.warn(e)}t.enqueue(e)}},{key:"decodeVideoFrame",value:function(e,t){var r=this;try{if(this.connection_.isH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){for(var i=[],n=new DataView(e.data),s=0,o=-1,a=-1,c=0;c<e.data.byteLength;c++){var u=n.getUint8(c);if(0===u)s++;else if(1===u){if(2===s||3===s){var d=c-s;if(-1===o?o=d:-1===a&&(a=d,i.push(new aV(new DataView(n.buffer.slice(o,a)))),o=d,a=-1),6!==n.getUint8(c+1)){e.data=new DataView(n.buffer.slice(d)).buffer;break}}s=0}else s=0}this.log_.debug("".concat(i.length," sei received")),rw(this.onSEIMessage)&&i.reverse().forEach((function(e){r.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer})}))}}catch(e){this.log_.warn(e)}t.enqueue(e)}},{key:"encodeSEINalu",value:function(e){var t=e.byteLength,r=parseInt(t/255),i=t%255,n=[];n.push(0,0,0,1,6,this.seiPayloadType_);for(var s=0;s<r;s++)n.push(255);n.push(i);var o=new DataView(e);return n.push.apply(n,I(new Uint8Array(o.buffer))),n.push(128),new aV(new DataView(new Uint8Array(n).buffer),!0)}}]),e}(),aV=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];a(this,e),this.dataView=t,this.isSEI&&(r?this.addPreventionByte():this.removePreventionByte())}return u(e,[{key:"addPreventionByte",value:function(){for(var e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,r=[],i=0,n=e;n<=t;n++){var s=this.dataView.getInt8(n);switch(s){case 0:case 1:case 2:case 3:2===i&&(r.push(3),i=0),0==s?i++:i=0,r.push(s);break;default:i=0,r.push(s)}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));var o=new DataView(new Uint8Array([].concat(I(new Uint8Array(this.dataView.buffer).slice(0,e)),r)).buffer);this.dataView=o}},{key:"removePreventionByte",value:function(){for(var e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,r=[],i=0,n=e;n<=t;n++)switch(this.dataView.getInt8(n)){case 0:i++,r.push(this.dataView.getInt8(n));break;case 3:2!==i&&r.push(this.dataView.getInt8(n)),i=0;break;default:r.push(this.dataView.getInt8(n)),i=0}var s=new DataView(new Uint8Array([].concat(I(new Uint8Array(this.dataView.buffer).slice(0,e)),r)).buffer);this.dataView=s}},{key:"isSEI",get:function(){return 6===this.dataView.getUint8(4)}},{key:"seiPayloadStartIndex",get:function(){for(var e=6,t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}},{key:"seiPayloadType",get:function(){return this.isSEI?this.dataView.getUint8(5):null}},{key:"seiPayload",get:function(){if(!this.isSEI)return null;for(var e=0,t=6,r=6;r<this.dataView.buffer.byteLength;r++){var i=this.dataView.getUint8(r);if(t++,255!==i){e+=i;break}e+=255}for(var n=new ArrayBuffer(e),s=new DataView(n),o=0;o<n.byteLength;o++,t++)s.setInt8(o,this.dataView.getInt8(t));return s}}]),e}(),cV=function(){function e(t){a(this,e),this.userId_=t.userId,this.tinyId_=t.tinyId,this.client_=t.client,this.sdpSemantics_=t.client.getSdpSemantics(),this.isUplink_=t.isUplink,this.log_=Lw.createLogger({id:"n|"+this.userId_,userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId(),isLocal:this.isUplink_}),this.signalChannel_=t.signalChannel,this.peerConnection_=null,this.isErrorObserved_=!1,this.emitter_=new Rw,this.currentState_=iT,this.waitForPeerConnectionConnectedPromise_=null,this.isReconnecting_=!1,this.reconnectionCount_=0,this.reconnectionTimer_=-1,this.isFirstConnection_=!0,this.delay_={audioDelay:0,videoDelay:0},this.enableSEI_=t.enableSEI,this.enableSEI_&&SC&&(this.sei_=new oV(this,this.log_,this.isUplink_))}var t;return u(e,[{key:"initialize",value:function(){var e={encodedInsertableStreams:this.enableSEI_&&SC,iceServers:this.client_.getIceServers(),iceTransportPolicy:this.client_.getIceTransportPolicy(),sdpSemantics:this.sdpSemantics_,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this.peerConnection_=new RTCPeerConnection(e),this.peerConnection_.onconnectionstatechange=this.onConnectionStateChange.bind(this)}},{key:"close",value:function(){this.log_.info("closing connection"),this.closePeerConnection(),this.sei_&&(this.sei_.destory(),this.sei_=null)}},{key:"closePeerConnection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.peerConnection_&&(this.peerConnection_.onconnectionstatechange=function(){},this.peerConnection_.close(),this.peerConnection_=null,e&&this.emitConnectionStateChangedEvent(iT))}},{key:"getDTLSTransportState",value:function(){if(!this.peerConnection_)return rT;var e=null;if(this.isUplink_){if(!fC()||0===this.peerConnection_.getSenders().length)return rT;e=this.peerConnection_.getSenders()[0].transport}else{if(!mC()||0===this.peerConnection_.getReceivers().length)return rT;e=this.peerConnection_.getReceivers()[0].transport}return e?e.state:rT}},{key:"onConnectionStateChange",value:function(e){var t=this.peerConnection_.iceConnectionState,r=this.getDTLSTransportState();if(this.log_.info("onConnectionStateChange() connectionState: "+e.target.connectionState),this.log_.info("ICE Transport state: ".concat(t,", DTLS Transport state: ").concat(r)),e.target.connectionState===aT&&this.emitConnectionStateChangedEvent(nT),"failed"===e.target.connectionState||e.target.connectionState===cT){var i="".concat(this.isUplink_?"uplink":"downlink"," ICE/DTLS Transport connection ").concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(r),n=new nk({message:i,code:ik.ICE_TRANSPORT_ERROR});dk.logFailedEvent({userId:this.client_.getUserId(),eventType:bT,error:n}),this.emitConnectionStateChangedEvent(iT),this.isErrorObserved_||this.emitter_.emit($C,n)}e.target.connectionState!==uT&&"completed"!==e.target.connectionState||(this.logSelectedCandidate(),dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:bT}),this.emitConnectionStateChangedEvent(oT))}},{key:"emitConnectionStateChangedEvent",value:function(e){e!==this.currentState_&&(this.currentState_===sT&&e===nT||(ww.emit(200,{client:this.client_,connection:this,prevState:this.currentState_,state:e}),this.emitter_.emit(UC,{prevState:this.currentState_,state:e}),this.currentState_=e))}},{key:"hitTest",value:function(e){return(0===e||"0"===e)&&this.isUplink_||e===this.tinyId_}},{key:"addEventInternal",value:function(e,t){var r=this.client_.getUserId(),i={eventId:e,eventDesc:t,timestamp:Hg(),userId:r,tinyId:this.client_.getTinyId()};this.isUplink_||(i.remoteUserId=this.userId_,i.remoteTinyId=this.tinyId_),ok(r,i)}},{key:"getPeerConnection",value:function(){return this.peerConnection_}},{key:"getClient",value:function(){return this.client_}},{key:"getUserId",value:function(){return this.userId_}},{key:"getTinyId",value:function(){return this.tinyId_}},{key:"logSelectedCandidate",value:(t=o(i().mark((function e(){var t,r,n,s,o,a,c;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.peerConnection_){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,this.peerConnection_.getStats();case 4:t=e.sent,r=R(t),e.prev=6,r.s();case 8:if((n=r.n()).done){e.next=18;break}if((s=S(n.value,2))[0],!IC(o=s[1])){e.next=16;break}return a=t.get(o.localCandidateId),c=t.get(o.remoteCandidateId),a&&this.log_.info("local candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port," ").concat(a.networkType||""," ").concat("relay"===a.candidateType?"relayProtocol:"+a.relayProtocol:"")),c&&this.log_.info("remote candidate: ".concat(c.candidateType," ").concat(c.protocol,":").concat(c.ip||c.address,":").concat(c.port)),e.abrupt("break",18);case 16:e.next=8;break;case 18:e.next=23;break;case 20:e.prev=20,e.t0=e.catch(6),r.e(e.t0);case 23:return e.prev=23,r.f(),e.finish(23);case 26:case"end":return e.stop()}}),e,this,[[6,20,23,26]])}))),function(){return t.apply(this,arguments)})},{key:"getCurrentState",value:function(){return this.currentState_}},{key:"waitForPeerConnectionConnected",value:function(){var e=this;return this.waitForPeerConnectionConnectedPromise_||(this.waitForPeerConnectionConnectedPromise_=new Promise((function(t,r){if(e.currentState_===oT)return t();var i=function(e){e.state===oT&&(clearTimeout(-1),o(),t())},n=function(t){t.client===e.client_&&(clearTimeout(-1),o(),r(new nk({code:ik.API_CALL_ABORTED,message:JR({key:GR,data:"leave room"})})))},s=function(t){var i=t.client,n=t.stream;!e.isUplink_&&i===e.client_&&n.getConnection()===e&&!e.peerConnection_&&(clearTimeout(-1),o(),r(new nk({code:ik.API_CALL_ABORTED,message:JR({key:GR,data:"unsubscribe stream"})})))},o=function(){ww.off(22,n,e),ww.off(Cw,s,e),e.emitter_.off(UC,i,e)};e.connectionTimeoutId_=setTimeout((function(){e.emitter_.off(UC,i,e);var t=new nk({code:ik.API_CALL_TIMEOUT,message:"connection timeout"});r(t)}),1e4),ww.on(22,n,e),e.emitter_.on(UC,i,e),e.isUplink_||ww.on(Cw,s,e)})),this.waitForPeerConnectionConnectedPromise_=this.waitForPeerConnectionConnectedPromise_.then((function(t){return e.waitForPeerConnectionConnectedPromise_=null,t})).catch((function(t){throw e.waitForPeerConnectionConnectedPromise_=null,t}))),this.waitForPeerConnectionConnectedPromise_}},{key:"getReconnectionCount",value:function(){return this.reconnectionCount_}},{key:"startReconnection",value:function(){this.isReconnecting_=!0,this.emitConnectionStateChangedEvent(sT),this.reconnect(),this.addEventInternal(this.isUplink_?32797:32800,"".concat(this.isUplink_?"uplink":"downlink","-connection is reconnecting"))}},{key:"stopReconnection",value:function(){this.log_.info("stop reconnection"),this.isReconnecting_=!1,this.reconnectionCount_=0,this.clearReconnectionTimer(),this.signalChannel_.off(3,this.reconnect,this)}},{key:"on",value:function(e,t,r){this.emitter_.on(e,t,r)}},{key:"off",value:function(e,t,r){this.emitter_.off(e,t,r)}},{key:"setDelay",value:function(e){var t=e.audioDelay,r=e.videoDelay;this.delay_={audioDelay:t,videoDelay:r}}},{key:"getDelay",value:function(){return this.delay_}},{key:"isH264",get:function(){var e,t;return!(null===(e=this.peerConnection_)||void 0===e||null===(t=e.remoteDescription)||void 0===t||!t.sdp.includes("H264"))}}]),e}(),uV=new(function(){function e(){a(this,e),this.set_=new Set,ww.on(1,this.add,this),ww.on(4,this.add,this),ww.on(5,this.delete,this),ww.on(22,this.delete,this)}return u(e,[{key:"add",value:function(e){var t=e.client,r=e.roomId;if("rtc"!==t.getMode()){var i=this.getKey(t.getUserId(),r||t.getRoomId(),t.getSDKAppId(),t.getUseStringRoomId());this.set_.add(i)}}},{key:"delete",value:function(e){var t=e.client;if("rtc"!==t.getMode()){var r=this.getKey(t.getUserId(),t.getRoomId(),t.getSDKAppId(),t.getUseStringRoomId());this.set_.delete(r)}}},{key:"getKey",value:function(e,t,r,i){return"".concat(r,"_").concat(t,"_").concat(e,"_").concat(i)}},{key:"isJoined",value:function(e){var t=e.userId,r=e.roomId,i=e.sdkAppId,n=e.client;return"rtc"!==n.getMode()&&this.set_.has(this.getKey(t,r,i,n.getUseStringRoomId()))}}]),e}());function dV(e,t,r,i){if(this.useStringRoomId_){if(!nw(e)||!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_ROOMID_STRING",data:t,link:{className:i,fnName:r}})})}else if(!(sw(e)&&/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_ROOMID_INTEGER",data:t,link:{className:i,fnName:r}})})}function lV(e,t,r,i){if(!/^[A-Za-z\d_-]*$/.test(e))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_STREAM_ID",data:t,link:{className:i,fnName:r}})})}var hV,pV,mV={createClient:{name:"clientConfig",required:!0,type:jT,properties:{sdkAppId:{required:!0,type:VT,allowEmpty:!1},userId:{required:!0,type:BT,allowEmpty:!1},userSig:{required:!0,type:BT,allowEmpty:!1},mode:{required:!0,type:BT,values:["rtc",YE]},useStringRoomId:{type:FT},autoSubscribe:{type:FT},enableAutoPlayDialog:{type:FT},streamId:{type:BT},userDefineRecordId:{type:BT},pureAudioPushMode:{type:VT,values:[1,2]},enableSEI:{type:FT}}},createStream:{name:"streamConfig",required:!0,type:jT,properties:{userId:{type:BT},audio:{type:FT},video:{type:FT},screen:{type:FT},screenAudio:{type:FT},microphoneId:{type:BT},cameraId:{type:BT},facingMode:{type:[BT,jT]},audioSource:{instanceOf:window.MediaStreamTrack},videoSource:{instanceOf:window.MediaStreamTrack}},validate:function(e){if(!iw(e.screen)&&e.screen&&iw(e.audio)&&(e.audio=!1),!(iw(e.audio)&&iw(e.video)||iw(e.audioSource)&&iw(e.videoSource)))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_CREATE_STREAM_SOURCE"})});if(!iw(e.screen)&&!0===e.screen&&!0===e.video)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_CREATE_STREAM_SCREEN"})});if(e.audio&&e.screenAudio)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_CREATE_STREAM_AUDIO"})});if(!0!==e.screen&&!0===e.screenAudio)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_CREATE_STREAM_SCREEN_AUDIO"})});if(!iw(e.screen)&&!0===e.screen&&!this.isScreenShareSupported())throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"NOT_SUPPORTED_CAPTURE"})})}}},fV={join:{name:"options",required:!0,properties:{roomId:{required:!0,type:[VT,BT],allowEmpty:!1,validate:dV},role:{type:[BT],values:[KE,QE]},privateMapKey:{type:[BT]}},validate:function(e){if(this.isJoined_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_JOIN"})});if(this.checkDestroy(),uV.isJoined({userId:this.userId_,roomId:e.roomId,sdkAppId:this.sdkAppId_,client:this}))throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"REPEAT_JOIN",data:this.userId_})})}},publish:{name:"stream",required:!0,instanceOf:QT,validate:function(e){if(!this.isJoined_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_PUBLISH"})});if(this.mode_===YE&&this.role_===QE)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_AUDIENCE"})});if(this.localStream_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_DUPLICATE_PUBLISHING"})});if(!e.getIsReadyToPublish())throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_INITIALIZE"})});if(this.notPublishWithoutH264Supported_)throw new nk({code:ik.NOT_SUPPORTED_H264,message:JR({key:BR})})}},unpublish:{name:"stream",required:!0,instanceOf:QT,validate:function(e){if(e!==this.localStream_){if(this.localStream_)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_UNPUBLISH"})});this.log_.warn("Client currently has no published stream, please call publish() first.")}}},subscribe:[{name:"stream",required:!0,instanceOf:XT,validate:function(e){if(!e.getConnection())throw new nk({code:ik.INVALID_OPERATION,message:JR({key:kR})});if(this.notSubscribeWithoutH264Supported_)throw new nk({code:ik.NOT_SUPPORTED_H264,message:JR({key:VR})})}},{name:"options",type:jT,properties:{audio:{type:FT},video:{type:FT}},validate:function(e){var t=e.audio,r=e.video;if(!(iw(t)||iw(r)||t||r))throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"SUBSCRIBE_ALL_FALSE"})})}}],unsubscribe:{name:"stream",required:!0,instanceOf:XT,validate:function(e){if(!e.getConnection())throw new nk({code:ik.INVALID_OPERATION,message:JR({key:kR})})}},switchRole:{name:"role",required:!0,values:[KE,QE],validate:function(){if(this.mode_!==YE)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_ROLE"})});if(!this.isJoined_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_OPERATION_SWITCH_ROLE"})})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:BT,validate:lV},appId:{type:VT,allowEmpty:!1},bizId:{type:VT,allowEmpty:!1},url:{type:BT,allowEmpty:!1}},validate:function(){if(this.isDestroyed_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:DR,data:{funName:"startPublishCDNStream"}})})}},startMixTranscode:{name:"config",required:!0,type:jT,properties:{mode:{type:BT,values:["preset-layout","manual"]},streamId:{type:BT,validate:lV},videoWidth:{type:VT,notLessThanZero:!0},videoHeight:{type:VT,notLessThanZero:!0},videoBitrate:{type:VT,notLessThanZero:!0,allowEmpty:!1},videoFramerate:{type:VT,validate:function(e,t,r,i){if(e<=0||e>30)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"MIX_PARAMS_VIDEO_FRAMERATE",link:{className:i,fnName:r}})})}},videoGop:{type:VT,validate:function(e,t,r,i){if(e<1||e>8)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"MIX_PARAMS_VIDEO_GOP",link:{className:i,fnName:r}})})}},audioSampleRate:{type:VT,notLessThanZero:!0},audioBitrate:{type:VT,validate:function(e,t,r,i){if(e<32||e>192)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"MIX_PARAMS_AUDIO_BITRATE",link:{className:i,fnName:r}})})}},audioChannels:{type:VT,values:[1,2]},backgroundColor:{type:VT},backgroundImage:{type:BT},mixUsers:{required:!0,type:"array",arrayItem:{require:!0,type:jT,properties:{userId:{required:!0,type:BT},roomId:{type:[BT,VT],validate:dV},pureAudio:{type:FT},width:{type:VT,notLessThanZero:!0},height:{type:VT,notLessThanZero:!0},locationX:{type:VT,notLessThanZero:!0},locationY:{type:VT,notLessThanZero:!0},zOrder:{type:VT},streamType:{type:BT,values:["main","auxiliary"]},renderMode:{type:VT,values:[0,1,2,4]}}}}},validate:function(e,t,r,i,n){var s=0,o=0,a=e.mixUsers,c=[];if(a.forEach((function(e,t){if(c.push(e.userId),!e.pureAudio){if(!e.zOrder||e.zOrder<1||e>15)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"MIX_PARAMS_USER_Z_ORDER",data:"config.mixUsers[".concat(t,"].zOrder"),link:{className:i,fnName:r}})});e.width+e.locationX>s&&(s=e.width+e.locationX),e.height+e.locationY>o&&(o=e.height+e.locationY)}})),c.indexOf(this.getUserId())<0)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"MIX_PARAMS_NOT_SELF",link:{className:i,fnName:r}})});if(e.videoWidth<s||e.videoHeight<o)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"MIX_PARAMS_USER_STREAM",link:{className:i,fnName:r}})})}},sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate:function(e){if(!SC)throw new nk({code:ik.NOT_SUPPORTED,message:JR({key:WR})});if(!this.enableSEI_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"SEI_DISABLED"})});if(e.byteLength>1e3)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"SEI_OVERSIZE",data:e.byteLength})});if(0===e.byteLength)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"SEI_EMPTY"})});if(!this.uplinkConnection_)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"SEI_BEFORE_PUBLISH"})});if(!this.localStream_.hasVideo())throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"SEI_NOT_VIDEO"})});var t=this.uplinkConnection_.isH264;if(!t)throw new nk({code:ik.NOT_SUPPORTED,message:JR({key:WR,data:t})})}},{name:"options",type:jT,properties:{seiPayloadType:{type:VT,values:[5,243]}}}]},gV={TRTC:mV,CLIENT:fV,LOCAL_STREAM:{switchDevice:[{name:"type",required:!0,type:BT,values:[wE,AE]},{name:"deviceId",required:!0,type:BT,validate:function(){if(this.screen_&&!this.audio_||this.audioSource_||this.videoSource_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_SWITCH_DEVICE"})});if(0===this.publishState_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_SWITCH_DEVICE_PUBLISHING"})})}}],setAudioCaptureVolume:{name:"volume",type:VT}},STREAM:{play:[{name:"elementId",required:!0,type:[BT,"HTMLDivElement"],validate:function(e,t,r){if(nw(e)){var i=document.getElementById(e);if(!i)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_ELEMENT_ID",data:{key:t,fnName:r}})});if(!(i instanceof HTMLDivElement))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_ELEMENT_ID_TYPE",data:{key:t,fnName:r,type:dw(i)}})})}}},{name:"options",type:jT,properties:{objectFit:{type:BT,values:["contain","cover","fill"]},muted:{type:FT},mirror:{type:FT}}}]}};function vV(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e,r,i){var n=i.value;return i.value=function(){for(var e=arguments.length,i=new Array(e),s=0;s<e;s++)i[s]=arguments[s];return _V.call(this,t,i,r,this.name_),n.apply(this,i)},i}}function yV(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e,r,n){var s=n.value;return n.value=o(i().mark((function e(){var n,o,a,c=arguments;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(n=c.length,o=new Array(n),a=0;a<n;a++)o[a]=c[a];return _V.call(this,t,o,r,this.name_),e.abrupt("return",s.apply(this,o));case 3:case"end":return e.stop()}}),e,this)}))),n}}function _V(e,t,r,i){try{for(var n=0;n<e.length;n++)bV.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:r,className:i})}catch(e){throw Lw.error(e),e}}function bV(e){var t=this,r=e.rule,i=e.value,n=e.key,s=e.fnName,o=e.className;if(iw(i)){if(r.required)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_PARAMETER_REQUIRED",data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})})}else{if(Array.isArray(r.type)){if(!r.type.map((function(e){return e.toLowerCase()})).includes(dw(i)))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:TR,data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})})}else if(!iw(r.type)&&dw(i)!==r.type)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:TR,data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})});if(!1===r.allowEmpty){var a=sw(i)&&(0===i||Number.isNaN(i)),c=nw(i)&&""===i.trim();if(a||c)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_PARAMETER_EMPTY",data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})})}if(r.notLessThanZero&&sw(i)&&i<0)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"CANNOT_LESS_THAN_ZERO",data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})});if(nw(r.instanceOf)){if(!i||i.name_!==r.instanceOf)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:RR,data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})})}else if(rw(r.instanceOf)&&!(i instanceof r.instanceOf))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:RR,data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})});if(r.values&&!r.values.includes(i))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_PARAMETER_RANGE",data:{key:n,rule:r,fnName:s,value:i},link:{className:o,fnName:s}})});var u=r.properties;ZR(u)&&aw(i)&&Object.keys(u).forEach((function(e){bV.call(t,{rule:u[e],value:i&&i[e],key:"".concat(n,".").concat(e),fnName:s,className:o})}));var d=r.arrayItem;ZR(d)&&cw(i)&&i.forEach((function(e,r){bV.call(t,{rule:d,value:e,key:"".concat(n,"[").concat(r,"]"),fnName:s,className:o})})),rw(r.validate)&&r.validate.call(this,i,n,s,o,this)}}Sn({target:"Number",stat:!0},{isNaN:function(e){return e!=e}});var SV=(hV=yV.apply(void 0,I(gV.STREAM.play)),w((pV=function(){function e(t){a(this,e),this.name_="Stream",this.userId_=t.userId,this.isRemote_=t.isRemote,this.type_=t.type,this.log_=Lw.createLogger({id:"s".concat(t.seq?t.seq:"","|").concat(this.userId_),userId:iw(t.client)?void 0:t.client.getUserId(),sdkAppId:iw(t.client)?void 0:t.client.getSDKAppId(),isLocal:!this.isRemote_,type:this.isRemote_?this.type_:""}),this.client_=null,iw(t.client)||(this.client_=t.client),this.mediaStream_=null,this.div_=null,this.isPlaying_=!1,this.connection_=null,this.audioPlayer_=null,this.videoPlayer_=null,this.muted_=!1,this.objectFit_="cover",this.mirror_=!1,this.id_="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),this.audioOutputDeviceId_=0,this.audioVolume_=1,this.emitter_=bw(new Rw,this.name_),this.connectionState_=iT,this.installEvents(),iw(t.mirror)||this.log_.warn('TRTC.createStream "mirror" option was deprecated since v4.12.1,please use localStream.play to set up preview mirror. refer to '.concat(iR,"/en/LocalStream.html#play. TRTC.createStream 接口的 mirror 选项从 v4.12.1 开始被废弃,请使用 localStream.play 设置本地流预览镜像,参考文档:").concat(iR,"/zh-cn/LocalStream.html#play。"))}var t,n,s,c,d;return u(e,[{key:"installEvents",value:function(){ww.on(301,this.restartPlayback,this)}},{key:"uninstallEvents",value:function(){ww.off(301,this.restartPlayback,this)}},{key:"getType",value:function(){return this.type_}},{key:"getLogger",value:function(){return this.log_}},{key:"isSubscribed",get:function(){return this.type_===eT&&this.connection_.isMainStreamSubscribed||this.type_===tT&&this.connection_.isAuxStreamSubscribed}},{key:"isMainVideoSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===eT&&e&&e.video}},{key:"isMainAudioSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===eT&&e&&e.audio}},{key:"isAuxVideoSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===tT&&e&&e.auxiliary}},{key:"isSmallVideoSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===eT&&e&&e.smallVideo}},{key:"emitConnectionStateChanged",value:function(e){e.state!==this.connectionState_&&(e.state!==iT&&this.isRemote_&&!this.isSubscribed||(this.emitter_.emit("connection-state-changed",e),this.connectionState_=e.state))}},{key:"setConnection",value:function(e){this.connection_!==e&&(e instanceof cV?(null!==this.connection_&&this.connection_.off(UC,this.emitConnectionStateChanged,this),e.on(UC,this.emitConnectionStateChanged,this)):null===e&&this.connection_.off(UC,this.emitConnectionStateChanged,this),this.connection_=e)}},{key:"getConnection",value:function(){return this.connection_}},{key:"play",value:(d=o(i().mark((function e(t,r){var n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.log_.info("stream ".concat(this.isPlaying_?"update":"start to"," play with elementId: ").concat(t," and options: ").concat(JSON.stringify(r),".")),!this.isPlaying_){e.next=9;break}return r&&!iw(r.muted)&&(this.muted_=r.muted),r&&!iw(r.objectFit)&&(this.objectFit_=r.objectFit),this.isScreenShare()?this.mirror_=!1:r&&!iw(r.mirror)&&(this.mirror_=r.mirror),this.audioPlayer_&&this.audioPlayer_.setMuted(this.muted_),this.videoPlayer_&&(this.videoPlayer_.setObjectFit(this.objectFit_),this.videoPlayer_.setMirror(this.mirror_)),this.elementId_!==t&&(n=t,nw(t)&&(n=document.getElementById(t)),n.appendChild(this.div_),this.elementId_=t),e.abrupt("return");case 9:return this.isPlaying_=!0,(s=document.createElement("div")).setAttribute("id","player_".concat(this.id_)),s.setAttribute("style","width: 100%; height: 100%; position: relative; background-color: black; overflow: hidden;"),o=t,nw(t)&&(o=document.getElementById(t)),o.appendChild(s),this.elementId_=t,this.div_=s,this.isRemote_||(this.muted_=!0),r&&!iw(r.muted)&&(this.muted_=r.muted),this.isScreenShare()&&(this.objectFit_="contain"),r&&!iw(r.objectFit)&&(this.objectFit_=r.objectFit),this.isScreenShare()?this.mirror_=!1:(this.isRemote_||(this.mirror_=!0),r&&!iw(r.mirror)&&(this.mirror_=r.mirror)),ww.emit(132,{stream:this}),e.next=26,Promise.all([this.playAudio(),this.playVideo()]);case 26:ww.emit(100,{stream:this});case 27:case"end":return e.stop()}}),e,this)}))),function(e,t){return d.apply(this,arguments)})},{key:"playAudio",value:(c=o(i().mark((function e(){var t,n,s=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasAudio()&&(!this.isRemote_||this.isMainAudioSubscribed)){e.next=2;break}return e.abrupt("return");case 2:if(t=this.getAudioTrack(),this.audioPlayer_||!t){e.next=17;break}return this.log_.info("create AudioPlayer and play"),this.audioPlayer_=new MP({stream:this,track:t,gainedTrack:null===(n=this.gain_)||void 0===n?void 0:n.audioTrack,div:this.div_,muted:this.muted_,outputDeviceId:this.audioOutputDeviceId_,volume:this.audioVolume_}),this.audioPlayer_.on(nM,(function(e){var t={type:wE,state:e.state,reason:e.reason};ww.emit(101,r({stream:s},t)),s.emitter_.emit(rM,t)})),e.prev=7,e.next=10,this.audioPlayer_.play();case 10:e.next=17;break;case 12:throw e.prev=12,e.t0=e.catch(7),this.client_&&this.client_.getEnableAutoPlayDialog()&&new tL,this.emitter_.emit(iM,e.t0),e.t0;case 17:case"end":return e.stop()}}),e,this,[[7,12]])}))),function(){return c.apply(this,arguments)})},{key:"playVideo",value:(s=o(i().mark((function e(){var t,n=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasVideo()&&(!this.isRemote_||this.isMainVideoSubscribed||this.isAuxVideoSubscribed||this.isSmallVideoSubscribed)){e.next=2;break}return e.abrupt("return");case 2:if(t=this.getVideoTrack(),this.videoPlayer_||!t){e.next=18;break}return ww.emit(134,{stream:this}),this.log_.info("create VideoPlayer and play"),this.videoPlayer_=new rL({stream:this,track:t,div:this.div_,muted:this.muted_,objectFit:this.objectFit_,mirror:this.mirror_}),this.videoPlayer_.on(nM,(function(e){var t={type:AE,state:e.state,reason:e.reason};ww.emit(101,r({stream:n},t)),n.emitter_.emit(rM,t)})),e.prev=8,e.next=11,this.videoPlayer_.play();case 11:e.next=18;break;case 13:throw e.prev=13,e.t0=e.catch(8),this.client_&&this.client_.getEnableAutoPlayDialog()&&new tL,this.emitter_.emit(iM,e.t0),e.t0;case 18:case"end":return e.stop()}}),e,this,[[8,13]])}))),function(){return s.apply(this,arguments)})},{key:"stopAudio",value:function(){this.audioPlayer_&&(this.log_.info("stop AudioPlayer"),this.audioPlayer_.stop(),this.audioPlayer_=null)}},{key:"stopVideo",value:function(){this.videoPlayer_&&(this.log_.info("stop VideoPlayer"),this.videoPlayer_.stop(),this.videoPlayer_=null)}},{key:"restartPlayback",value:function(){this.audioPlayer_&&!this.audioPlayer_.isPlaying&&this.restartAudio(),this.videoPlayer_&&!this.videoPlayer_.isPlaying&&this.restartVideo()}},{key:"restartAudio",value:function(){this.isPlaying_&&(this.stopAudio(),this.playAudio().catch((function(e){})))}},{key:"restartVideo",value:function(){this.isPlaying_&&(this.stopVideo(),this.playVideo().catch((function(e){})))}},{key:"stop",value:function(){this.isPlaying_&&(this.isPlaying_=!1,this.stopAudio(),this.stopVideo(),this.div_.parentNode.removeChild(this.div_))}},{key:"resume",value:(n=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isPlaying_){e.next=2;break}return e.abrupt("return");case 2:if(this.log_.info("resume"),!this.audioPlayer_){e.next=6;break}return e.next=6,this.audioPlayer_.resume();case 6:if(!this.videoPlayer_){e.next=9;break}return e.next=9,this.videoPlayer_.resume();case 9:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"close",value:function(){this.log_.info("close stream"),this.isPlaying_&&this.stop(),this.isRemote_||(this.mediaStream_&&(this.mediaStream_.preventEvent=1,this.mediaStream_.getTracks().forEach((function(e){e.stop()})),this.mediaStream_=null),this.uninstallEvents())}},{key:"muteAudio",value:function(){return this.addRemoteEvent(!0,wE),this.doEnableTrack(wE,!1)}},{key:"muteVideo",value:function(){return this.addRemoteEvent(!0,AE),this.doEnableTrack(AE,!1)}},{key:"unmuteAudio",value:function(){return this.addRemoteEvent(!1,wE),this.doEnableTrack(wE,!0)}},{key:"unmuteVideo",value:function(){return this.addRemoteEvent(!1,AE),this.doEnableTrack(AE,!0)}},{key:"addRemoteEvent",value:function(e,t){if(this.isRemote_&&this.client_){var r=this.client_.getUserId(),i="".concat(e?OE:PE," remote ").concat(t);ok(r,{eventId:t===wE?e?32785:32787:e?32784:32786,eventDesc:i,timestamp:(new Date).getTime(),userId:r,tinyId:this.client_.getTinyId(),remoteUserId:this.userId_,remoteTinyId:this.connection_.getTinyId()})}}},{key:"doEnableTrack",value:function(e,t){var r=!1;return e===wE?this.mediaStream_.getAudioTracks().forEach((function(e){r=!0,e.enabled=t})):this.mediaStream_.getVideoTracks().forEach((function(e){r=!0,e.enabled=t})),r}},{key:"getId",value:function(){return this.id_}},{key:"getUserId",value:function(){return this.userId_}},{key:"getTinyId",value:function(){return this.connection_?this.connection_.getTinyId():""}},{key:"isPlaying",value:function(){return this.isPlaying_}},{key:"setAudioOutput",value:(t=o(i().mark((function e(t){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.audioOutputDeviceId_=t,!this.audioPlayer_){e.next=4;break}return e.next=4,this.audioPlayer_.setSinkId(t);case 4:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"setAudioVolume",value:function(e){this.audioVolume_=e,this.log_.info("setAudioVolume to ".concat(e)),this.audioPlayer_&&this.audioPlayer_.setVolume(e)}},{key:"getAudioLevel",value:function(){var e=0;return this.audioPlayer_&&(e=this.audioPlayer_.getAudioLevel()),e}},{key:"getInternalAudioLevel",value:function(){var e=0;return this.audioPlayer_&&(e=this.audioPlayer_.getInternalAudioLevel()),e}},{key:"hasAudio",value:function(){if(this.isRemote_){if(!this.connection_)return!1;var e=this.connection_.getTrackState();return this.type_===eT&&e.audio}return!!this.getAudioTrack()}},{key:"hasVideo",value:function(){if(this.isRemote_){if(!this.connection_)return!1;var e=this.connection_.getTrackState();return this.type_===tT?e.auxiliary:e.video}return!!this.getVideoTrack()}},{key:"getSubscribedState",value:function(){return this.isRemote_&&this.connection_?this.connection_.getSubscribeState():null}},{key:"getAudioTrack",value:function(){var e=null;if(this.mediaStream_){var t=this.mediaStream_.getAudioTracks();t.length>0&&(e=t[0])}return e}},{key:"getVideoTrack",value:function(){var e=null;if(this.mediaStream_){var t=this.mediaStream_.getVideoTracks();t.length>0&&(e=t[0])}return e}},{key:"getVideoFrame",value:function(){return this.videoPlayer_?this.videoPlayer_.getVideoFrame():null}},{key:"getMediaStream",value:function(){return this.mediaStream_}},{key:"setMediaStream",value:function(e){e!==this.mediaStream_&&(this.mediaStream_&&this.mediaStream_.getTracks().forEach((function(e){return e.stop()})),this.mediaStream_=e)}},{key:"updateVideoPlayingState",value:function(e){this.isPlaying_&&(e?(this.log_.info("playing state updated, play video"),this.playVideo().catch((function(e){}))):(this.log_.info("playing state updated, stop video"),this.stopVideo()))}},{key:"updateAudioPlayingState",value:function(e){this.isPlaying_&&(e?(this.log_.info("playing state updated, play audio"),this.playAudio().catch((function(e){}))):(this.log_.info("playing state updated, stop audio"),this.stopAudio()))}},{key:"on",value:function(e,t,r){this.emitter_.on(e,t,r)}},{key:"off",value:function(e,t,r){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,r)}},{key:"isRemote",value:function(){return this.isRemote_}},{key:"isScreenShare",value:function(){return!this.isRemote_&&this.screen_||this.isRemote_&&this.getType()===kE}},{key:"getDiv",value:function(){return this.div_}},{key:"getObjectFit",value:function(){return this.objectFit_}},{key:"getMuted",value:function(){return this.muted_}},{key:"getClient",value:function(){return this.client_}}]),e}()).prototype,"play",[hV],Object.getOwnPropertyDescriptor(pV.prototype,"play"),pV.prototype),pV),IV=function(e){l(i,e);var t=y(i);function i(e){var n;a(this,i);var s={isRemote:!0,type:e.type},o=r(r({},e),s);return(n=t.call(this,o)).name_=XT,n.isStreamAddedEventEmitted_=!1,n.isAbleToCallSubscription_=!0,n}return u(i,[{key:"installEvents",value:function(){b(h(i.prototype),"installEvents",this).call(this),ww.on(kw,this.handleStreamSubscribed,this),ww.on(Cw,this.handleStreamUnsubscribed,this)}},{key:"uninstallEvents",value:function(){b(h(i.prototype),"uninstallEvents",this).call(this),ww.off(kw,this.handleStreamSubscribed,this),ww.off(Cw,this.handleStreamUnsubscribed,this)}},{key:"handleStreamSubscribed",value:function(e){e.client===this.client_&&e.stream===this&&this.connection_.getCurrentState()===oT&&this.emitConnectionStateChanged({prevState:iT,state:oT})}},{key:"handleStreamUnsubscribed",value:function(e){e.client===this.client_&&e.stream===this&&this.emitConnectionStateChanged({prevState:oT,state:iT})}},{key:"getType",value:function(){return b(h(i.prototype),"getType",this).call(this)}},{key:"getIsAbleToCallSubscription",value:function(){return this.isAbleToCallSubscription_}},{key:"setIsAbleToCallSubscription",value:function(e){this.isAbleToCallSubscription_=e}},{key:"setIsStreamAddedEventEmitted",value:function(e){this.isStreamAddedEventEmitted_=e}},{key:"getIsStreamAddedEventEmitted",value:function(){return this.isStreamAddedEventEmitted_}},{key:"getAudioTrack",value:function(){return this.connection_&&this.connection_.getTrackState().audio?b(h(i.prototype),"getAudioTrack",this).call(this):null}},{key:"getVideoTrack",value:function(){if(!this.connection_)return null;var e=this.connection_.getTrackState();return this.type_===eT&&!e.video||this.type_===tT&&!e.auxiliary?null:b(h(i.prototype),"getVideoTrack",this).call(this)}},{key:"close",value:function(){b(h(i.prototype),"close",this).call(this)}}]),i}(SV),EV=function(){function e(t){a(this,e),this.client_=t.client,this.subscribedStreams_=new Map,this.unsubscribedStreams_=new Map,this.subscriptedOptions_=new Map,this.autoRecoveryFlags_=new Map}var t,r,n;return u(e,[{key:"isEnabled",get:function(){return"webrtc"!==this.client_.getEnv()}},{key:"recover",value:(n=o(i().mark((function e(t){var r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.getUserId(),n=t.getType(),this.hasAutoRecoveryFlag(r,n)){e.next=5;break}return e.abrupt("return");case 5:if(s=this.getUnsubscribedStream(r,n)?"unsubscribe":"subscribe",e.prev=6,Lw.warn("recover() try to recover subscription [".concat(s,"][").concat(r,"][").concat(n,"]")),"subscribe"!==s){e.next=13;break}return e.next=11,this.recoverSubscription(r,t);case 11:e.next=15;break;case 13:return e.next=15,this.recoverUnsubscription(r,t);case 15:dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:RT}),Lw.warn("recover() recover successfully [".concat(s,"][").concat(r,"][").concat(n,"]")),e.next=23;break;case 19:e.prev=19,e.t0=e.catch(6),Lw.error("recover() recover failed [".concat(s,"][").concat(r,"][").concat(n,"]"),e.t0),dk.logFailedEvent({userId:this.client_.getUserId(),eventType:RT,error:e.t0});case 23:this.deleteAutoRecoveryFlag(r,n);case 24:case"end":return e.stop()}}),e,this,[[6,19]])}))),function(e){return n.apply(this,arguments)})},{key:"recoverSubscription",value:(r=o(i().mark((function e(t,r){var n,s,o,a,c;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.getOptions(t,r.getType()),s=this.getSubscribedStream(t,r.getType()),n&&s){e.next=4;break}return e.abrupt("return");case 4:o=this.getStreamMuteState(s),a=o.isAudioMuted,c=o.isVideoMuted,this.mergeStream(s,r),this.recoverPlayingState(s),a&&s.doEnableTrack(wE,!1),c&&s.doEnableTrack(AE,!1);case 9:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"recoverUnsubscription",value:(t=o(i().mark((function e(t,r){var n;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.getUnsubscribedStream(t,r.getType())){e.next=3;break}return e.abrupt("return");case 3:this.mergeStream(n,r);case 4:case"end":return e.stop()}}),e,this)}))),function(e,r){return t.apply(this,arguments)})},{key:"getStreamMuteState",value:function(e){var t={isAudioMuted:!1,isVideoMuted:!1},r=e.getMediaStream();return r&&(t.isAudioMuted=r.getAudioTracks().map((function(e){return e.enabled})).includes(!1),t.isVideoMuted=r.getVideoTracks().map((function(e){return e.enabled})).includes(!1)),t}},{key:"recoverPlayingState",value:function(e){var t=e.isPlaying(),r=e.getDiv();if(t&&r){var i=r.parentNode;e.stop(),e.play(i,{objectFit:e.getObjectFit(),muted:e.getMuted()})}}},{key:"mergeStream",value:function(e,t){var r=t.getConnection(),i=t.getMediaStream();e.setConnection(r),r.setRemoteStream(i.id,e),e.setMediaStream(i),e.updateAudioPlayingState(t.hasAudio()),e.updateVideoPlayingState(t.hasVideo())}},{key:"addSubscriptionRecord",value:function(e,t,r){var i=t.getType();if(this.subscribedStreams_.has(e))this.subscribedStreams_.get(e).set(i,t);else{var n=new Map;n.set(t.getType(),t),this.subscribedStreams_.set(e,n)}if(this.subscriptedOptions_.has(e))this.subscriptedOptions_.get(e).set(i,r);else{var s=new Map;s.set(t.getType(),r),this.subscriptedOptions_.set(e,s)}this.deleteUnsubscriptionRecord(e,i)}},{key:"addUnsubscriptionRecord",value:function(e,t){if(this.unsubscribedStreams_.has(e))this.unsubscribedStreams_.get(e).set(t.getType(),t);else{var r=new Map;r.set(t.getType(),t),this.unsubscribedStreams_.set(e,r)}this.deleteSubscriptionRecord(e,t.getType())}},{key:"getSubscribedStream",value:function(e,t){return this.subscribedStreams_.has(e)&&this.subscribedStreams_.get(e).has(t)?this.subscribedStreams_.get(e).get(t):null}},{key:"getOptions",value:function(e,t){return this.subscriptedOptions_.has(e)&&this.subscriptedOptions_.get(e).has(t)?this.subscriptedOptions_.get(e).get(t):null}},{key:"getUnsubscribedStream",value:function(e,t){return this.unsubscribedStreams_.has(e)&&this.unsubscribedStreams_.get(e).has(t)?this.unsubscribedStreams_.get(e).get(t):null}},{key:"deleteSubscriptionRecord",value:function(e,t){this.subscribedStreams_.has(e)&&this.subscribedStreams_.get(e).delete(t),this.subscriptedOptions_.has(e)&&this.subscriptedOptions_.get(e).delete(t)}},{key:"deleteUnsubscriptionRecord",value:function(e,t){this.unsubscribedStreams_.has(e)&&this.unsubscribedStreams_.get(e).delete(t)}},{key:"markAllStream",value:function(){for(var e=0,t=I(this.subscribedStreams_.entries());e<t.length;e++)for(var r=S(t[e],2),i=r[0],n=0,s=I(r[1].entries());n<s.length;n++){var o=S(s[n],1)[0];this.setAutoRecoveryFlag(i,o)}for(var a=0,c=I(this.unsubscribedStreams_.entries());a<c.length;a++)for(var u=S(c[a],2),d=u[0],l=0,h=I(u[1].entries());l<h.length;l++){var p=S(h[l],1)[0];this.setAutoRecoveryFlag(d,p)}}},{key:"setAutoRecoveryFlag",value:function(e,t){if(Lw.info("setAutoRecoveryFlag() mark [".concat(e,"][").concat(t,"]")),this.autoRecoveryFlags_.has(e))this.autoRecoveryFlags_.get(e).set(t);else{var r=new Map;r.set(t),this.autoRecoveryFlags_.set(e,r)}}},{key:"hasAutoRecoveryFlag",value:function(e,t){return!!this.isEnabled&&this.autoRecoveryFlags_.has(e)&&this.autoRecoveryFlags_.get(e).has(t)}},{key:"deleteAutoRecoveryFlag",value:function(e,t){this.autoRecoveryFlags_.has(e)&&this.autoRecoveryFlags_.get(e).delete(t)}},{key:"delete",value:function(e){this.unsubscribedStreams_.delete(e),this.subscribedStreams_.delete(e),this.subscriptedOptions_.delete(e),this.autoRecoveryFlags_.delete(e)}}]),e}(),TV=_R;Sn({target:"String",proto:!0,forced:SR("small")},{small:function(){return TV(this,"small","","")}});var RV,wV,AV=function(){function e(t){a(this,e),this.player_=t,this.canvas_=document.createElement("canvas"),this.canvasCtx_=this.canvas_.getContext("2d")}return u(e,[{key:"setCanvasRect",value:function(e,t){this.canvas_.width=e,this.canvas_.height=t}},{key:"drawVideoToCanvas",value:function(){var e=this.player_.getElement();this.canvasCtx_.drawImage(e,0,0,this.canvas_.width,this.canvas_.height)}},{key:"generateVideoTrackFromCanvasCapture",value:function(e){return this.canvas_.captureStream(e).getVideoTracks()[0]}},{key:"generateStreamFromTrack",value:function(e){var t=new MediaStream;return t.addTrack(e),t}},{key:"destroy",value:function(){this.player_.stop(),this.canvas_.width=0,this.canvas_.height=0,this.canvas_=null,this.canvasCtx_=null}},{key:"canvas",get:function(){return this.canvas_}},{key:"canvasCtx",get:function(){return this.canvasCtx_}},{key:"canDrawVideoToCanvas",get:function(){if(this.player_){var e=this.player_.getElement();if(e)return e.readyState===e.HAVE_ENOUGH_DATA}return!1}}]),e}(),kV=new Blob(["let width,height,offscreen,ctx;onmessage=function(e){const{action,data}=e.data;switch(action){case'render':offscreen=data.canvas;width=offscreen.width;height=offscreen.height;ctx=offscreen.getContext('2d');draw(data.readable,data.writable);break}};function draw(readable,writable){const transformer=new TransformStream({async transform(cameraFrame,controller){ctx.drawImage(cameraFrame,0,0,width,height);const frame=new VideoFrame(offscreen,{timestamp:cameraFrame.timestamp});cameraFrame.close();controller.enqueue(frame)}});readable.pipeThrough(transformer).pipeTo(writable)}"],{type:"application/javascript"}),CV=function(){function e(t){a(this,e);var r=t.videoTrack;this.width=void 0,this.height=void 0,this.canvas=null,this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:r}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}return u(e,[{key:"initWorker",value:function(){try{this.worker=new Worker(URL.createObjectURL(kV)),Lw.info("init worker processor success")}catch(e){Lw.warn("init worker processor failed. ".concat(e.error))}}},{key:"setCanvasRect",value:function(e,t){this.width=e,this.height=t,this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.offscreen=this.canvas.transferControlToOffscreen(),this.worker.postMessage({action:"render",data:{canvas:this.offscreen,readable:this.bigReadable,writable:this.smallWritable}},[this.offscreen,this.bigReadable,this.smallWritable])}},{key:"generatorVideoTrack",value:function(){var e=new MediaStream([this.smallGenerator]);return null==e?void 0:e.getTracks()[0]}},{key:"destroy",value:function(){this.worker.terminate()}}]),e}(),MV=function(){function e(t){a(this,e),this.localStream_=t,this.player_=null,this.processor_=null,this.initOffscreenSuccess_=!1}var t;return u(e,[{key:"initialize",value:(t=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(OC()&&(null===(t=navigator)||void 0===t?void 0:t.hardwareConcurrency)>=6)){e.next=13;break}return e.prev=1,e.next=4,this.initOffscreen();case 4:this.initOffscreenSuccess_=!0,Lw.info("Initialize VideoGenerator successfully!"),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(1),this.initCanvas();case 11:e.next=14;break;case 13:this.initCanvas();case 14:case"end":return e.stop()}}),e,this,[[1,8]])}))),function(){return t.apply(this,arguments)})},{key:"generateSmallVideoTrack",value:function(e){var t,r=this.getSmallVideoProfile(e);return this.initOffscreenSuccess_?(this.processor_.setCanvasRect(r.width,r.height),t=this.processor_.generatorVideoTrack()):(this.processor_.setCanvasRect(r.width,r.height),this.player_.setRect({width:r.width,height:r.height}),t=this.processor_.generateVideoTrackFromCanvasCapture(r.frameRate),this.interval_=eC.run(hR,this.render.bind(this),{fps:r.frameRate})),t}},{key:"render",value:function(){this.processor_.canDrawVideoToCanvas&&this.processor_.drawVideoToCanvas()}},{key:"destroy",value:function(){eC.clearTask(this.interval_),this.processor_&&this.processor_.destroy()}},{key:"initOffscreen",value:function(){this.processor_=new CV({videoTrack:this.localStream_.getVideoTrack()})}},{key:"initCanvas",value:function(){this.player_=new rL({stream:this.localStream_,track:this.localStream_.getVideoTrack(),muted:!0,objectFit:"cover",mirror:!1}),this.player_.play().then((function(){Lw.info("VideoGenerator: play local video success")})).catch((function(){Lw.error("VideoGenerator: Failed to play local video")})),this.processor_=new AV(this.player_)}},{key:"getSmallVideoProfile",value:function(e){var t,r=this.localStream_.getVideoTrack(),i=this.localStream_.getVideoProfile(),n=r.getSettings(),s=n&&n.width&&n.height?{width:n.width,height:n.height}:i,o=s.width*s.height,a=e.width*e.height;return Lw.info("big stream resolution: ".concat(s.height,"*").concat(s.width," small stream resolution: ").concat(e.height,"*").concat(e.width," ")),o>a?t=o/a:(Lw.warn("Small stream resolution is larger than big stream, which is invalid. big: ".concat(s.width," * ").concat(s.height," small: ").concat(e.width," * ").concat(e.height)),t=o/19200),{width:parseInt(s.width/Math.sqrt(t)),height:parseInt(s.height/Math.sqrt(t)),frameRate:e.frameRate}}}]),e}();function OV(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{retries:5,timeout:2e3};return function(t,r,i){var n=Mw({retryFunction:i.value,settings:e,onError:e.onError,onRetrying:e.onRetrying,onRetryFailed:e.onRetryFailed});return i.value=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return n.apply(this,t)},i}}var PV,LV,xV={voiceActivityDetection:!1},DV=(RV=OV({retries:1,timeout:0,onRetrying:function(e){this.log_.warn("connection timeout, retrying [".concat(e,"]"))},onError:function(e,t,r){e.message.includes("timeout")?(this.reset(),this.initialize(),t()):r(e)}}),w((wV=function(e){l(E,e);var t,r,n,s,c,d,p,m,f,g,v,_,I=y(E);function E(e){var t;return a(this,E),(t=I.call(this,e)).localStream_=null,t.exchangeSDPTimeout_=-1,t.smallGenerator_=null,t.isSDPExchanging_=!1,t.ssrc_={audio:0,video:0,small:0},t.canvasTrack_=null,t}return u(E,[{key:"initialize",value:function(){b(h(E.prototype),"initialize",this).call(this),this.installEvents()}},{key:"reset",value:function(){this.closePeerConnection(),this.uninstallEvents(),this.clearExchangeSDPTimeout(),this.canvasTrack_=null,this.localStream_&&this.localStream_.clearCanvas()}},{key:"close",value:function(){b(h(E.prototype),"close",this).call(this),this.reset(),this.emitConnectionStateChangedEvent(iT),this.smallGenerator_&&(this.smallGenerator_.destroy(),this.smallGenerator_=null)}},{key:"installEvents",value:function(){this.emitter_.on($C,this.handleError,this),this.emitter_.on(UC,this.handleConnectionStateChange,this)}},{key:"uninstallEvents",value:function(){this.emitter_.off($C,this.handleError,this),this.emitter_.off(UC,this.handleConnectionStateChange,this)}},{key:"publish",value:(_=o(i().mark((function e(t){var r,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.localStream_=t,r=t.getMediaStream(),this.log_.info("is publishing stream: ".concat(t.getId())),n=this.localStream_.getAudioTrack(),s=this.localStream_.getVideoTrack(),n&&(o=this.localStream_.getGainedTrack(),this.peerConnection_.addTrack(o||n,r)),!s){e.next=14;break}if((yE||vE)&&uw(s)?(this.canvasTrack_=this.localStream_.genCanvasTrack(s),this.peerConnection_.addTrack(this.canvasTrack_,r)):this.peerConnection_.addTrack(s,r),!this.client_.getIsEnableSmallStream()){e.next=14;break}return this.smallGenerator_=new MV(this.localStream_),e.next=12,this.smallGenerator_.initialize();case 12:a=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_),this.peerConnection_.addTrack(a,r);case 14:return e.next=16,this.connect();case 16:return e.abrupt("return",t);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return _.apply(this,arguments)})},{key:"updateMediaSettings",value:function(e){var t=this,r=this.getMediaSettings(e);this.signalChannel_.sendWaitForResponse({command:"update_constraint_config",data:r,responseCommand:tk.UPDATE_CONSTRAINT_CONFIG_RES}).then((function(e){0!==e.data.code&&t.log_.warn(e.data.message)})).catch(this.log_.warn)}},{key:"getMediaSettings",value:function(e){var t=this,r=this.client_.getSystemResult().detail,i=r.isH264EncodeSupported,n=r.isVp8EncodeSupported,s="";i?s="H264":n&&(s="VP8");var o={videoCodec:s,videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0};return CC?e.getTracks().forEach((function(e){var r=e.getSettings();if(e.kind===wE){var i=1;r.channelCount&&(i=r.channelCount),o.audioChannel=i,o.audioBps=1e3*t.localStream_.getAudioBitrate(),o.audioFs=r.sampleRate}else e.kind===AE&&(t.client_.getIsEnableSmallStream()&&(o.smallVideoWidth=t.client_.smallStreamConfig.width,o.smallVideoHeight=t.client_.smallStreamConfig.height,o.smallVideoFps=t.client_.smallStreamConfig.framerate,o.smallVideoBps=1e3*t.client_.smallStreamConfig.bitrate),o.videoWidth=r.width,o.videoHeight=r.height,o.videoFps=r.frameRate,o.videoBps=1e3*t.localStream_.getVideoBitrate())})):o=this.getMediaSettingsFromProfile(o),this.log_.info("updateMediaSettings: "+JSON.stringify(o)),o}},{key:"getMediaSettingsFromProfile",value:function(e){var t=this.localStream_;if(t){if(t.getAudioTrack()){var r=t.getAudioProfile();e.audioChannel=r.channelCount,e.audioBps=1e3*r.bitrate,e.audioFs=r.sampleRate}if(t.getVideoTrack()){var i=t.getVideoProfile();e.videoWidth=i.width,e.videoHeight=i.height,e.videoFps=i.frameRate,e.videoBps=1e3*i.bitrate}}return e}},{key:"addTrack",value:(v=o(i().mark((function e(t){var r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.peerConnection_){e.next=25;break}if(t.kind===AE&&(yE||vE)&&uw(t)&&(t=this.canvasTrack_=this.localStream_.genCanvasTrack(t)),this.log_.info("is adding ".concat(t.kind," track to current published local stream")),!(gC()&&this.peerConnection_.getTransceivers().findIndex((function(e){return"stopped"===e.direction}))>=0)){e.next=7;break}return this.log_.warn("transceiver is stopping, negotiate sdp first"),e.next=7,this.updateOffer(qT,t);case 7:if(!(r=this.peerConnection_.getSenders().find((function(e){return e.track&&e.track.kind===t.kind})))){e.next=14;break}return this.log_.warn("sender already exists, remove sender first"),n=r.track,this.removeSender(r),e.next=14,this.updateOffer(qT,n);case 14:if(s=this.localStream_.getMediaStream(),this.peerConnection_.addTrack(t,s),t.kind!==AE||!this.client_.getIsEnableSmallStream()){e.next=22;break}return this.smallGenerator_=new MV(this.localStream_),e.next=20,this.smallGenerator_.initialize();case 20:o=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_),this.peerConnection_.addTrack(o,s);case 22:return e.next=24,this.updateOffer(WT,t);case 24:ok(this.userId_,{eventId:t.kind===wE?32769:32768,eventDesc:"add ".concat(t.kind," track to current published stream"),timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_});case 25:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"isNeedToResetOfferOrder",value:function(){if("plan-b"===this.sdpSemantics_||!this.peerConnection_||!this.peerConnection_.localDescription)return!1;for(var e=this.peerConnection_.localDescription.sdp,t=Ak(e),r=0;r<t.media.length;r++)if(0===t.media[r].mid&&t.media[r].type===AE)return!0;return!1}},{key:"removeSender",value:function(e){var t=null;gC()&&(t=this.peerConnection_.getTransceivers().find((function(t){return t.sender&&t.sender.track===e.track}))),this.peerConnection_.removeTrack(e),t&&rw(t.stop)&&(this.log_.info("stop transceiver"),t.stop())}},{key:"removeTrack",value:(g=o(i().mark((function e(t){var r,n,s=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.peerConnection_||!fC()){e.next=15;break}if(t.kind===AE&&(yE||vE)&&this.canvasTrack_&&(t=this.canvasTrack_,this.localStream_.clearCanvas()),this.log_.info("is removing ".concat(t.kind," track from current published local stream")),t.kind!==AE||!this.isNeedToResetOfferOrder()){e.next=10;break}return this.reset(),this.initialize(),null===(r=this.localStream_.getMediaStream())||void 0===r||r.removeTrack(t),e.next=9,this.publish(this.localStream_);case 9:return e.abrupt("return");case 10:return(n=this.peerConnection_.getSenders()).forEach((function(e,r){t.kind===wE&&e.track===t&&s.removeSender(e),t.kind===AE&&e.track===t&&1===r&&(s.removeSender(e),n[2]&&s.removeSender(n[2]))})),e.next=14,this.updateOffer(qT,t);case 14:ok(this.userId_,{eventId:t.kind===wE?32771:32770,eventDesc:"remove ".concat(t.kind," track from current published stream"),timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_});case 15:case"end":return e.stop()}}),e,this)}))),function(e){return g.apply(this,arguments)})},{key:"replaceTrack",value:(f=o(i().mark((function e(t){var r,n,s,o,a,c,u;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.kind!==AE||!yE&&!vE||!this.canvasTrack_){e.next=2;break}return e.abrupt("return");case 2:if(vC()&&fC()){e.next=4;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"NOT_SUPPORTED_REPLACE_TRACK"})});case 4:if(this.peerConnection_){e.next=6;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:LR})});case 6:if(0!==(r=this.peerConnection_.getSenders()).length){e.next=9;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:LR})});case 9:n=R(r.entries()),e.prev=10,n.s();case 12:if((s=n.n()).done){e.next=28;break}if(o=S(s.value,2),a=o[0],!(c=o[1]).track||c.track.kind!==t.kind){e.next=26;break}if(this.log_.info("is replacing ".concat(2===a?"smallVideo":t.kind," track to current published local stream")),t.kind!==AE){e.next=25;break}if(1===a&&c.replaceTrack(t),2!==a||!this.smallGenerator_){e.next=25;break}return this.smallGenerator_.destroy(),this.smallGenerator_=new MV(this.localStream_),e.next=23,this.smallGenerator_.initialize();case 23:u=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig),c.replaceTrack(u);case 25:t.kind===wE&&c.replaceTrack(t);case 26:e.next=12;break;case 28:e.next=33;break;case 30:e.prev=30,e.t0=e.catch(10),n.e(e.t0);case 33:return e.prev=33,n.f(),e.finish(33);case 36:ok(this.userId_,{eventId:t.kind===wE?32783:32782,eventDesc:"replace ".concat(t.kind," track from current published stream"),timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_});case 37:case"end":return e.stop()}}),e,this,[[10,30,33,36]])}))),function(e){return f.apply(this,arguments)})},{key:"setBandwidth",value:(m=o(i().mark((function e(t,r,n){var s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isUplink_){e.next=2;break}return e.abrupt("return",n);case 2:if(yC()){e.next=4;break}return e.abrupt("return",r===AE?this.updateVideoBandwidthRestriction(n,t):this.updateAudioBandwidthRestriction(n,t));case 4:if(!(s=this.peerConnection_.getSenders().find((function(e){return e.track&&e.track.kind===r})))){e.next=20;break}return(o=s.getParameters()).encodings&&0!==o.encodings.length||(o.encodings=[{}]),"unlimited"===t?delete o.encodings[0].maxBitrate:o.encodings[0].maxBitrate=1e3*t,e.prev=9,e.next=12,s.setParameters(o);case 12:return this.log_.info(r+" bandwidth was set to "+t+" kbps"),e.abrupt("return",n);case 16:return e.prev=16,e.t0=e.catch(9),this.log_.info("failed to set bandwidth by setting maxBitrate: "+e.t0),e.abrupt("return",r===AE?this.updateVideoBandwidthRestriction(n,t):this.updateAudioBandwidthRestriction(n,t));case 20:return e.abrupt("return",n);case 21:case"end":return e.stop()}}),e,this,[[9,16]])}))),function(e,t,r){return m.apply(this,arguments)})},{key:"setSmallStreamBandwidth",value:(p=o(i().mark((function e(t,r){var n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isUplink_){e.next=2;break}return e.abrupt("return",r);case 2:if(yC()){e.next=4;break}return e.abrupt("return",this.updateSmallVideoBandwidthRestriction(r,t));case 4:if(!(n=this.peerConnection_.getSenders().filter((function(e){return e.track&&e.track.kind===AE}))[1])){e.next=20;break}return(s=n.getParameters()).encodings&&0!==s.encodings.length||(s.encodings=[{}]),"unlimited"===t?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=1e3*t,e.prev=9,e.next=12,n.setParameters(s);case 12:return this.log_.info("small stream bandwidth was set to "+t+" kbps"),e.abrupt("return",r);case 16:return e.prev=16,e.t0=e.catch(9),this.log_.info("failed to set small stream bandwidth by setting maxBitrate: "+e.t0),e.abrupt("return",this.updateSmallVideoBandwidthRestriction(r,t));case 20:return e.abrupt("return",r);case 21:case"end":return e.stop()}}),e,this,[[9,16]])}))),function(e,t){return p.apply(this,arguments)})},{key:"updateVideoBandwidthRestriction",value:function(e,t){var r="AS";return bI&&(r="TIAS",t*=1e3),-1===e.indexOf("b="+r+":")?e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/,"m=video $1\r\nc=IN $2\r\nb="+r+":"+t+"\r\n"):e.replace(new RegExp("b="+r+":.*\r\n"),"b="+r+":"+t+"\r\n")}},{key:"updateAudioBandwidthRestriction",value:function(e,t){var r="AS";return bI&&(r="TIAS",t*=1e3),e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb="+r+":"+t+"\r\n")}},{key:"updateSmallVideoBandwidthRestriction",value:function(e,t){var r="AS";bI&&(r="TIAS",t*=1e3);var i=/m=video (.*)\r\nc=IN (.*)\r\n/g,n=[],s=i.exec(e);for(n.push(s);null!==s;)s=i.exec(e),n.push(s);var o=n[n.length-2],a=e.slice(0,o.index),c=e.slice(o.index);return-1===e.indexOf("b="+r+":")?a+(c=c.replace(/m=video (.*)\r\nc=IN (.*)\r\n/,"m=video $1\r\nc=IN $2\r\nb="+r+":"+t+"\r\n")):a+(c=c.replace(new RegExp("b="+r+":.*\r\n"),"b="+r+":"+t+"\r\n"))}},{key:"removeBandwidthRestriction",value:function(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}},{key:"removeVideoOrientation",value:function(e){return e.replace(/urn:3gpp:video-orientation/,"")}},{key:"connect",value:(d=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.exchangeSDP();case 3:return e.next=5,this.waitForPeerConnectionConnected();case 5:e.next=11;break;case 7:throw e.prev=7,e.t0=e.catch(0),this.closePeerConnection(!0),e.t0;case 11:case"end":return e.stop()}}),e,this,[[0,7]])}))),function(){return d.apply(this,arguments)})},{key:"exchangeSDP",value:(c=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,this.isSDPExchanging_=!0,e.next=4,this.createOffer();case 4:return this.log_.info("createOffer success, sending offer to remote server"),e.next=7,this.doExchangeSDP();case 7:this.isSDPExchanging_=!1,e.next=14;break;case 10:throw e.prev=10,e.t0=e.catch(0),this.isSDPExchanging_=!1,e.t0;case 14:case"end":return e.stop()}}),e,this,[[0,10]])}))),function(){return c.apply(this,arguments)})},{key:"createOffer",value:(s=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.peerConnection_.createOffer(xV);case 3:return t=e.sent,e.next=6,this.peerConnection_.setLocalDescription(t);case 6:this.updateSSRC(t.sdp),dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:yT,kind:"offer"}),e.next=14;break;case 10:throw e.prev=10,e.t0=e.catch(0),dk.logFailedEvent({userId:this.client_.getUserId(),eventType:yT,kind:"offer",error:e.t0}),e.t0;case 14:case"end":return e.stop()}}),e,this,[[0,10]])}))),function(){return s.apply(this,arguments)})},{key:"doExchangeSDP",value:function(){var e=this;return new Promise((function(t,r){e.exchangeSDPTimeout_=setTimeout((function(){e.signalChannel_.off(tk.PUBLISH_RESULT,n),e.clearExchangeSDPTimeout();var t=new nk({code:ik.API_CALL_TIMEOUT,message:JR({key:"EXCHANGE_SDP_TIMEOUT"})});r(t)}),1e4);var n=function(){var n=o(i().mark((function n(s){var o,a,c;return i().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:if(i.prev=0,e.clearExchangeSDPTimeout(),o=s.data,a=o.code,c=o.message,0!==a){i.next=9;break}return i.next=6,e.acceptAnswer(s.data.data);case 6:t(),i.next=10;break;case 9:e.checkPublishResultCode(a,c);case 10:i.next=15;break;case 12:i.prev=12,i.t0=i.catch(0),r(i.t0);case 15:case"end":return i.stop()}}),n,null,[[0,12]])})));return function(e){return n.apply(this,arguments)}}(),s=e.getMediaSettings(e.localStream_.getMediaStream()),a={type:e.peerConnection_.localDescription.type,sdp:e.removeVideoOrientation(e.peerConnection_.localDescription.sdp),screen:e.localStream_.hasScreenTrack(),constraintConfig:s};e.signalChannel_.once(tk.PUBLISH_RESULT,n),e.log_.debug("sending sdp offer: "+a.sdp),e.signalChannel_.send("publish",a)}))}},{key:"setSDPDirection",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",i=Ak(e);return i.media.forEach((function(e){"all"!==r&&e.type!==r||(e.direction=t)})),kk(i)}},{key:"updateOffer",value:(n=o(i().mark((function e(t,r){var n,s,o,a,c,u,d;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.peerConnection_.createOffer(xV);case 3:return n=e.sent,bI&&(n.sdp=this.setSDPDirection(n.sdp,"sendrecv")),e.next=7,this.peerConnection_.setLocalDescription(n);case 7:return s=this.getMediaSettings(this.localStream_.getMediaStream()),o={action:t,trackId:r.id,kind:r.kind===AE?"bigVideo":r.kind,type:"offer",sdp:this.peerConnection_.localDescription.sdp,constraintConfig:s},this.log_.info("createOffer success, sending updated offer to remote server"),this.log_.debug("updatedOffer: "+o.sdp),e.next=13,this.signalChannel_.sendWaitForResponse({command:"publish_change",data:o,responseCommand:tk.UPDATE_OFFER_RESULT,timeout:1e4,commandDesc:"update offer"});case 13:return a=e.sent,c=a.data,u=c.code,d=c.message,0!==u&&this.checkPublishResultCode(u,d),e.next=18,this.acceptAnswer(a.data.data);case 18:this.updateSSRC(n.sdp),dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:yT,kind:"offer"}),e.next=27;break;case 22:throw e.prev=22,e.t0=e.catch(0),this.log_.error(e.t0),dk.logFailedEvent({userId:this.client_.getUserId(),eventType:yT,kind:"offer",error:e.t0}),e.t0;case 27:case"end":return e.stop()}}),e,this,[[0,22]])}))),function(e,t){return n.apply(this,arguments)})},{key:"acceptAnswer",value:(r=o(i().mark((function e(t){var r,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.localStream_.getVideoBitrate(),n=this.localStream_.getAudioBitrate(),e.prev=2,s=this.removeVideoOrientation(t.sdp),e.next=6,this.setBandwidth(r,AE,s);case 6:return s=e.sent,e.next=9,this.setBandwidth(n,wE,s);case 9:if(s=e.sent,!this.client_.getIsEnableSmallStream()){e.next=15;break}return o=this.client_.smallStreamConfig,e.next=14,this.setSmallStreamBandwidth(o.bitrate,s);case 14:s=e.sent;case 15:return a={type:t.type,sdp:s},e.next=18,this.peerConnection_.setRemoteDescription(a);case 18:this.sei_&&this.sei_.handleEncodedStreams(),this.log_.debug("accepted answer: "+s),dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:_T,kind:"answer"}),e.next=28;break;case 23:throw e.prev=23,e.t0=e.catch(2),dk.logFailedEvent({userId:this.client_.getUserId(),eventType:_T,kind:"answer",error:e.t0}),this.log_.error("failed to accept remote answer "+e.t0),e.t0;case 28:case"end":return e.stop()}}),e,this,[[2,23]])}))),function(e){return r.apply(this,arguments)})},{key:"sendMutedFlag",value:function(e){var t={audio:e.audio,bigVideo:e.video,auxVideo:e.auxVideo};this.log_.info("send muted state: ".concat(JSON.stringify(t))),this.signalChannel_.send("mute_uplink",t)}},{key:"getIsReconnecting",value:function(){return this.isReconnecting_}},{key:"reconnect",value:(t=o(i().mark((function e(){var t,r,n=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(-1===this.reconnectionTimer_){e.next=3;break}return this.log_.warn("reconnect() uplink is reconnecting, ignore current reconnection"),e.abrupt("return");case 3:if(!(this.reconnectionCount_>=30)){e.next=12;break}return this.log_.warn("SDK has tried reconnect uplink for ".concat(30," times, but all failed, please check your network")),this.stopReconnection(),t=new nk({code:ik.UPLINK_RECONNECTION_FAILED,message:JR({key:"UPLINK_RECONNECTION_FAILED"})}),dk.logFailedEvent({userId:this.client_.getUserId(),eventType:fT,error:t}),this.addEventInternal(32799,"uplink-connection reconnect fail"),this.emitConnectionStateChangedEvent(iT),this.emitter_.emit($C,t),e.abrupt("return");case 12:if(this.signalChannel_.getCurrentState()===XA){e.next=16;break}return this.log_.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this.signalChannel_.once(3,this.reconnect,this),e.abrupt("return");case 16:if(this.reconnectionCount_++,e.prev=17,this.log_.warn("reconnect() try to reconnect uplink [".concat(this.reconnectionCount_,"/").concat(30,"]")),r=tw(this.reconnectionCount_),this.reconnectionTimer_=setTimeout((function(){n.log_.warn("reconnect() uplink reconnect timeout(".concat(r/1e3,"s), try again")),n.clearReconnectionTimer(),n.reconnect()}),r),!(this.isSDPExchanging_||this.peerConnection_&&this.peerConnection_.connectionState===aT)){e.next=23;break}return e.abrupt("return");case 23:return e.next=25,this.signalChannel_.sendWaitForResponse({command:rk,responseCommand:tk.UNPUBLISH_RESULT,enableLog:!1});case 25:return this.reset(),this.initialize(),e.next=29,this.publish(this.localStream_);case 29:dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:fT}),this.log_.warn("reconnect() uplink reconnect successfully"),this.addEventInternal(32798,"uplink-connection reconnect success"),this.stopReconnection(),this.localStream_.syncMuteState(),e.next=38;break;case 36:e.prev=36,e.t0=e.catch(17);case 38:case"end":return e.stop()}}),e,this,[[17,36]])}))),function(){return t.apply(this,arguments)})},{key:"clearExchangeSDPTimeout",value:function(){-1!==this.exchangeSDPTimeout_&&(clearTimeout(this.exchangeSDPTimeout_),this.exchangeSDPTimeout_=-1)}},{key:"clearReconnectionTimer",value:function(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}},{key:"handleError",value:function(e){e.getCode()===ik.ICE_TRANSPORT_ERROR&&(this.isFirstConnection_&&(this.isFirstConnection_=!1,dk.logFailedEvent({userId:this.client_.getUserId(),eventType:mT,error:e})),this.isReconnecting_||this.startReconnection())}},{key:"handleConnectionStateChange",value:function(e){e.state===oT&&this.isFirstConnection_&&(this.isFirstConnection_=!1,dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:mT}),this.addEventInternal(32792,"uplink-connection is connected"))}},{key:"updateSSRC",value:function(e){var t=this;try{var r=0;Ak(e).media.forEach((function(e){if(e.type===wE){var i=e.ssrcs[0];i&&(t.ssrc_.audio=i.id)}else{var n=e.ssrcs[0];switch(r+=1){case 1:n&&(t.ssrc_.video=n.id);break;case 2:n&&(t.ssrc_.small=n.id)}}}))}catch(e){}}},{key:"getLocalStreamVideoTrackId",value:function(){if(this.peerConnection_){var e=this.peerConnection_.getSenders().filter((function(e){return e.track&&e.track.kind===AE}));if(e[0])return e[0].track.id}if(this.localStream_){var t=this.localStream_.getVideoTrack();if(t)return t.id}return""}},{key:"getSSRC",value:function(){return this.ssrc_}},{key:"checkPublishResultCode",value:function(e,t){if(0!==e)throw 1028===e?(this.log_.error(HR.NOT_SUPPORTED_H264ENCODE),new nk({code:ik.NOT_SUPPORTED_H264,message:JR({key:BR})})):new nk({code:ik.UNKNOWN,message:JR({key:FR,data:{signalResponse:tk.PUBLISH_RESULT,code:e,message:t}})})}},{key:"getLocalStream",value:function(){return this.localStream_}},{key:"sendSEI",value:function(e,t){this.sei_.push(e,t)}}]),E}(cV)).prototype,"publish",[RV],Object.getOwnPropertyDescriptor(wV.prototype,"publish"),wV.prototype),wV),NV=(PV=OV({retries:1,timeout:0,onRetrying:function(e){this.log_.warn("connection timeout, retrying [".concat(e,"]"))},onError:function(e,t,r){e.message.includes("timeout")?t():r(e)}}),w((LV=function(e){l(g,e);var t,n,s,c,d,p,m,f=y(g);function g(e){var t;return a(this,g),(t=f.call(this,e)).remoteStreams_=new Map,t.autoSubscribe=e.autoSubscribe,t.trackState_={audio:e.trackState.audio,video:e.trackState.video,auxiliary:e.trackState.auxiliary,smallVideo:e.trackState.smallVideo},t.ssrc_={audio:0,video:0,auxiliary:0},t.subscribeState_={audio:e.autoSubscribe,video:e.autoSubscribe,auxiliary:e.autoSubscribe,smallVideo:!1},t.isSDPExchanging_=!1,t.installEvents(),t}return u(g,[{key:"isMainStreamSubscribed",get:function(){return(this.subscribeState_.audio||this.subscribeState_.video||this.subscribeState_.smallVideo)&&(this.trackState_.audio||this.trackState_.video||this.trackState_.smallVideo)}},{key:"isAuxStreamSubscribed",get:function(){return this.subscribeState_.auxiliary&&this.trackState_.auxiliary}},{key:"isSmallStreamSubscribed",get:function(){return this.subscribeState_.smallVideo&&this.trackState_.smallVideo}},{key:"isBigStreamSubscribed",get:function(){return this.subscribeState_.video&&this.trackState_.video}},{key:"isStreamUnpublished",value:function(e){return e.getType()===VE?!this.trackState_.audio&&!this.trackState_.video:!this.trackState_.auxiliary}},{key:"initialize",value:function(){b(h(g.prototype),"initialize",this).call(this),this.peerConnection_.ontrack=this.onTrack.bind(this)}},{key:"close",value:function(){var e=this;b(h(g.prototype),"close",this).call(this),this.trackState_.audio=!1,this.trackState_.video=!1,this.trackState_.auxiliary=!1,this.emitConnectionStateChangedEvent(iT),this.remoteStreams_.forEach((function(t){var r=t;r.setConnection(null),r.uninstallEvents(),r.getIsStreamAddedEventEmitted()&&e.emitter_.emit(xC,{stream:r})})),this.remoteStreams_.clear(),this.uninstallEvents()}},{key:"installEvents",value:function(){var e=this;ww.on(Aw,this.onRemoteStreamUpdate,this),this.emitter_.on($C,(function(t){t.getCode()===ik.ICE_TRANSPORT_ERROR&&(e.isFirstConnection_&&(e.isFirstConnection_=!1,dk.logFailedEvent({userId:e.client_.getUserId(),eventType:gT,error:t})),e.isReconnecting_||e.startReconnection())})),this.emitter_.on(UC,(function(t){t.state===oT&&e.isFirstConnection_&&(e.isFirstConnection_=!1,dk.logSuccessEvent({userId:e.client_.getUserId(),eventType:gT}),e.addEventInternal(32793,"downlink-connection is connected"))}))}},{key:"uninstallEvents",value:function(){ww.removeListener(Aw,this.onRemoteStreamUpdate,this)}},{key:"onRemoteStreamUpdate",value:function(e){if(this.hitTest(e.tinyId)&&e.client===this.client_){this.updateTrackState(e.action,e.kind);var t=e.kind===kE?ZE:XE,r=this.remoteStreams_.get(t);if(!r)return;e.action===WT?this.handleRemoteAddTrack(e.kind,r):this.handleRemoteRemoveTrack(e.kind,r)}}},{key:"handleRemoteAddTrack",value:function(e,t){this.log_.info("remote add ".concat(e," track")),e===wE?t.updateAudioPlayingState(this.subscribeState_.audio):t.updateVideoPlayingState(e===kE?this.subscribeState_.auxiliary:this.subscribeState_.video||this.subscribeState_.smallVideo),t.getIsStreamAddedEventEmitted()?this.emitter_.emit(DC,{stream:t}):(this.emitter_.emit(LC,{stream:t}),this.currentState_===oT&&t.emitConnectionStateChanged({prevState:iT,state:oT}))}},{key:"handleRemoteRemoveTrack",value:function(e,t){t.getIsStreamAddedEventEmitted()&&(this.log_.info("remote remove ".concat(e," track")),e===kE||!this.trackState_.audio&&!this.trackState_.video?(this.log_.info("remote stream ".concat(t.getType()," removed")),this.currentState_===oT&&t.emitConnectionStateChanged({prevState:oT,state:iT}),this.emitter_.emit(xC,{stream:t})):(e===wE?t.updateAudioPlayingState(!1):(e!==CE||this.isSmallStreamSubscribed)&&t.updateVideoPlayingState(!1),this.emitter_.emit(DC,{stream:t})))}},{key:"updateTrackState",value:function(e,t){var r=e===WT;switch(t){case wE:this.trackState_.audio=r;break;case AE:this.trackState_.video=r;break;case kE:this.trackState_.auxiliary=r;break;case CE:this.trackState_.smallVideo=r}this.log_.info("trackState updated: ".concat(JSON.stringify(this.trackState_)))}},{key:"onTrack",value:function(e){var t=e.streams[0],r=e.track;if(this.log_.info("ontrack() kind: ".concat(r.kind," id: ").concat(r.id," streamId: ").concat(t.id)),this.sdpSemantics_===LT){var i=function(e){var t=gk.parse(e),r={audio:[],video:[]};return t.media.forEach((function(e){if(e.ssrcs){var t=e.ssrcs[0].id>>16&255;if(e.type===wE)r.audio.push(XE);else if(e.type==AE){var i=2===t?XE:ZE;r.video.push(i)}}})),r}(this.peerConnection_.remoteDescription.sdp);if(r.kind===wE){if(0===i.audio.length||t.id!==XE)return void this.log_.debug("skip this invalid audio track")}else if(-1===i.video.indexOf(t.id))return void this.log_.debug("skip this invalid video track: ".concat(r.id," msid: ").concat(t.id))}dk.logEvent({eventType:"ontrack",kind:r.kind});var n=!1,s=this.remoteStreams_.get(t.id),o=t.id===XE?eT:tT;if(iw(s)&&((s=new IV({type:o,userId:this.userId_,client:this.client_})).setConnection(this),this.remoteStreams_.set(t.id,s),n=!0),s.setMediaStream(t),r.kind===wE?s.updateAudioPlayingState(this.subscribeState_.audio):o===eT?s.updateVideoPlayingState(this.subscribeState_.video||this.subscribeState_.smallVideo):s.updateVideoPlayingState(this.subscribeState_.auxiliary),(o!==tT||this.trackState_.auxiliary)&&(o!==eT||this.trackState_.audio||this.trackState_.video)){var a=this.client_.getSubscriptionManager();a&&a.hasAutoRecoveryFlag(this.userId_,o)||(n?this.emitter_.emit(LC,{stream:s}):this.emitter_.emit(DC,{stream:s}))}}},{key:"addRRTRLine",value:function(e){var t=e.split("\r\n"),r=new Map;t.forEach((function(e,i){/^a=rtcp-fb:/.test(e)&&t[i+1]&&!/^a=rtcp-fb:/.test(t[i+1])&&r.set(i+1,e.match(/^a=rtcp-fb:\d+/)[0]+" rrtr")}));for(var i=I(r),n=0;n<i.length;n++){var s=S(i[n],2),o=s[0],a=s[1];t.splice(o+n,0,a)}return t.join("\r\n")}},{key:"addSPSDescription",value:function(e){var t=Ak(e);return t.media.forEach((function(e){e.type===AE&&e.fmtp.forEach((function(e){e.config+=";sps-pps-idr-in-keyframe=1"}))})),kk(t)}},{key:"removeSDESDescription",value:function(e){var t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=Ak(e);return r.media.forEach((function(e){e.ext=e.ext.filter((function(e){return!t.includes(e.uri)}))})),kk(r)}},{key:"isSubscriptionStateNotChanged",value:function(e,t){return e.getType()===eT?(null==t?void 0:t.audio)===this.subscribeState_.audio&&(null==t?void 0:t.video)===this.subscribeState_.video&&this.isSubscribeSmall(t):e.getType()===tT?!iw(t.video)&&this.subscribeState_.auxiliary===t.video:void 0}},{key:"isSubscribeSmall",value:function(e){return iw(e.smallVideo)&&!this.subscribeState_.smallVideo}},{key:"subscribe",value:(m=o(i().mark((function e(t,r){var n,s,o,a,c,u;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,o=r.emitEvent,a=void 0===o||o,c=t.getType(),"new"!==(null===(n=this.peerConnection_)||void 0===n?void 0:n.connectionState)&&(null===(s=this.peerConnection_)||void 0===s?void 0:s.connectionState)!==aT){e.next=6;break}return e.next=6,this.waitForPeerConnectionConnected();case 6:if(!this.isSubscriptionStateNotChanged(t,r)){e.next=13;break}if(this.peerConnection_){e.next=11;break}return this.initialize(),e.next=11,this.connect();case 11:case 26:return a&&iw(r.smallVideo)&&this.emitter_.emit(NC,{stream:t,result:!0}),e.abrupt("return",t);case 13:if(c===VE?(iw(r.audio)||(this.subscribeState_.audio=r.audio),iw(r.video)||(this.subscribeState_.video=r.video),this.subscribeState_.smallVideo=(null==r?void 0:r.smallVideo)||!1,this.addEventInternal(this.subscribeState_.audio?32777:32779,this.subscribeState_.audio?"subscribe audio":"unsubscribe audio"),this.addEventInternal(this.subscribeState_.video?32777:32779,this.subscribeState_.video?"subscribe video":"unsubscribe video"),this.addEventInternal(this.subscribeState_.smallVideo?32803:32804,this.subscribeState_.smallVideo?"subscribe smallVideo":"unsubscribe smallVideo")):iw(r.video)||(this.subscribeState_.auxiliary=r.video),this.log_.info("subscribe ".concat(c," stream with options ").concat(JSON.stringify(r)," current state: ").concat(JSON.stringify(this.subscribeState_))),!this.peerConnection_&&!this.isSDPExchanging_){e.next=23;break}return u=PT,this.isMainStreamSubscribed||this.isAuxStreamSubscribed||(u=OT),e.next=20,this.sendSubscription(u);case 20:c===VE?(t.updateAudioPlayingState(this.subscribeState_.audio),t.updateVideoPlayingState(this.subscribeState_.video||this.subscribeState_.smallVideo)):t.updateVideoPlayingState(this.subscribeState_.auxiliary),e.next=26;break;case 23:return this.initialize(),e.next=26,this.connect();case 30:if(e.prev=30,e.t0=e.catch(0),!this.client_.getIsJoined()||!this.isStreamUnpublished(t)){e.next=35;break}throw this.log_.warn("".concat(e.t0.message," ").concat(JSON.stringify(this.trackState_))),new nk({code:ik.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId_," unpublished stream")});case 35:throw e.t0;case 36:case"end":return e.stop()}}),e,this,[[0,30]])}))),function(e,t){return m.apply(this,arguments)})},{key:"unsubscribe",value:(p=o(i().mark((function e(t){var r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((r=t.getType())!==VE){e.next=10;break}if(this.isMainStreamSubscribed){e.next=5;break}return this.log_.info("main stream already unsubscribed"),e.abrupt("return",t);case 5:this.subscribeState_.audio=!1,this.subscribeState_.video=!1,this.subscribeState_.smallVideo=!1,e.next=14;break;case 10:if(this.isAuxStreamSubscribed){e.next=13;break}return this.log_.info("auxiliary stream already unsubscribed"),e.abrupt("return",t);case 13:this.subscribeState_.auxiliary=!1;case 14:return n=OT,(r===eT&&this.isAuxStreamSubscribed||r===tT&&this.isMainStreamSubscribed)&&(n=PT),this.log_.info("unsubscribe ".concat(r," stream with ").concat(JSON.stringify(this.subscribeState_))),e.next=19,this.sendSubscription(n);case 19:return t.updateVideoPlayingState(!1),t.updateAudioPlayingState(!1),n===OT&&((s=t.getMediaStream())&&s.getTracks().forEach((function(e){return s.removeTrack(e)})),this.closePeerConnection(),this.emitConnectionStateChangedEvent(iT)),this.addEventInternal(32779,"unsubscribe audio"),this.addEventInternal(32778,"unsubscribe video"),e.abrupt("return",t);case 25:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"sendSubscription",value:function(e){var t=this,r={srcTinyId:this.tinyId_,srcUserId:this.userId_},i="unsubscribe",n=tk.UNSUBSCRIBE_RESULT;return e===PT&&(r={audio:this.subscribeState_.audio,bigVideo:this.subscribeState_.video,auxVideo:this.subscribeState_.auxiliary,smallVideo:this.subscribeState_.smallVideo,srcTinyId:this.tinyId_},i="subscribe_change",n=tk.SUBSCRIBE_CHANGE_RESULT),this.signalChannel_.sendWaitForResponse({command:i,data:r,responseCommand:n,timeout:1e4}).then((function(r){var i=r.data;if(0!==i.code){var n=new nk({code:i.code,message:JR({key:"ERROR_MESSAGE",data:{type:e,message:i.message}})});throw t.log_.error(n),n}}))}},{key:"connect",value:(d=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.exchangeSDP();case 3:return e.next=5,this.waitForPeerConnectionConnected();case 5:e.next=11;break;case 7:throw e.prev=7,e.t0=e.catch(0),this.closePeerConnection(!0),e.t0;case 11:case"end":return e.stop()}}),e,this,[[0,7]])}))),function(){return d.apply(this,arguments)})},{key:"exchangeSDP",value:(c=o(i().mark((function e(){var t,r,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,this.isSDPExchanging_=!0,e.next=4,this.createOffer();case 4:return this.log_.info("createOffer success, sending offer to remote server"),t=this.peerConnection_.localDescription,r=t.type,n=t.sdp,s={type:r,sdp:n,srcUserId:this.userId_,srcTinyId:this.tinyId_,audio:this.subscribeState_.audio,bigVideo:this.subscribeState_.video,auxVideo:this.subscribeState_.auxiliary,smallVideo:this.subscribeState_.smallVideo},ww.emit(201,{client:this.client_,connection:this,userId:this.userId_,tinyId:this.tinyId_,role:20,subscribeState:this.subscribeState_,trackState:this.trackState_}),e.next=10,this.signalChannel_.sendWaitForResponse({command:"subscribe",commandDesc:"exchange sdp",data:s,responseCommand:tk.SUBSCRIBE_RESULT,timeout:1e4});case 10:if(o=e.sent,this.peerConnection_){e.next=15;break}throw a=new nk({code:ik.INVALID_OPERATION,message:JR({key:"STREAM_UNSUBSCRIBED"})}),this.log_.warn(a),a;case 15:return e.next=17,this.onSubscribeResult(o);case 17:this.isSDPExchanging_=!1,e.next=24;break;case 20:throw e.prev=20,e.t0=e.catch(0),this.isSDPExchanging_=!1,e.t0;case 24:case"end":return e.stop()}}),e,this,[[0,20]])}))),function(){return c.apply(this,arguments)})},{key:"createOffer",value:(s=o(i().mark((function e(){var t,r;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={voiceActivityDetection:!1},"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype&&this.sdpSemantics_===LT?(this.peerConnection_.addTransceiver(wE,{direction:"recvonly"}),this.peerConnection_.addTransceiver(AE,{direction:"recvonly"}),this.peerConnection_.addTransceiver(AE,{direction:"recvonly"})):(t.offerToReceiveAudio=!0,t.offerToReceiveVideo=!0),e.next=4,this.peerConnection_.createOffer(t);case 4:return r=e.sent,e.next=7,dC();case 7:return e.sent.isH264DecodeSupported||(this.log_.warn("remove h264 desc from sdp"),r.sdp=Mk(r.sdp)),r.sdp=this.addRRTRLine(r.sdp),r.sdp=this.addSPSDescription(r.sdp),r.sdp=Ck(r.sdp),this.sdpSemantics_===LT&&(r.sdp=this.removeSDESDescription(r.sdp)),e.next=16,this.peerConnection_.setLocalDescription(r);case 16:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"onSubscribeResult",value:(n=o(i().mark((function e(t){var n,s,o,a,c,u,d,l=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t&&t.data||{},s=n.code,o=n.message,a=void 0===o?"":o,c=t&&t.data&&t.data.data||{},u=c.type,d=c.sdp,77393!==s){e.next=5;break}throw this.log_.error(HR.NOT_SUPPORTED_H264DECODE),new nk({code:ik.NOT_SUPPORTED_H264,message:JR({key:VR})});case 5:if(e.prev=5,0===s){e.next=8;break}throw new nk({code:s,message:JR({key:"EXCHANGE_SDP_FAILED",data:{errMsg:a}})});case 8:return this.log_.debug("accept remote answer: "+d),e.next=11,this.peerConnection_.setRemoteDescription({type:u,sdp:d});case 11:this.sei_&&(this.sei_.handleEncodedStreams(),this.sei_.onSEIMessage=function(e){l.emitter_.emit(BC,r(r({},e),{},{userId:l.userId_}))}),this.updateSSRC(d),e.next=19;break;case 15:throw e.prev=15,e.t0=e.catch(5),this.log_.error(e.t0),e.t0;case 19:case"end":return e.stop()}}),e,this,[[5,15]])}))),function(e){return n.apply(this,arguments)})},{key:"updateSSRC",value:function(e){var t=this;try{Ak(e).media.forEach((function(e){if(e.type===wE){var r=e.ssrcs.find((function(e){return e.value.includes(XE)}));r&&(t.ssrc_.audio=r.id)}else{var i=e.ssrcs.find((function(e){return e.value.includes(XE)})),n=e.ssrcs.find((function(e){return e.value.includes(ZE)}));i&&(t.ssrc_.video=i.id),n&&(t.ssrc_.auxiliary=n.id)}}))}catch(e){}}},{key:"setRemoteStream",value:function(e,t){this.remoteStreams_.set(e,t)}},{key:"getSubscribeState",value:function(){return this.subscribeState_}},{key:"getTrackState",value:function(){return this.trackState_}},{key:"getSSRC",value:function(){return this.ssrc_}},{key:"getMainStream",value:function(){return this.remoteStreams_.get(XE)}},{key:"getAuxStream",value:function(){return this.remoteStreams_.get(ZE)}},{key:"getMainStreamVideoTrackId",value:function(){var e=this.getMainStream();if(e){var t=e.getVideoTrack();if(t)return t.id}return""}},{key:"getAuxStreamVideoTrackId",value:function(){var e=this.getAuxStream();if(e){var t=e.getVideoTrack();if(t)return t.id}return""}},{key:"reconnect",value:(t=o(i().mark((function e(){var t,r,n=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(-1===this.reconnectionTimer_){e.next=3;break}return this.log_.warn("reconnect() downlink is reconnecting, ignore current reconnection"),e.abrupt("return");case 3:if(!(this.reconnectionCount_>=30)){e.next=12;break}return this.log_.warn("SDK has tried reconnect downlink [".concat(this.userId_,"] for ").concat(30," times, but all failed, please check your network")),this.stopReconnection(),t=new nk({code:ik.DOWNLINK_RECONNECTION_FAILED,message:JR({key:"DOWNLINK_RECONNECTION_FAILED"})}),dk.logFailedEvent({userId:this.client_.getUserId(),eventType:vT,error:t}),this.addEventInternal(32802,"downlink-connection reconnect fail"),this.emitConnectionStateChangedEvent(iT),this.emitter_.emit($C,t),e.abrupt("return");case 12:if(this.signalChannel_.getCurrentState()===XA){e.next=16;break}return this.log_.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this.signalChannel_.once(3,this.reconnect,this),e.abrupt("return");case 16:if(this.reconnectionCount_++,this.log_.warn("reconnect() try to reconnect downlink [".concat(this.reconnectionCount_,"/").concat(30,"]")),r=tw(this.reconnectionCount_),this.reconnectionTimer_=setTimeout((function(){n.log_.warn("reconnect() downlink [".concat(n.userId_,"] reconnect timeout(").concat(r/1e3,"s), try again")),n.clearReconnectionTimer(),n.reconnect()}),r),!(this.isSDPExchanging_||this.peerConnection_&&this.peerConnection_.connectionState===aT)){e.next=22;break}return e.abrupt("return");case 22:return e.prev=22,this.closePeerConnection(),this.initialize(),e.next=27,this.connect();case 27:this.stopReconnection(),this.log_.warn("reconnect() downlink reconnect successfully"),dk.logSuccessEvent({userId:this.client_.getUserId(),eventType:vT}),this.addEventInternal(32801,"downlink-connection reconnect success"),this.recoverSubscription(),e.next=36;break;case 34:e.prev=34,e.t0=e.catch(22);case 36:case"end":return e.stop()}}),e,this,[[22,34]])}))),function(){return t.apply(this,arguments)})},{key:"recoverSubscription",value:function(){var e=this,t=this.client_.getSubscriptionManager();t&&I(this.remoteStreams_.values()).forEach((function(r){t.hasAutoRecoveryFlag(e.userId_,r.getType())&&t.recover(r)}))}},{key:"getIsReconnecting",value:function(){return this.isReconnecting_}},{key:"getSubscribedMainStream",value:function(){var e=null;return this.isMainStreamSubscribed&&(e=this.remoteStreams_.get(XE)),e}},{key:"clearReconnectionTimer",value:function(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}},{key:"startReconnection",value:function(){var e=this.client_.getSubscriptionManager();if(e){var t,r=R(this.remoteStreams_.values());try{for(r.s();!(t=r.n()).done;){var i=t.value,n=i.getType();(n===eT&&(this.trackState_.audio||this.trackState_.video)||n===tT&&this.trackState_.auxiliary)&&e.setAutoRecoveryFlag(this.userId_,i.getType())}}catch(e){r.e(e)}finally{r.f()}}b(h(g.prototype),"startReconnection",this).call(this)}},{key:"getCurrentState",value:function(){return this.currentState_}},{key:"hasMainStream",value:function(){return this.trackState_.video||this.trackState_.audio||this.trackState_.smallVideo}},{key:"hasAuxStream",value:function(){return this.trackState_.auxiliary}}]),g}(cV)).prototype,"subscribe",[PV],Object.getOwnPropertyDescriptor(LV.prototype,"subscribe"),LV.prototype),LV),$V=function(){function e(){a(this,e),this.startTime=0,this.endTime=0,this.start()}return u(e,[{key:"start",value:function(){0===this.startTime&&(this.startTime=hw())}},{key:"stop",value:function(){0===this.endTime&&(this.endTime=hw())}},{key:"getDuration",value:function(){return 0===this.endTime?hw()-this.startTime:this.endTime-this.startTime}}]),e}(),UV=function(){function e(t){a(this,e),this.client_=t.client,this.intervalId_=-1,this.statsCalculator_=t.stats,this.prevStats_=null,this.renderFreezeMap_=new Map,this.remoteStreamMap_=new Map,this.dataFreezeMap_=new Map,this.monitorFreezeData_=new Map}var t,r,n;return u(e,[{key:"installEvents",value:function(){ww.on(134,this.handlePlayVideoStart,this),ww.on(130,this.onVideoTrackMuted,this),ww.on(131,this.onVideoTrackUnmuted,this),ww.on(116,this.handleStreamStopped,this),ww.on(Cw,this.handleStreamStopped,this),ww.on(102,this.handleVideoPlaying,this)}},{key:"uninstallEvents",value:function(){ww.off(134,this.handlePlayVideoStart,this),ww.off(130,this.onVideoTrackMuted,this),ww.off(131,this.onVideoTrackUnmuted,this),ww.off(116,this.handleStreamStopped,this),ww.off(Cw,this.handleStreamStopped,this),ww.off(102,this.handleVideoPlaying,this)}},{key:"start",value:function(){var e=this;-1===this.intervalId_&&(this.installEvents(),this.intervalId_=eC.run(o(i().mark((function t(){return i().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.detectFPS();case 3:t.next=7;break;case 5:t.prev=5,t.t0=t.catch(0);case 7:case"end":return t.stop()}}),t,null,[[0,5]])}))),{delay:1e3}))}},{key:"stop",value:function(){-1!==this.intervalId_&&(this.uninstallEvents(),eC.clearTask(this.intervalId_),this.intervalId_=-1,this.renderFreezeMap_.clear(),this.dataFreezeMap_.clear(),this.remoteStreamMap_.clear())}},{key:"onVideoTrackMuted",value:function(e){var t=e.stream;if(t.getClient()===this.client_&&t.isRemote()){var r=t.userId_,i=t.type_,n="".concat(r,"_").concat(i),s=this.dataFreezeMap_.get(n),o=new $V;s?s.durationItemList.push(o):this.dataFreezeMap_.set(n,{userId:r,type:i,durationItemList:[o],isFreezing:function(){var e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}}},{key:"onVideoTrackUnmuted",value:function(e){var t=e.stream;if(t.getClient()===this.client_&&t.isRemote()){var r=t.userId_,i=t.type_,n="".concat(r,"_").concat(i);this.stopDataFreeze({key:n,userId:r,type:i})}}},{key:"handleStreamStopped",value:function(e){var t=e.client,r=e.stream;if(t===this.client_){var i=r.getUserId(),n=r.getType(),s="".concat(i,"_").concat(n);this.stopDataFreeze({key:s,userId:i,type:n})}}},{key:"stopDataFreeze",value:function(e){var t=e.key,r=e.userId,i=e.type,n=this.dataFreezeMap_.get(t);if(n&&n.isFreezing()){var s=n.durationItemList[n.durationItemList.length-1];s.stop();var o=s.getDuration();o>500?(dk.logEvent({eventType:"videoFrozenCount",delta:o}),this.monitorFreezeData_.set(t,{userId:r,type:i,duration:o})):n.durationItemList.pop()}}},{key:"getTotalDuration",value:function(e){return e.reduce((function(e,t){var r=t.getDuration();return e+Math.min(r,5e3)}),0)}},{key:"getStats",value:(n=o(i().mark((function e(){var t,r,n,s,o,a,c,u,d,l,h;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.client_.getConnections(),r={},n=R(t),e.prev=3,n.s();case 5:if((s=n.n()).done){e.next=20;break}if(o=S(s.value,2),a=o[0],(c=o[1]).getPeerConnection()){e.next=9;break}return e.abrupt("continue",18);case 9:return u=c.getSubscribeState(),d=c.getTrackState(),e.next=13,this.statsCalculator_.getReceiverStats(c);case 13:l=e.sent,(h={userId:l.userId,tinyId:a,hasVideo:d.video&&u.video,hasAuxiliary:d.auxiliary&&u.auxiliary,video:{framesDecoded:0},auxiliary:{framesDecoded:0}}).hasVideo&&(h.video.framesDecoded=l.video.framesDecoded),h.hasAuxiliary&&(h.auxiliary.framesDecoded=l.auxiliary.framesDecoded),r[l.userId]=h;case 18:e.next=5;break;case 20:e.next=25;break;case 22:e.prev=22,e.t0=e.catch(3),n.e(e.t0);case 25:return e.prev=25,n.f(),e.finish(25);case 28:return e.abrupt("return",r);case 29:case"end":return e.stop()}}),e,this,[[3,22,25,28]])}))),function(){return n.apply(this,arguments)})},{key:"detectFPS",value:(r=o(i().mark((function e(){var t,r,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getStats();case 2:if(t=e.sent,this.prevStats_){e.next=6;break}return this.prevStats_=t,e.abrupt("return");case 6:e.t0=i().keys(t);case 7:if((e.t1=e.t0()).done){e.next=17;break}if(r=e.t1.value,this.prevStats_[r]){e.next=11;break}return e.abrupt("continue",7);case 11:n=t[r].tinyId,s=this.client_.getMutedStates(),t[r].hasVideo&&this.prevStats_[r].hasVideo&&s.has(n)&&!s.get(n).videoMuted&&(o=t[r].video.framesDecoded-this.prevStats_[r].video.framesDecoded,this.handleRenderFreeze({userId:r,type:eT,fps:o})),t[r].hasAuxiliary&&this.prevStats_[r].hasAuxiliary&&(a=t[r].auxiliary.framesDecoded-this.prevStats_[r].auxiliary.framesDecoded,this.handleRenderFreeze({userId:r,type:tT,fps:a})),e.next=7;break;case 17:this.prevStats_=t;case 18:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"handleRenderFreeze",value:(t=o(i().mark((function e(t){var r,n,s,o,a,c,u,d;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=t.userId,n=t.fps,s=t.type,o="".concat(r,"_").concat(s),a=this.renderFreezeMap_.get(o),n<=2?(c=hw(),a&&!a.isFreeze&&(a.freezeTimeline.push({startTime:c,endTime:void 0}),a.isFreeze=!0),a||this.renderFreezeMap_.set(o,{userId:r,type:s,isFreeze:!0,freezeTimeline:[{startTime:c,endTime:void 0}],renderFreezeTotal:0})):a&&a.isFreeze&&(a.isFreeze=!1,(u=a.freezeTimeline.pop()).endTime=hw(),d=u.endTime-u.startTime,a.freezeTimeline.push(u),a.renderFreezeTotal+=Math.min(5e3,d));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"handlePlayVideoStart",value:function(e){var t=e.stream;if(t.getClient()===this.client_&&t.isRemote()&&t.hasVideo()){var r="".concat(t.getUserId(),"_").concat(t.getType());this.remoteStreamMap_.has(r)?this.remoteStreamMap_.get(r).remoteStream=t:this.remoteStreamMap_.set(r,{isPlayingFired:!1,remoteStream:t})}}},{key:"handleVideoPlaying",value:function(e){var t=e.stream;if(t.isRemote()&&t.getClient()===this.client_){var r="".concat(t.getUserId(),"_").concat(t.getType());this.remoteStreamMap_.has(r)&&(this.remoteStreamMap_.get(r).isPlayingFired=!0)}}},{key:"getDataFreezeDuration",value:function(e){var t={dataFreeze:0,count:0},r=this.dataFreezeMap_.get(e);if(r){if(r.isFreezing()){var i=r.durationItemList[r.durationItemList.length-1];i.stop(),i.getDuration()<500&&r.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(r.durationItemList),t.count=r.durationItemList.length}return t}},{key:"getRenderFreezeDuration",value:function(e){var t=this.renderFreezeMap_.get(e),r=0,i=0;if(t)if(t.isFreeze){var n=hw()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;r=t.renderFreezeTotal+Math.min(n,5e3),i=t.freezeTimeline.length}else r=t.renderFreezeTotal;return{renderFreeze:r,count:i}}},{key:"getMonitorFreeze",value:function(){return this.monitorFreezeData_}},{key:"isBlackStream",value:function(e){return!!this.remoteStreamMap_.has(e)&&!this.remoteStreamMap_.get(e).isPlayingFired}},{key:"resetMonitor",value:function(){this.monitorFreezeData_.clear()}}]),e}(),BV=u((function e(t){a(this,e),this.userId=t.userId,this.tinyId=t.tinyId,this.role=20===t.role?KE:QE})),VV={exports:{}};!function(e){!function(t){function r(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function i(e,t,i,n,s,o){return r((a=r(r(t,e),r(n,o)))<<(c=s)|a>>>32-c,i);var a,c}function n(e,t,r,n,s,o,a){return i(t&r|~t&n,e,t,s,o,a)}function s(e,t,r,n,s,o,a){return i(t&n|r&~n,e,t,s,o,a)}function o(e,t,r,n,s,o,a){return i(t^r^n,e,t,s,o,a)}function a(e,t,r,n,s,o,a){return i(r^(t|~n),e,t,s,o,a)}function c(e,t){var i,c,u,d,l;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var h=1732584193,p=-271733879,m=-1732584194,f=271733878;for(i=0;i<e.length;i+=16)c=h,u=p,d=m,l=f,h=n(h,p,m,f,e[i],7,-680876936),f=n(f,h,p,m,e[i+1],12,-389564586),m=n(m,f,h,p,e[i+2],17,606105819),p=n(p,m,f,h,e[i+3],22,-1044525330),h=n(h,p,m,f,e[i+4],7,-176418897),f=n(f,h,p,m,e[i+5],12,1200080426),m=n(m,f,h,p,e[i+6],17,-1473231341),p=n(p,m,f,h,e[i+7],22,-45705983),h=n(h,p,m,f,e[i+8],7,1770035416),f=n(f,h,p,m,e[i+9],12,-1958414417),m=n(m,f,h,p,e[i+10],17,-42063),p=n(p,m,f,h,e[i+11],22,-1990404162),h=n(h,p,m,f,e[i+12],7,1804603682),f=n(f,h,p,m,e[i+13],12,-40341101),m=n(m,f,h,p,e[i+14],17,-1502002290),h=s(h,p=n(p,m,f,h,e[i+15],22,1236535329),m,f,e[i+1],5,-165796510),f=s(f,h,p,m,e[i+6],9,-1069501632),m=s(m,f,h,p,e[i+11],14,643717713),p=s(p,m,f,h,e[i],20,-373897302),h=s(h,p,m,f,e[i+5],5,-701558691),f=s(f,h,p,m,e[i+10],9,38016083),m=s(m,f,h,p,e[i+15],14,-660478335),p=s(p,m,f,h,e[i+4],20,-405537848),h=s(h,p,m,f,e[i+9],5,568446438),f=s(f,h,p,m,e[i+14],9,-1019803690),m=s(m,f,h,p,e[i+3],14,-187363961),p=s(p,m,f,h,e[i+8],20,1163531501),h=s(h,p,m,f,e[i+13],5,-1444681467),f=s(f,h,p,m,e[i+2],9,-51403784),m=s(m,f,h,p,e[i+7],14,1735328473),h=o(h,p=s(p,m,f,h,e[i+12],20,-1926607734),m,f,e[i+5],4,-378558),f=o(f,h,p,m,e[i+8],11,-2022574463),m=o(m,f,h,p,e[i+11],16,1839030562),p=o(p,m,f,h,e[i+14],23,-35309556),h=o(h,p,m,f,e[i+1],4,-1530992060),f=o(f,h,p,m,e[i+4],11,1272893353),m=o(m,f,h,p,e[i+7],16,-155497632),p=o(p,m,f,h,e[i+10],23,-1094730640),h=o(h,p,m,f,e[i+13],4,681279174),f=o(f,h,p,m,e[i],11,-358537222),m=o(m,f,h,p,e[i+3],16,-722521979),p=o(p,m,f,h,e[i+6],23,76029189),h=o(h,p,m,f,e[i+9],4,-640364487),f=o(f,h,p,m,e[i+12],11,-421815835),m=o(m,f,h,p,e[i+15],16,530742520),h=a(h,p=o(p,m,f,h,e[i+2],23,-995338651),m,f,e[i],6,-198630844),f=a(f,h,p,m,e[i+7],10,1126891415),m=a(m,f,h,p,e[i+14],15,-1416354905),p=a(p,m,f,h,e[i+5],21,-57434055),h=a(h,p,m,f,e[i+12],6,1700485571),f=a(f,h,p,m,e[i+3],10,-1894986606),m=a(m,f,h,p,e[i+10],15,-1051523),p=a(p,m,f,h,e[i+1],21,-2054922799),h=a(h,p,m,f,e[i+8],6,1873313359),f=a(f,h,p,m,e[i+15],10,-30611744),m=a(m,f,h,p,e[i+6],15,-1560198380),p=a(p,m,f,h,e[i+13],21,1309151649),h=a(h,p,m,f,e[i+4],6,-145523070),f=a(f,h,p,m,e[i+11],10,-1120210379),m=a(m,f,h,p,e[i+2],15,718787259),p=a(p,m,f,h,e[i+9],21,-343485551),h=r(h,c),p=r(p,u),m=r(m,d),f=r(f,l);return[h,p,m,f]}function u(e){var t,r="",i=32*e.length;for(t=0;t<i;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function d(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var i=8*e.length;for(t=0;t<i;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function l(e){var t,r,i="0123456789abcdef",n="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),n+=i.charAt(t>>>4&15)+i.charAt(15&t);return n}function h(e){return unescape(encodeURIComponent(e))}function p(e){return function(e){return u(c(d(e),8*e.length))}(h(e))}function m(e,t){return function(e,t){var r,i,n=d(e),s=[],o=[];for(s[15]=o[15]=void 0,n.length>16&&(n=c(n,8*e.length)),r=0;r<16;r+=1)s[r]=909522486^n[r],o[r]=1549556828^n[r];return i=c(s.concat(d(t)),512+8*t.length),u(c(o.concat(i),640))}(h(e),h(t))}function f(e,t,r){return t?r?m(t,e):l(m(t,e)):r?p(e):l(p(e))}e.exports?e.exports=f:t.md5=f}(A)}(VV);var FV,jV,WV=VV.exports,qV=function(){function e(t){a(this,e),this.client_=t.client,this.signalChannel_=t.signalChannel,this.log_=Lw.createLogger({id:"mix|"+this.client_.getUserId(),userId:t.client.getUserId(),sdkAppId:t.client.getSDKAppId()}),this.isMixing_=!1,this.config_=null,this.data_=null,this.remoteStreamMap_=new Map,this.installEvents()}var t,r,n,s;return u(e,[{key:"isPresetLayoutMode",get:function(){return this.config_&&this.config_.mode===DT}},{key:"installEvents",value:function(){ww.on(kw,this.onStreamSubscribed,this),ww.on(Cw,this.onStreamUnsubscribed,this),this.client_.on("stream-removed",this.onStreamRemoved,this)}},{key:"uninstallEvents",value:function(){ww.off(kw,this.onStreamSubscribed,this),ww.off(Cw,this.onStreamUnsubscribed,this),this.client_.off("stream-removed",this.onStreamRemoved,this)}},{key:"reset",value:function(){this.uninstallEvents(),this.isMixing_=!1,this.config_=null}},{key:"onStreamSubscribed",value:function(e){var t=e.client,r=e.stream;t===this.client_&&(this.remoteStreamMap_.set(r.getId(),{remoteStream:r,isUsed:!1}),this.isMixing_&&this.hasAvailablePlaceHolder()&&this.startMixTranscode(this.config_))}},{key:"onStreamUnsubscribed",value:function(e){var t=e.client,r=e.stream;t===this.client_&&this.onStreamRemoved({stream:r})}},{key:"onStreamRemoved",value:function(e){var t=e.stream;if(this.remoteStreamMap_.has(t.getId())){var r=this.remoteStreamMap_.get(t.getId()).isUsed;this.remoteStreamMap_.delete(t.getId()),this.isMixing_&&this.isPresetLayoutMode&&r&&this.startMixTranscode(this.config_)}}},{key:"startMixTranscode",value:(s=o(i().mark((function e(t){var r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.resetIsUsedFlag(),this.config_=t,r=this.getInputParam(t,this.remoteStreamMap_),n=this.getOutputParam(t),s=this.getOutputSessionId({config:t,roomId:this.client_.getRoomId(),userId:this.client_.getUserId()}),!this.isMixing_||!this.data_||s===this.data_.outputSessionId){e.next=10;break}return this.log_.info("startMixTranscode() streamId changed, stop mixing before start"),e.next=10,this.doStopMixTranscode();case 10:return e.next=12,this.doStartMixTranscode({outputSessionId:s,inputParam:r,outputParam:n});case 12:e.next=18;break;case 14:throw e.prev=14,e.t0=e.catch(0),this.resetIsUsedFlag(),e.t0;case 18:case"end":return e.stop()}}),e,this,[[0,14]])}))),function(e){return s.apply(this,arguments)})},{key:"doStartMixTranscode",value:(n=o(i().mark((function e(t){var r,n,s,o,a,c,u,d;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.outputSessionId,n=t.inputParam,s=t.outputParam,o={roomId:String(this.client_.getRoomId()),mcuRequestTime:Date.now(),outputSessionId:r,inputParam:n,outputParam:s},this.data_=o,this.log_.info("startMixTranscode: ".concat(JSON.stringify(o))),this.isMixing_=!0,e.prev=5,e.next=8,this.signalChannel_.sendWaitForResponse({command:"start_mcu_mix",data:o,timeout:5e3,responseCommand:tk.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"});case 8:if(a=e.sent,c=a.data,u=c.code,d=c.message,0===u){e.next=15;break}throw-102083===u&&(d="Please enable relayed-push in ".concat(rR," and try later, refer to ").concat(nR,"tutorial-26-advanced-publish-cdn-stream.html")),this.log_.error("startMixTranscode failed, errCode: ".concat(u," errMsg: ").concat(d)),this.isMixing_=!1,new nk({code:ik.START_MIX_TRANSCODE_FAILED,message:JR({key:"START_MIX_TRANSCODE_FAILED",data:{message:d},link:{className:"Client",fnName:"startMixTranscode"}})});case 15:e.next=21;break;case 17:throw e.prev=17,e.t0=e.catch(5),this.isMixing_=!1,e.t0;case 21:case"end":return e.stop()}}),e,this,[[5,17]])}))),function(e){return n.apply(this,arguments)})},{key:"reStartMixTranscode",value:function(){this.isMixing_&&this.startMixTranscode(this.config_)}},{key:"stopMixTranscode",value:(r=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isMixing_){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"MIX_TRANSCODE_NOT_STARTED"})});case 2:return e.next=4,this.doStopMixTranscode();case 4:this.resetIsUsedFlag();case 5:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"doStopMixTranscode",value:(t=o(i().mark((function e(){var t,r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={mcuRequestTime:Date.now(),outputSessionId:this.data_.outputSessionId,streamType:this.data_.outputParam.streamType},this.log_.info("stopMixTranscode: ".concat(JSON.stringify(t))),e.next=4,this.signalChannel_.sendWaitForResponse({command:"stop_mcu_mix",data:t,timeout:5e3,responseCommand:tk.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"});case 4:if(r=e.sent,n=r.data,s=n.code,o=n.message,0!==s){e.next=10;break}this.isMixing_=!1,e.next=12;break;case 10:throw this.log_.error("stopMixTranscode failed, errCode: ".concat(s," errMsg: ").concat(o)),new nk({code:ik.STOP_MIX_TRANSCODE_FAILED,message:JR({key:"STOP_MIX_TRANSCODE_FAILED",data:{message:o},link:{className:"Client",fnName:"stopMixTranscode"}})});case 12:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"getOutputSessionId",value:function(e){var t=e.config,r=e.userId,i=e.roomId;return nw(t.streamId)&&t.streamId.length>0?t.streamId:WV("".concat(i,"_").concat(r,"_main"))}},{key:"getInputParam",value:function(e,t){var r=this,i=e.mixUsers.map((function(e){return{userId:e.userId,roomId:String(e.roomId||r.client_.getRoomId()),width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder,streamType:iw(e.streamType)||e.streamType!==tT?0:1,inputType:e.pureAudio?UT:$T,renderMode:e.renderMode||0}}));return e.mode===DT&&(i.forEach((function(e){if(e.userId===NT){var r=I(t.values()).find((function(e){return!e.isUsed}));r&&(e.userId=r.remoteStream.getUserId(),e.streamType=r.remoteStream.getType()===tT?1:0,r.isUsed=!0)}})),i=i.filter((function(e){return e.userId!==NT}))),i}},{key:"getOutputParam",value:function(e){var t=e.streamId||"";return{streamId:t,streamType:t.length>0?1:0,width:iw(e.videoWidth)?640:e.videoWidth,height:iw(e.videoHeight)?480:e.videoHeight,videoBps:e.videoBitrate||0,fps:e.videoFramerate||15,gop:e.videoGOP||2,audioSampleRate:e.audioSampleRate||48e3,audioBps:e.audioBitrate||64,audioChannels:e.audioChannels||1,backgroundColor:e.backgroundColor||0,backgroundImg:e.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}},{key:"hasAvailablePlaceHolder",value:function(){return!!this.isPresetLayoutMode&&this.data_.inputParam.length!==this.config_.mixUsers.length}},{key:"resetIsUsedFlag",value:function(){this.remoteStreamMap_.forEach((function(e){return e.isUsed=!1}))}}]),e}(),GV=function(){function e(t){a(this,e),this.client_=t.client,this.signalChannel_=t.signalChannel,this.isPublishingTencentCDN_=!1,this.publishTencentStreamRetryCount_=0,this.publishTencentStreamId_=void 0,this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1}var t,r,n,s,c;return u(e,[{key:"setSignalChannel",value:function(e){this.signalChannel_=e.signalChannel}},{key:"getIsPublishingTencentCDN",value:function(){return this.isPublishingTencentCDN_}},{key:"getIsPublishingGivenCDN",value:function(){return this.isPublishingGivenCDN_}},{key:"generatePublishCDNStreamId",value:function(e){if(!e){var t="".concat(this.client_.getRoomId(),"_").concat(this.client_.getUserId(),"_main");return/^[A-Za-z\d_-]*$/.test(t)||(t=WV(t)),"".concat(this.client_.getSDKAppId(),"_").concat(t)}return e}},{key:"startPublishTencentCDN",value:(c=o(i().mark((function e(t){var r,n;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isPublishingTencentCDN_=!0,this.publishTencentStreamId_=t.streamId,this.client_.isJoined_){e.next=4;break}return e.abrupt("return");case 4:return r=this.generatePublishCDNStreamId(t.streamId),n={requestTime:Date.now(),sessionId:WV("".concat(this.client_.getRoomId(),"_").concat(this.client_.getUserId(),"_main")),streamId:r,streamType:0},this.publishTencentStreamRetryCount_=0,e.next=9,this.doStartPublishTencentCDN(n);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"doStartPublishTencentCDN",value:(s=o(i().mark((function e(t){var r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,Lw.info("startPublishTencentCDN: "+JSON.stringify(t)),e.next=4,this.signalChannel_.sendWaitForResponseWithRetry({command:"start_publishing",data:t,timeout:2e3,responseCommand:tk.START_PUBLISH_TENCENT_CDN_RES,commandDesc:"startPublishCDNStream",retries:2});case 4:if(r=e.sent,n=r.data,s=n.code,o=n.message,0===s){e.next=12;break}throw this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,-102083===s&&(o="Please enable relayed-push in ".concat(rR," and try later, refer to ").concat(nR,"tutorial-26-advanced-publish-cdn-stream.html")),Lw.error("startPublishTencentCDN failed, errCode: ".concat(s,", errMsg: ").concat(o)),new nk({code:ik.START_PUBLISH_CDN_FAILED,message:JR({key:MR,data:{message:o},link:{className:"Client",fnName:"startPublishCDNStream"}})});case 12:e.next=19;break;case 14:throw e.prev=14,e.t0=e.catch(0),this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,e.t0;case 19:case"end":return e.stop()}}),e,this,[[0,14]])}))),function(e){return s.apply(this,arguments)})},{key:"stopPublishTencentCDN",value:(n=o(i().mark((function e(){var t,r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={requestTime:Date.now(),sessionId:WV("".concat(this.client_.getRoomId(),"_").concat(this.client_.getUserId(),"_main"))},Lw.info("stopPublishTencentCDN: "+JSON.stringify(t)),e.next=4,this.signalChannel_.sendWaitForResponse({command:"stop_publishing",data:t,timeout:5e3,responseCommand:tk.STOP_PUBLISH_TENCENT_CDN_RES,commandDesc:"stopPublishCDNStream"});case 4:if(r=e.sent,n=r.data,s=n.code,o=n.message,0!==s){e.next=11;break}this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,e.next=19;break;case 11:if(-102069!==s){e.next=17;break}Lw.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,e.next=19;break;case 17:throw Lw.error("stopPublishTencentCDN failed, errCode: ".concat(s," errMsg: ").concat(o)),new nk({code:ik.STOP_PUBLISH_CDN_FAILED,message:JR({key:OR,data:{message:o},link:{className:"Client",fnName:"stopPublishCDNStream"}})});case 19:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"startPublishGivenCDN",value:(r=o(i().mark((function e(t){var r,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r={pushRequestTime:Date.now(),pushAppId:t.appId,pushBizId:t.bizId,pushCdnUrl:t.url,pushStreamType:VE,pushStreamId:this.publishTencentStreamId_},Lw.info("startPublishGivenCDN: "+JSON.stringify(r)),this.publishGivenCDNData_=r,this.isPublishingGivenCDN_=!0,this.client_.isJoined_){e.next=6;break}return e.abrupt("return");case 6:return e.prev=6,e.next=9,this.signalChannel_.sendWaitForResponse({command:"start_push_user_cdn",data:r,timeout:5e3,responseCommand:tk.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDNStream"});case 9:if(n=e.sent,s=n.data,o=s.code,a=s.message,0===o){e.next=16;break}throw Lw.error("startPublishGivenCDN failed, errCode: ".concat(o,", errMsg: ").concat(a)),this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,new nk({code:ik.START_PUBLISH_CDN_FAILED,message:JR({key:MR,data:{message:a},link:{className:"Client",fnName:"startPublishCDNStream"}})});case 16:e.next=23;break;case 18:throw e.prev=18,e.t0=e.catch(6),this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,e.t0;case 23:case"end":return e.stop()}}),e,this,[[6,18]])}))),function(e){return r.apply(this,arguments)})},{key:"stopPublishGivenCDN",value:(t=o(i().mark((function e(){var t,r,n,s,o,a,c,u,d,l;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.publishGivenCDNData_,r=t.pushAppId,n=t.pushBizId,s=t.pushCdnUrl,o=t.pushStreamType,a={pushRequestTime:Date.now(),pushAppId:r,pushBizId:n,pushCdnUrl:s,pushStreamType:o},Lw.info("stopPublishGivenCDN: "+JSON.stringify(a)),e.next=5,this.signalChannel_.sendWaitForResponse({command:"stop_push_user_cdn",data:a,timeout:5e3,responseCommand:tk.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDNStream"});case 5:if(c=e.sent,u=c.data,d=u.code,l=u.message,0!==d){e.next=12;break}this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,e.next=14;break;case 12:throw Lw.error("stopPublishGivenCDN failed, errCode: ".concat(d," errMsg: ").concat(l)),new nk({code:ik.STOP_PUBLISH_CDN_FAILED,message:JR({key:OR,data:{message:l},link:{className:"Client",fnName:"stopPublishCDNStream"}})});case 14:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"handleCDNConfigForJoinData",value:function(e){var t,r=e;if(this.isPublishingTencentCDN_){var i={};nw(r)&&(i=JSON.parse(r)),i.Str_uc_params||(i.Str_uc_params={}),i.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this.publishTencentStreamId_),r=JSON.stringify(i)}if(this.isPublishingGivenCDN_){var n=this.publishGivenCDNData_,s=n.pushAppId,o=n.pushBizId,a=n.pushCdnUrl,c=n.pushStreamType,u=n.pushStreamId;t={pushRequestTime:Date.now(),pushAppId:s,pushBizId:o,pushCdnUrl:a,pushStreamType:c,pushStreamId:u}}return{bussinessInfo:r,pushUserCdnInfo:t}}},{key:"reset",value:function(){this.isPublishingTencentCDN_=!1,this.publishTencentStreamRetryCount_=0,this.publishTencentStreamId_=void 0,this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1}}]),e}(),HV=function(){function e(t){a(this,e),this.client_=t.client,this.durationMap_=new Map,this.installEvents()}return u(e,[{key:"installEvents",value:function(){ww.on(kw,this.handleSubscribed,this),ww.on(Aw,this.handleStreamTrackUpdated,this),ww.on(Cw,this.handleStreamStopped,this),ww.on(116,this.handleStreamStopped,this)}},{key:"uninstallEvents",value:function(){ww.off(kw,this.handleSubscribed,this),ww.off(Aw,this.handleStreamTrackUpdated,this),ww.off(Cw,this.handleStreamStopped,this),ww.off(116,this.handleStreamStopped,this)}},{key:"handleSubscribed",value:function(e){var t=e.client,r=e.stream;if(t===this.client_){var i=r.getUserId(),n=r.getType(),s="".concat(i,"_").concat(n);if(r.hasAudio())if(r.isMainAudioSubscribed){var o=new $V,a=this.durationMap_.get(s);a?this.isRecording(a.audio)||a.audio.push(o):this.durationMap_.set(s,{userId:i,type:n,audio:[o],video:[]})}else this.stopDurationItem(s,wE);if(r.hasVideo())if(n===eT&&r.isMainVideoSubscribed||n===tT&&r.isAuxVideoSubscribed){var c=new $V,u=this.durationMap_.get(s);u?this.isRecording(u.video)||u.video.push(c):this.durationMap_.set(s,{userId:i,type:n,audio:[],video:[c]})}else this.stopDurationItem(s,AE)}}},{key:"handleStreamStopped",value:function(e){var t=e.client,r=e.stream;if(this.clientHitTest(t)){var i=r.getUserId(),n=r.getType(),s="".concat(i,"_").concat(n);this.stopDurationItem(s,wE),this.stopDurationItem(s,AE)}}},{key:"handleStreamTrackUpdated",value:function(e){var t=e.client,r=e.userId,i=e.tinyId,n=e.kind,s=e.action;if(this.clientHitTest(t)&&this.client_.getConnections().has(i)){var o=n===kE?n:eT,a="".concat(r,"_").concat(o);if(s===WT){var c=this.client_.getConnections().get(i).getSubscribeState();if(n===wE&&!c.audio||n===AE&&!c.video||n===kE&&!c.auxiliary)return;var u=new $V,d=this.durationMap_.get(a);d?(n!==wE||this.isRecording(d.audio)||d.audio.push(u),n===wE||this.isRecording(d.video)||d.video.push(u)):this.durationMap_.set(a,{userId:r,type:o,audio:n===wE?[u]:[],video:n===wE?[]:[u]})}else this.stopDurationItem(a,n===wE?wE:AE)}}},{key:"isRecording",value:function(e){return e.findIndex((function(e){return 0===e.endTime}))>=0}},{key:"stopDurationItem",value:function(e,t){if(this.durationMap_.has(e)){var r=this.durationMap_.get(e)[t].find((function(e){return 0===e.endTime}));r&&r.stop()}}},{key:"clientHitTest",value:function(e){return this.client_===e}},{key:"getDuration",value:function(e,t){return this.durationMap_.has(e)?this.durationMap_.get(e)[t].reduce((function(e,t){return e+t.getDuration()}),0):0}},{key:"getDurationMap",value:function(){return this.durationMap_}},{key:"reset",value:function(){this.durationMap_.clear()}},{key:"destroy",value:function(){this.client_=null,this.uninstallEvents()}}]),e}(),zV=Sn,JV=O,YV=Pc.f;zV({target:"Object",stat:!0,forced:JV((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:YV});var KV=5e3,QV={msg_user_info:0,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0},XV=u((function e(t){a(this,e),this.str_identifier=String(t.userId),this.uint64_tinyid=Number(t.tinyId),this.uint32_role=t.role})),ZV=(FV=OV({timeout:500,retries:3}),w((jV=function(){function e(t){var r=this;a(this,e),this.frameWorkType_=t.frameWorkType||30,this.client_=t.client,this.keyPrefix_="key_point",this.storageKey_="".concat(this.keyPrefix_,"_").concat(this.client_.getUserId()),this.log_=Lw.createLogger({id:"kpm|"+this.client_.getUserId(),userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId()}),Object.getOwnPropertyNames(this.__proto__).forEach((function(e){e.startsWith("handle")&&rw(r[e])&&(r[e]=function(e){var t=e.fn,r=e.context;return o(i().mark((function e(){var n,s,o,a=arguments;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(e.prev=0,n=a.length,s=new Array(n),o=0;o<n;o++)s[o]=a[o];return e.next=4,t.apply(r||this,s);case 4:return e.abrupt("return",e.sent);case 7:e.prev=7,e.t0=e.catch(0),Lw.error("".concat(t.name,"() error observed ")+e.t0);case 10:case"end":return e.stop()}}),e,this,[[0,7]])})))}({fn:r[e],context:r}))})),this.initData(),this.installEvents(),this.intervalId_=eC.run(lR,this.setStorage.bind(this),{delay:2e4})}var t,n,s;return u(e,[{key:"initData",value:function(){this.firstPublishedUserList_=[],this.networkQuality_={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this.basicInfo={string_sdk_version:$o,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this.client_.getMode()?1:0,uint32_joining_duration:0,uint32_networkType:GT[XR()],uint32_framework:this.frameWorkType_},this.pathJoinRoom_={uint64_start_time:0,uint64_init_audio_start_time:0,uint64_init_audio_end_time:0,uint64_init_camera_start_time:0,uint64_init_camera_end_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_init_audio_ret:0,int32_init_camera_ret:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this.pathLeaveRoom_={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this.pathMainVideoMap_=new Map,this.pathMainAudioMap_=new Map,this.pathAuxiliaryMap_=new Map,this.localStreamStats_={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this.remoteStreamStatsMap_=new Map}},{key:"installEvents",value:function(){ww.on(1,this.handleJoinStart,this),ww.on(28,this.handleWSStart,this),ww.on(29,this.handleWSEnd,this),ww.on(2,this.handleJoinSendCMD,this),ww.on(3,this.handleJoinReceivedCMDResponce,this),ww.on(4,this.handleJoinSuccess,this),ww.on(5,this.handleJoinFailed,this),ww.on(24,this.handleReceivedPublishUserList,this),ww.on(200,this.handleConnectionStateChanged,this),ww.on(20,this.handleLeaveStart,this),ww.on(22,this.handleLeaveSuccess,this),ww.on(21,this.handleLeaveSendCMD,this),ww.on(201,this.handleSendSubscribeCMD,this),ww.on(102,this.handleVideoPlaying,this),ww.on(103,this.handleAudioPlaying,this),ww.on(300,this.handleNetworkQuality,this),ww.on(23,this.handleHeartbeatStats,this),ww.on(111,this.handleRemoteStreamAdded,this),ww.on(112,this.handleRemoteStreamSubscribeStart,this),ww.on(kw,this.handleRemoteStreamSubscribed,this),ww.on(133,this.handleVideoLoadedData,this),ww.on(132,this.handlePlayStream,this),ww.on(27,this.handlePublishStart,this),ww.on(121,this.handleLocalStreamInitStart,this),ww.on(122,this.handleLocalStreamInitEnd,this),ww.on(123,this.handleLocalStreamInitFailed,this)}},{key:"uninstallEvents",value:function(){ww.off(1,this.handleJoinStart,this),ww.off(28,this.handleWSStart,this),ww.off(29,this.handleWSEnd,this),ww.off(2,this.handleJoinSendCMD,this),ww.off(3,this.handleJoinReceivedCMDResponce,this),ww.off(24,this.handleReceivedPublishUserList,this),ww.off(200,this.handleConnectionStateChanged,this),ww.off(20,this.handleLeaveStart,this),ww.off(22,this.handleLeaveSuccess,this),ww.off(4,this.handleJoinSuccess,this),ww.off(5,this.handleJoinFailed,this),ww.off(21,this.handleLeaveSendCMD,this),ww.off(201,this.handleSendSubscribeCMD,this),ww.off(102,this.handleVideoPlaying,this),ww.off(103,this.handleAudioPlaying,this),ww.off(300,this.handleNetworkQuality,this),ww.off(23,this.handleHeartbeatStats,this),ww.off(111,this.handleRemoteStreamAdded,this),ww.off(112,this.handleRemoteStreamSubscribeStart,this),ww.off(kw,this.handleRemoteStreamSubscribed,this),ww.off(133,this.handleVideoLoadedData,this),ww.off(132,this.handlePlayStream,this),ww.off(27,this.handlePublishStart,this),ww.off(121,this.handleLocalStreamInitStart,this),ww.off(122,this.handleLocalStreamInitEnd,this),ww.off(123,this.handleLocalStreamInitFailed,this)}},{key:"destroy",value:function(){this.uninstallEvents(),eC.clearTask(this.intervalId_),this.client_=null}},{key:"handleJoinStart",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_start_time&&(this.pathJoinRoom_.uint64_start_time=Date.now(),this.checkStorage())}},{key:"handleWSStart",value:function(e){var t=e.client;this.hitTest(t)&&0===this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_start_time&&(this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_start_time=Date.now())}},{key:"handleWSEnd",value:function(e){var t=e.client,r=e.error;this.hitTest(t)&&0===this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_end_time&&(this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_end_time=Date.now(),r&&(this.pathJoinRoom_.int32_send_request_acc_ip_cmd_ret=r instanceof nk?Number(r.getExtraCode()||r.getCode()):ik.UNKNOWN,this.pathJoinRoom_.int32_end_ret=2))}},{key:"handleJoinSendCMD",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_send_request_enter_room_cmd_start_time&&(this.pathJoinRoom_.uint64_send_request_enter_room_cmd_start_time=Date.now())}},{key:"handleJoinReceivedCMDResponce",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_send_request_enter_room_cmd_end_time&&(this.pathJoinRoom_.uint64_send_request_enter_room_cmd_end_time=Date.now(),this.pathJoinRoom_.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this.pathJoinRoom_.int32_end_ret=3))}},{key:"handleJoinSuccess",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_end_time&&(this.pathJoinRoom_.uint64_end_time=Date.now(),this.pathJoinRoom_.int32_end_ret=0)}},{key:"handleJoinFailed",value:function(e){var t=e.client;this.hitTest(t)&&(this.pathJoinRoom_.uint64_end_time=Date.now(),0===this.pathJoinRoom_.int32_end_ret&&(this.pathJoinRoom_.int32_end_ret=3),this.prepareReport(),this.report())}},{key:"handleReceivedPublishUserList",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_recv_userlist_time&&(this.pathJoinRoom_.uint64_recv_userlist_time=Date.now(),this.firstPublishedUserList_=e.data.data&&e.data.data.userList||[])}},{key:"handleConnectionStateChanged",value:function(e){var t=e.client,r=e.state,i=e.connection;if(this.hitTest(t)&&r===oT){this.client_.getUplinkConnection()===i&&0===this.pathJoinRoom_.uint64_send_first_video_frame_time&&this.localStreamStats_.publishStartTime>this.pathJoinRoom_.uint64_end_time&&this.localStreamStats_.publishStartTime-this.pathJoinRoom_.uint64_end_time<=100&&(this.pathJoinRoom_.uint64_send_first_video_frame_time=Date.now());var n=this.pathMainVideoMap_.get("".concat(i.getUserId(),"_").concat(eT));n&&0===n.statsToReport.uint64_pc_connected_time&&(n.statsToReport.uint64_pc_connected_time=Date.now())}}},{key:"handleLeaveStart",value:function(e){this.hitTest(e.client)&&(this.pathLeaveRoom_.uint64_start_time=Date.now())}},{key:"handleLeaveSuccess",value:function(e){this.hitTest(e.client)&&0===this.pathLeaveRoom_.uint64_end_time&&(this.pathLeaveRoom_.uint64_end_time=Date.now(),0!==this.pathJoinRoom_.uint64_end_time?this.basicInfo.uint32_joining_duration=this.pathLeaveRoom_.uint64_end_time-this.pathJoinRoom_.uint64_end_time:this.log_.warn("pathJoinRoom endTime is 0"),this.report())}},{key:"handleLeaveSendCMD",value:function(e){this.hitTest(e.client)&&(this.pathLeaveRoom_.uint64_send_request_exit_room_cmd_start_time=Date.now(),this.pathLeaveRoom_.uint64_send_request_exit_room_cmd_end_time=Date.now())}},{key:"handleRemoteStreamAdded",value:function(e){var t=e.client,i=e.stream;if(this.hitTest(t)){var n=i.getUserId(),s=i.getType(),o="".concat(n,"_").concat(s),a=this.remoteStreamStatsMap_.get(o);if(a)a.stream=i;else{var c={userId:n,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:r({},QV),stream:i};c.statsToReport.msg_user_info=new XV({userId:n,tinyId:i.getTinyId(),role:20}),c.statsToReport.uint32_stream_type=s===eT?2:7,this.remoteStreamStatsMap_.set(o,c)}}}},{key:"handleRemoteStreamSubscribeStart",value:function(e){var t=e.client,r=e.stream;if(this.hitTest(t)){var i=r.getUserId(),n=r.getType(),s="".concat(i,"_").concat(n),o=this.remoteStreamStatsMap_.get(s);o&&0===o.subscribeStartTime&&(o.subscribeStartTime=Date.now())}}},{key:"handleSendSubscribeCMD",value:function(e){if(this.hitTest(e.client)){var t=new XV(e),r=Date.now(),i="".concat(e.userId,"_").concat(eT);e.trackState.video&&e.subscribeState.video&&!this.pathMainVideoMap_.has(i)&&this.pathMainVideoMap_.set(i,{statsToReport:{msg_user_info:t,uint64_start_enter_time:this.pathJoinRoom_.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0,uint64_pc_connected_time:0},userId:e.userId,sendSubscribeCMDTime:r}),e.trackState.audio&&e.subscribeState.audio&&!this.pathMainAudioMap_.has(i)&&this.pathMainAudioMap_.set(i,{statsToReport:{msg_user_info:t,uint64_start_enter_time:this.pathJoinRoom_.uint64_start_time,uint64_play_first_frame_time:0},userId:e.userId,sendSubscribeCMDTime:r});var n="".concat(e.userId,"_").concat(tT);e.trackState.auxiliary&&e.subscribeState.auxiliary&&!this.pathAuxiliaryMap_.has(n)&&this.pathAuxiliaryMap_.set(n,{sendSubscribeCMDTime:r})}}},{key:"handleRemoteStreamSubscribed",value:function(e){var t=e.client,r=e.stream;if(this.hitTest(t)){var i=r.getUserId(),n=r.getType(),s="".concat(i,"_").concat(n),o=this.remoteStreamStatsMap_.get(s);o&&0===o.subscribedTime&&(o.subscribedTime=Date.now(),o.stream=r)}}},{key:"handlePlayStream",value:function(e){var t=e.stream;if(t.isRemote()&&t.getConnection()&&this.hitTest(t.getConnection().getClient())){var r=t.getConnection().getUserId(),i="".concat(r,"_").concat(t.getType());if(this.remoteStreamStatsMap_.has(i)){var n=this.remoteStreamStatsMap_.get(i);0===n.playStreamTime&&(n.playStreamTime=Date.now())}}}},{key:"handleVideoLoadedData",value:function(e){var t=e.stream;if(t.isRemote()&&t.getConnection()&&this.hitTest(t.getConnection().getClient())){var r=t.getConnection().getUserId(),i="".concat(r,"_").concat(t.getType());if(this.pathMainVideoMap_.has(i)){var n=this.pathMainVideoMap_.get(i);0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}}}},{key:"handleVideoPlaying",value:function(e){var t=e.stream;if(t.isRemote()&&t.getConnection()&&this.hitTest(t.getConnection().getClient())){var r=t.getConnection().getUserId(),i="".concat(r,"_").concat(t.getType()),n=Date.now();if(this.pathMainVideoMap_.has(i)){var s=this.pathMainVideoMap_.get(i);if(0===s.statsToReport.uint64_render_first_frame_time&&(s.statsToReport.uint64_render_first_frame_time=n),this.remoteStreamStatsMap_.has(i)){var o=this.remoteStreamStatsMap_.get(i),a=o.statsToReport,c=o.playStreamTime,u=o.subscribedTime;0===a.uint32_video_render_first&&c-u<=100&&(a.uint32_video_render_first=n-s.sendSubscribeCMDTime)}}if(t.getType()===tT&&this.pathAuxiliaryMap_.has(i)&&this.remoteStreamStatsMap_.has(i)){var d=this.remoteStreamStatsMap_.get(i),l=d.statsToReport,h=d.playStreamTime,p=d.subscribedTime;0===l.uint32_video_render_first&&h-p<=100&&(l.uint32_video_render_first=n-this.pathAuxiliaryMap_.get(i).sendSubscribeCMDTime)}}}},{key:"handleAudioPlaying",value:function(e){if(e.stream.isRemote()&&e.stream.getConnection()&&this.hitTest(e.stream.getConnection().getClient())){var t=e.stream.getConnection().getUserId(),r="".concat(t,"_").concat(e.stream.getType());if(this.pathMainAudioMap_.has(r)){var i=this.pathMainAudioMap_.get(r);0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}}}},{key:"handleNetworkQuality",value:function(e){var t=this;this.hitTest(e.client)&&(this.networkQuality_.totalUplinkLoss+=e.uplinkLoss,this.networkQuality_.totalUplinkRTT+=e.uplinkRTT,this.networkQuality_.count++,e.downlinkLossAndRTTMap.forEach((function(e){var r=e.rtt,i=e.loss,n=e.userId,s=t.networkQuality_.totalDownlinkRTTAndLossMap.get(n);s?(s.totalRTT+=r,s.totalLoss+=i,s.count++):t.networkQuality_.totalDownlinkRTTAndLossMap.set(n,{totalRTT:r,totalLoss:i,count:1})})))}},{key:"handleHeartbeatStats",value:function(e){var t=this;if(this.hitTest(e.client)){var r=e.stats,i=r.msg_up_stream_info,n=r.msg_down_stream_info;if(i.msg_video_status[0]){var s=i.msg_video_status[0],o=s.uint32_video_codec_bitrate,a=s.uint32_video_enc_fps,c=s.uint32_video_width,u=s.uint32_video_height;this.localStreamStats_.totalVideoBitrate+=o,this.localStreamStats_.totalVideoFPS+=a,this.localStreamStats_.totalVideoWidth+=c,this.localStreamStats_.totalVideoHeight+=u,this.localStreamStats_.videoCount++}var d=i.msg_audio_status.audioLevel;Math.floor(100*d)>0&&(this.localStreamStats_.totalAudioLevel+=d,this.localStreamStats_.audioLevelCount++),n.forEach((function(e){var r=e.msg_user_info,i=e.msg_audio_status,n=e.msg_video_status,s=r.str_identifier;if(n.forEach((function(e){var r=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,n="".concat(s,"_").concat(r?eT:tT);if(t.remoteStreamStatsMap_.has(n)){var o=t.remoteStreamStatsMap_.get(n);(r&&o.stream.isMainVideoSubscribed||i&&o.stream.isAuxVideoSubscribed)&&(o.totalVideoFPS+=e.uint32_video_receive_fps,o.totalVideoBitrate+=e.uint32_video_codec_bitrate,o.videoCount++,0===o.statsToReport.uint32_video_width&&(o.statsToReport.uint32_video_width=e.uint32_video_width),0===o.statsToReport.uint32_video_height&&(o.statsToReport.uint32_video_height=e.uint32_video_height))}})),i){var o="".concat(s,"_").concat(eT);if(t.remoteStreamStatsMap_.has(o)){var a=t.remoteStreamStatsMap_.get(o);a.stream.isMainAudioSubscribed&&(a.totalAudioBitrate+=i.uint32_audio_codec_bitrate,a.audioCount++,Math.floor(100*i.audioLevel)>0&&(a.totalAudioLevel+=i.audioLevel,a.audioLevelCount++))}}}))}}},{key:"handlePublishStart",value:function(e){var t=e.client;this.hitTest(t)&&0===this.localStreamStats_.publishStartTime&&(this.localStreamStats_.publishStartTime=Date.now())}},{key:"handleLocalStreamInitStart",value:function(e){var t=e.audio,r=e.video;t&&0===this.pathJoinRoom_.uint64_init_audio_start_time&&(this.pathJoinRoom_.uint64_init_audio_start_time=Date.now()),r&&0===this.pathJoinRoom_.uint64_init_camera_start_time&&(this.pathJoinRoom_.uint64_init_camera_start_time=Date.now())}},{key:"handleLocalStreamInitEnd",value:function(e){var t=e.audio,r=e.video;t&&0===this.pathJoinRoom_.uint64_init_audio_end_time&&(this.pathJoinRoom_.uint64_init_audio_end_time=Date.now()),r&&0===this.pathJoinRoom_.uint64_init_camera_end_time&&(this.pathJoinRoom_.uint64_init_camera_end_time=Date.now())}},{key:"handleLocalStreamInitFailed",value:function(e){var t=e.audio,r=e.video,i=e.error,n=i instanceof nk?i.getExtraCode()||i.getCode():{NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5}[i.name]||ik.UNKNOWN;t&&0===this.pathJoinRoom_.uint64_init_audio_end_time&&(this.pathJoinRoom_.int32_init_audio_ret=n,this.pathJoinRoom_.uint64_init_audio_end_time=Date.now()),r&&0===this.pathJoinRoom_.uint64_init_camera_end_time&&(this.pathJoinRoom_.int32_init_camera_ret=n,this.pathJoinRoom_.uint64_init_camera_end_time=Date.now())}},{key:"hasVideoFlag",value:function(e){return this.firstPublishedUserList_.findIndex((function(t){return t.userId===e&&1&t.flag}))>=0}},{key:"hasAudioFlag",value:function(e){return this.firstPublishedUserList_.findIndex((function(t){return t.userId===e&&8&t.flag}))>=0}},{key:"hasAuxFlag",value:function(e){return this.firstPublishedUserList_.findIndex((function(t){return t.userId===e&&4&t.flag}))>=0}},{key:"hitTest",value:function(e){return e===this.client_}},{key:"checkStorage",value:(s=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!(t=tC.getItem(this.storageKey_))){e.next=6;break}return e.next=5,this.upload(t);case 5:tC.deleteItem(this.storageKey_);case 6:e.next=11;break;case 8:e.prev=8,e.t0=e.catch(0),this.log_.warn(e.t0);case 11:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return s.apply(this,arguments)})},{key:"setStorage",value:function(){this.prepareReport();var e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&tC.setItem(this.storageKey_,e)}},{key:"prepareReport",value:function(){var e=this;if(this.networkQuality_.count>0&&(this.basicInfo.uint32_avg_rtt=Math.floor(this.networkQuality_.totalUplinkRTT/this.networkQuality_.count),this.basicInfo.uint32_avg_up_loss=Math.floor(this.networkQuality_.totalUplinkLoss/this.networkQuality_.count)),this.localStreamStats_.videoCount>0){this.localStreamStats_.statsToReport.uint32_video_big_capture_fps=Math.floor(this.localStreamStats_.totalVideoFPS/this.localStreamStats_.videoCount),this.localStreamStats_.statsToReport.uint32_video_big_bitrate=Math.floor(this.localStreamStats_.totalVideoBitrate/this.localStreamStats_.videoCount);var t=Math.floor(this.localStreamStats_.totalVideoWidth/this.localStreamStats_.videoCount),r=Math.floor(this.localStreamStats_.totalVideoHeight/this.localStreamStats_.videoCount);this.localStreamStats_.statsToReport.uint32_video_big_resolution=t<<16|r}this.localStreamStats_.audioLevelCount>0&&(this.localStreamStats_.statsToReport.uint32_audio_capture_db=Math.floor(this.localStreamStats_.totalAudioLevel/this.localStreamStats_.audioLevelCount*100)),this.remoteStreamStatsMap_.forEach((function(t,r){var i=t.userId;if(e.networkQuality_.totalDownlinkRTTAndLossMap.has(i)){var n=e.networkQuality_.totalDownlinkRTTAndLossMap.get(i),s=n.totalLoss,o=n.count;t.statsToReport.uint32_avg_down_loss=Math.floor(s/o)}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));var a=e.client_.getCallDurationCalculator();a&&(t.statsToReport.uint32_audio_play_time=a.getDuration(r,wE),t.statsToReport.uint32_video_play_time=a.getDuration(r,AE)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,KV);var c=e.client_.getBadCaseDetector();if(c){var u=c.getDataFreezeDuration(r),d=u.dataFreeze,l=u.count,h=c.getRenderFreezeDuration(r).renderFreeze;t.statsToReport.uint32_video_block_count=l,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(h,t.statsToReport.uint32_video_play_time),c.isBlackStream(r)&&0===t.statsToReport.uint32_video_avg_fps?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}(0===t.subscribeStartTime||t.subscribeStartTime-t.streamAddedTime>100||0===t.playStreamTime)&&(e.pathMainAudioMap_.delete(r),e.pathMainVideoMap_.delete(r),t.statsToReport.uint32_video_render_first=0)})),this.pathMainAudioMap_.forEach((function(t,r){e.hasAudioFlag(t.userId)?t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>KV&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+KV):e.pathMainAudioMap_.delete(r)})),this.pathMainVideoMap_.forEach((function(t,r){e.hasVideoFlag(t.userId)?t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>KV&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+KV):e.pathMainVideoMap_.delete(r)})),this.pathJoinRoom_.uint64_end_time-this.pathJoinRoom_.uint64_start_time>KV&&(this.pathJoinRoom_.uint64_end_time=this.pathJoinRoom_.uint64_start_time+KV)}},{key:"getReportData",value:function(){var e=this.client_.getSignalInfo();return{uint32_sdk_app_id:Number(this.client_.getSDKAppId()),msg_user_info:new XV({userId:this.client_.getUserId(),tinyId:this.client_.getTinyId(),role:this.client_.getRole()===KE?20:21}),msg_basic_info:this.basicInfo,uint32_acc_ip:pw(e.relayIp),uint32_client_ip:pw(e.clientIp,"small"),uint32_acc_port:0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Math.pow(2,31)),msg_path_enter_room:this.pathJoinRoom_,msg_path_exit_room:this.pathLeaveRoom_,msg_path_recv_video:I(this.pathMainVideoMap_.values()).map((function(e){return e.statsToReport})),msg_quality_statistics:I(this.remoteStreamStatsMap_.values()).map((function(e){return e.statsToReport})),str_room_name:String(this.client_.getRoomId()),msg_path_recv_audio:I(this.pathMainAudioMap_.values()).map((function(e){return e.statsToReport})),uint32_info_client_ip:pw(e.clientIp,"small"),error_code:[],msg_local_statistics:this.localStreamStats_.statsToReport}}},{key:"report",value:(n=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,t=this.getReportData(),e.next=4,this.upload(t);case 4:tC.deleteItem(this.storageKey_),this.initData(),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(0),this.log_.warn(e.t0);case 11:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return n.apply(this,arguments)})},{key:"upload",value:(t=o(i().mark((function e(t){var r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(bE||0===t.msg_path_enter_room.uint64_start_time||[ZT,eR,tR].findIndex((function(e){return e===location.host}))>=0)){e.next=2;break}return e.abrupt("return");case 2:return r=Number(this.client_.getSDKAppId()),n=QR(r,"jssdk_new_endreport"),e.next=6,Ew({url:n,body:JSON.stringify(t)});case 6:if("ok"===(s=e.sent).data){e.next=9;break}throw"key point upload failed: ".concat(s.data);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}()).prototype,"upload",[FV],Object.getOwnPropertyDescriptor(jV.prototype,"upload"),jV.prototype),jV);function eF(){return function(e,t,r){var n=r.value,s=new Set;return r.value=o(i().mark((function e(){var r,o,a,c,u=arguments;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!s.has(this)){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:ER,data:{name:t}})});case 2:for(e.prev=2,s.add(this),r=u.length,o=new Array(r),a=0;a<r;a++)o[a]=u[a];return e.next=7,n.apply(this,o);case 7:return c=e.sent,s.delete(this),e.abrupt("return",c);case 12:throw e.prev=12,e.t0=e.catch(2),s.delete(this),e.t0;case 16:case"end":return e.stop()}}),e,this,[[2,12]])}))),r}}function tF(e){return rF.apply(this,arguments)}function rF(){return(rF=o(i().mark((function e(t){var r,n,s,o,a,c,u,d,l,h,p,m,f;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.userId,n=t.sdkAppId,s=t.useStringRoomId,o=t.roomId,a=t.userSig,c={delta:0,count:[1,1],msg:[]},e.prev=2,(u=new FormData).append("userId",String(r)),u.append("sdkAppId",String(n)),u.append("isStrGroupId",s),u.append("groupId",String(o)),u.append("sdkVersion",$o),u.append("userSig",String(a)),d=hw(),e.next=13,aF(u,c,n);case 13:return l=e.sent,c.delta=hw()-d,iF({stat:c,userId:r}),e.abrupt("return",l);case 19:throw e.prev=19,e.t0=e.catch(2),h=cw(e.t0)?e.t0[0]:e.t0,p=sw(h.code)?h.code:0,m="get websocket url failed: ".concat(h.message.includes("timeout")?"timeout":h.message),f=new nk({code:ik.SCHEDULE_FAILED,extraCode:p,message:JR({key:AR,data:{error:m,code:p}})}),Lw.error(f),iF({stat:c,userId:r,roomId:o,error:f}),f;case 28:case"end":return e.stop()}}),e,null,[[2,19]])})))).apply(this,arguments)}function iF(e){var t=e.stat,r=e.userId,i=e.error;i?dk.logFailedEvent({eventType:CT,error:i,userId:r}):dk.logSuccessEvent({eventType:CT,delta:t.delta,userId:r}),dk.uploadEvent({log:"stat-schedule:"+JSON.stringify(t),userId:r})}function nF(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:VE;return t=KR(e)?r===VE?YT:KT:r===VE?zT:JT,"https://".concat(t,"/api/v1/config")}function sF(e,t,r){return new Promise((function(i,n){Ew({url:e,body:t,timeout:r.timeout}).then((function(e){0===e.data.code?i(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var oF=function(e,t){return Mw({retryFunction:sF,settings:{retries:3,timeout:0},onError:t,onRetrying:e})};function aF(e,t,r){return new Promise((function(i,n){var s,o=null;(s=[oF((function(e){return t.count[0]=e+1}),(function(e,r){t.msg[0]=e.message,o||r()}))(nF(r,VE),e,{get timeout(){return 1e3*ew(2+t.count[0])}}),oF((function(e){return t.count[1]=e+1}),(function(e,r){t.msg[1]=e.message,o||r()}))(nF(r,FE),e,{get timeout(){return 1e3*ew(2+t.count[1])}})],new Promise((function(e,t){var r=[];s.forEach((function(i){i.then(e).catch((function(e){r.push(e),r.length===s.length&&t(r)}))}))}))).then((function(e){i(o=e)})).catch(n)}))}var cF,uF,dF,lF,hF,pF,mF,fF,gF,vF,yF,_F,bF,SF,IF,EF,TF,RF,wF,AF,kF,CF=new(function(){function e(){a(this,e)}return u(e,[{key:"call",value:function(e,t){return rw(this[e])?this[e](t):Promise.reject(new nk({code:ik.INVALID_PARAMETER,message:JR({key:"API_NOT_EXIST",data:{name:e}})}))}},{key:"updatePrivateMapKey",value:function(e){var t=e.privateMapKey;return e.client.setProperty("privateMapKey",t),Promise.resolve()}}]),e}()),MF=(cF=eF(),uF=yV(gV.CLIENT.join),dF=eF(),lF=OV({retries:3}),hF=eF(),pF=yV(gV.CLIENT.publish),mF=eF(),fF=yV(gV.CLIENT.unpublish),gF=yV.apply(void 0,I(gV.CLIENT.subscribe)),vF=yV(gV.CLIENT.unsubscribe),yF=eF(),_F=yV(gV.CLIENT.switchRole),bF=yV(gV.CLIENT.startPublishCDNStream),SF=yV(gV.CLIENT.startMixTranscode),IF=vV.apply(void 0,I(gV.CLIENT.sendSEIMessage)),wF=(RF={timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t[0].byteLength}}).timesInSecond,AF=RF.maxSizeInSecond,kF=RF.getSize,EF=function(e,t,r){var i=r.value,n=new Map;return ww.on(33,(function(e){var t=e.client;return n.delete(t)})),r.value=function(){var e=n.get(this);e||(e={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.set(this,e)),0===e.timestamp?e.timestamp=Date.now():Date.now()-e.timestamp>1e3&&(e.timestamp=Date.now(),e.callCountInSecond=0,e.totalSizeInSecond=0);for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];if(kF&&(e.totalSizeInSecond+=kF.apply(void 0,s)),0!==e.timestamp&&Date.now()-e.timestamp<1e3&&(e.callCountInSecond>=wF||e.totalSizeInSecond>AF))throw new nk({code:ik.INVALID_OPERATION,message:JR({key:qR,data:{isTimes:e.callCountInSecond>=wF,isSize:e.totalSizeInSecond>AF,name:t,timesInSecond:wF,maxSizeInSecond:AF}})});return e.callCountInSecond++,i.apply(this,s)},r},TF=function(){function e(t){var r,i;a(this,e),this.name_="Client",this.mode_=t.mode,this.sdpSemantics_="plan-b",iw(t.sdpSemantics)?function(){if(!("RTCRtpTransceiver"in window)||!("stop"in window.RTCRtpTransceiver.prototype))return!1;if(iw(window.RTCRtpTransceiver))return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;var e=new RTCPeerConnection,t=!1;try{e.addTransceiver(wE),t=!0}catch(e){}return e.close(),t}()&&(this.sdpSemantics_=LT):this.sdpSemantics_=t.sdpSemantics,this.sdkAppId_=t.sdkAppId,this.userId_=t.userId,this.log_=Lw.createLogger({id:"c".concat(t.seq,"|").concat(this.userId_),userId:this.userId_,sdkAppId:this.sdkAppId_}),this.userSig_=t.userSig,this.roomId_=0,this.useStringRoomId_=t.useStringRoomId||!1,this.pureAudioPushMode_=null,this.version_=t.version,this.log_.info("using sdpSemantics: "+this.sdpSemantics_),this.signalChannel_=null,this.role_=KE,this.privateMapKey_="",this.tinyId_=0,this.env_="",this.proxy_=null,this.connections_=new Map,this.mutedStates_=new Map,this.userMap_=new Map,this.syncUserListInterval_=-1,this.localStream_=null,this.uplinkConnection_=null,this.emitter_=bw(new Rw,this.name_),this.isJoined_=!1,this.heartbeat_=-1,this.lastHeartBeatTime_=-1,this.stats_=new sM(this),this.joinTimeout_=-1,this.changeBigSmallRecords_=new Map,this.networkQuality_=null,this.badCaseDetector_=null,this.networkType_=XR(),this.autoSubscribe_=!!iw(t.autoSubscribe)||t.autoSubscribe,this.joinedTimestamp_=0,this.joinOptions_={},this.basis_=(i={browser:EE().name+"/"+EE().version,os:TC(),displayResolution:RC(),isScreenShareSupported:pC(),isWebRTCSupported:sC(),isGetUserMediaSupported:wC(),isWebAudioSupported:AC(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:(r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1},iw(window.AudioDecoder)||(r.AudioDecoder=!0),iw(window.AudioEncoder)||(r.AudioEncoder=!0),iw(window.VideoDecoder)||(r.VideoDecoder=!0),iw(window.VideoEncoder)||(r.VideoEncoder=!0),iw(window.ImageDecoder)||(r.ImageDecoder=!0),r),isMediaSessionSupported:"mediaSession"in navigator&&!iw(navigator.mediaSession.setActionHandler),isWebTransportSupported:!iw(window.WebTransport)},navigator.userAgent.includes("miniProgram")&&(i.browser="mini/".concat(i.browser)),i),this.initBussinessInfo_(t),this.publishedCDN_=!1,this.publishCDNData_=null,this.mixedMCU_=!1,this.mixTranscodeData_=null,this.checkSystemResult_=null,this.enableAudioVolumeEvaluation_=!1,this.audioVolumeIntervalId_=null,this.mixTranscodeManager_=null,this.publishCDNManager_=new GV({client:this}),this.keyPointManager_=new ZV({client:this,frameWorkType:t.frameWorkType}),this.isPublishing_=!1,this.isEnableSmallStream_=!1,this.smallStreamConfig_={bitrate:100,frameRate:15,height:120,width:160},this.turnServers_=[],this.iceTransportPolicy_=t.iceTransportPolicy,this.schedule_={domains:null,iceServers:null,iceTransportPolicy:null},this.enableAutoPlayDialog_=!!iw(t.enableAutoPlayDialog)||t.enableAutoPlayDialog,this.signalInfo_={},this.enableSEI_=!iw(t.enableSEI)&&t.enableSEI,this.isDestroyed_=!1}var t,n,s,c,d,l,h,p,m,f,g,v,y,_,b,E,T,w,A,k,C,M,O,P,L,x,D;return u(e,[{key:"initBussinessInfo_",value:function(e){this.bussinessInfo_=e.bussinessInfo;var t={};if(nw(e.bussinessInfo)&&(t=JSON.parse(e.bussinessInfo)),!iw(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_PURE_AUDIO"})});this.pureAudioPushMode_=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this.pureAudioPushMode_}if(!iw(e.streamId)){if(!(nw(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_STREAMID"})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_streamid_main=e.streamId}if(!iw(e.userDefineRecordId)){if(null===e.userDefineRecordId.match(/^[A-Za-z0-9_-]{1,64}$/gi))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_USER_DEFINE_RECORDID"})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!iw(e.userDefinePushArgs)){if(!(nw(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_USER_DEFINE_PUSH_ARGS"})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}uk(t)||(this.bussinessInfo_=JSON.stringify(t))}},{key:"schedule",value:(D=o(i().mark((function e(t){var n;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,tF({userId:this.userId_,sdkAppId:this.sdkAppId_,roomId:t,useStringRoomId:this.useStringRoomId_,version:this.version_,userSig:this.userSig_});case 2:(n=e.sent)&&(this.log_.info("schedule: ".concat(JSON.stringify(n))),this.schedule_=r(r({},this.schedule_),n),ww.emit(31,this.schedule_));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return D.apply(this,arguments)})},{key:"getSignalChannelUrl",value:function(){var e={mainUrl:"",backupUrl:""},t=YR();return t?e.mainUrl=e.backupUrl="wss://".concat(t,".rtc.qq.com"):this.proxy_?e.mainUrl=e.backupUrl=this.proxy_:Array.isArray(this.schedule_.domains)&&this.schedule_.domains.length>0&&(e.mainUrl=e.backupUrl="wss://".concat(this.schedule_.domains[0]),this.schedule_.domains[1]&&(e.backupUrl="wss://".concat(this.schedule_.domains[1]))),e}},{key:"getUserId",value:function(){return this.userId_}},{key:"getUserSig",value:function(){return this.userSig_}},{key:"getRole",value:function(){return this.role_}},{key:"getSignalInfo",value:function(){return this.signalInfo_}},{key:"getRoomId",value:function(){return this.roomId_}},{key:"getSDKAppId",value:function(){return this.sdkAppId_}},{key:"getTinyId",value:function(){return this.tinyId_}},{key:"getIceTransportPolicy",value:function(){return this.iceTransportPolicy_||this.schedule_.iceTransportPolicy||"all"}},{key:"initialize",value:function(){var e=this;this.log_.info("setup signal channel");var t=this.getSignalChannelUrl(),r=t.mainUrl,i=t.backupUrl;return this.signalChannel_=new lk({sdkAppId:this.sdkAppId_,userId:this.userId_,userSig:this.userSig_,url:r,backupUrl:i,client:this}),this.networkQuality_||(this.networkQuality_=new oM({connections:this.connections_,signalChannel:this.signalChannel_,userId:this.userId_,client:this}),this.networkQuality_.on(XC,(function(t){e.emitter_.emit(XC,t)}))),this.deviceDetector_||(this.deviceDetector_=new aM({client:this})),this.subscriptionManager_||(this.subscriptionManager_=new EV({client:this})),this.badCaseDetector_||(this.badCaseDetector_=new UV({client:this,stats:this.stats_})),this.callDurationCalculator_||(this.callDurationCalculator_=new HV({client:this})),this.mixTranscodeManager_||(this.mixTranscodeManager_=new qV({client:this,signalChannel:this.signalChannel_})),this.publishCDNManager_&&this.publishCDNManager_.setSignalChannel({signalChannel:this.signalChannel_}),this.signalChannel_.on(2,(function(t){e.log_.info("SignalChannel state changed from ".concat(t.prevState," to ").concat(t.state)),e.emitter_.emit(qC,t)})),this.signalChannel_.on(4,(function(t){e.reset(),e.emitter_.emit(tM,t)})),this.signalChannel_.once(1,(function(t){e.tinyId_=t.signalInfo.tinyId,ww.emit(29,{client:e})})),this.signalChannel_.on(tk.PEER_JOIN,this.onPeerJoin,this),this.signalChannel_.on(tk.PEER_LEAVE,this.onPeerLeave,this),this.signalChannel_.on(tk.UPDATE_REMOTE_MUTE_STAT,(function(t){Date.now()-e.lastHeartBeatTime_>=1e4&&e.doHeartbeat(),ww.emit(24,{client:e,data:t.data}),e.onPublishedUserList(t.data),e.onUpdateRemoteMuteStat(t.data)})),this.signalChannel_.on(tk.CLIENT_BANNED,(function(t){var r,i=t.data.data.reason;if(dk.uploadEvent({log:"stat-banned:".concat(i),userId:e.userId_}),"banned"===i)r="you got banned by the admin";else if("kick"===i)r="duplicated userId joining the room";else if("room_disband"===i)r="the room has been disbanded by the admin",i=i.replace("_","-");else if("user_time_out"===i)return e.log_.warn("".concat(i," last heart beat time: ").concat(e.lastHeartBeatTime_," interval: ").concat(Date.now()-e.lastHeartBeatTime_,", visibility: ").concat(document.visibilityState)),void e.reJoin();e.log_["kick"===i?"error":"info"]("user was banned because of [".concat(i,"]")),e.reset(),e.emitter_.emit(QC,{reason:i,message:JR({key:"CLIENT_BANNED",data:{message:r,reason:i}})||i})})),ww.emit(28,{client:this}),this.signalChannel_.connect()}},{key:"preJoin",value:(x=o(i().mark((function e(t){var r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.joinOptions_=t,e.next=3,lC();case 3:if(this.checkSystemResult_=e.sent,this.checkDestroy(),(r=YR())||(r=HE,this.proxy_&&(this.proxy_.startsWith("wss://trtc.rtc.qq.com")?r="trtc":this.proxy_.startsWith("wss://webrtc.qq.com")&&(r="webrtc"))),this.env_=r,dk.setConfig({env:r,sdkAppId:this.sdkAppId_,userId:this.userId_,roomId:t.roomId}),this.uploadTrtcStats(),n=this.checkSystemResult_.detail,s=n.isH264EncodeSupported,o=n.isVp8EncodeSupported,sC()&&(s||o)){e.next=13;break}throw new nk({code:ik.NOT_SUPPORTED,message:JR({key:UR})});case 13:case"end":return e.stop()}}),e,this)}))),function(e){return x.apply(this,arguments)})},{key:"join",value:(L=o(i().mark((function e(t){var r,n=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=hw(),ww.emit(1,{client:this,roomId:t.roomId}),ok(this.userId_,{eventId:32788,eventDesc:"joining room",timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_}),e.next=5,this.preJoin(t);case 5:return e.abrupt("return",new Promise(function(){var e=o(i().mark((function e(s,o){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n.joinReject_=o,e.prev=1,n.proxy_||n.schedule_.domains){e.next=5;break}return e.next=5,n.schedule(t.roomId);case 5:return n.checkDestroy(),e.next=8,n.initialize(t);case 8:return e.next=10,n.doJoin(t);case 10:n.signalInfo_=n.signalChannel_.getSignalInfo(),ww.emit(4,{client:n}),n.joinedTimestamp_=hw(),dk.logSuccessEvent({userId:n.userId_,eventType:"delta-join",delta:n.joinedTimestamp_-r}),dk.logSuccessEvent({userId:n.userId_,eventType:"join"}),dk.uploadEvent({log:"stat-autoplay-dialog:".concat(n.enableAutoPlayDialog_),userId:n.userId_}),dk.uploadEvent({log:"stat-conv-".concat(bE,"-").concat(location.hostname),userId:n.userId_}),s(),e.next=26;break;case 20:e.prev=20,e.t0=e.catch(1),ww.emit(5,{client:n,error:e.t0}),dk.logFailedEvent({userId:n.userId_,eventType:"join",error:e.t0}),n.reset(),o(e.t0);case 26:n.joinReject_=null;case 27:case"end":return e.stop()}}),e,null,[[1,20]])})));return function(t,r){return e.apply(this,arguments)}}()));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return L.apply(this,arguments)})},{key:"checkDestroy",value:function(){if(this.isDestroyed_)throw new nk({code:ik.INVALID_OPERATION,message:JR({key:DR,data:{funName:"join"}})})}},{key:"uploadTrtcStats",value:(P=o(i().mark((function e(){var t,r,n,s,o,a,c,u,d,l,h,p,m;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,KF.getMicrophones();case 3:n=e.sent,t=n&&n.length,e.next=9;break;case 7:e.prev=7,e.t0=e.catch(0);case 9:return e.prev=9,e.next=12,KF.getCameras();case 12:s=e.sent,r=s&&s.length,e.next=18;break;case 16:e.prev=16,e.t1=e.catch(9);case 18:o={microphone:t,camera:r},a=this.checkSystemResult_.detail,c=a.isH264EncodeSupported,u=a.isVp8EncodeSupported,d=a.isH264DecodeSupported,l=a.isVp8DecodeSupported,h={webRTC:this.basis_.isWebRTCSupported,getUserMedia:this.basis_.isGetUserMediaSupported,webSocket:this.basis_.isWebSocketsSupported,screenShare:this.basis_.isScreenShareSupported,webAudio:this.basis_.isWebAudioSupported,h264Encode:c,h264Decode:d,vp8Encode:u,vp8Decode:l},p={browser:this.basis_.browser,os:this.basis_.os,trtc:h,devices:o},m={isWebCodecSupported:this.basis_.isWebCodecSupported,isMediaSessionSupported:this.basis_.isMediaSessionSupported,isWebTransportSupported:this.basis_.isWebTransportSupported},dk.uploadEvent({log:"trtcstats-"+JSON.stringify(p),userId:this.userId_}),this.log_.info("TrtcStats-"+JSON.stringify(p)),dk.uploadEvent({log:"trtcadvancedstats-"+JSON.stringify(m),userId:this.userId_});case 26:case"end":return e.stop()}}),e,this,[[0,7],[9,16]])}))),function(){return P.apply(this,arguments)})},{key:"doJoin",value:function(e){var t=this;return new Promise((function(r,i){t.roomId_=e.roomId,iw(e.role)||(t.role_=e.role),iw(e.privateMapKey)||(t.privateMapKey_=e.privateMapKey),t.log_.info("Join() => joining room: ".concat(e.roomId," useStringRoomId: ").concat(t.useStringRoomId_," mode: ").concat(t.mode_," role: ").concat(t.role_));var n={roomId:String(e.roomId),useStringRoomId:t.useStringRoomId_,privateMapKey:t.privateMapKey_,trtcRole:t.role_===KE?20:21,trtcScene:t.mode_===YE?2:1,sdpSemantics:t.sdpSemantics_,version:Iw(t.version_),ua:navigator&&navigator.userAgent||"",autoSubscribe:t.autoSubscribe_,terminalType:_I?4:gI?2:mI?3:HI?12:GI?5:zI?13:1,netType:GT[XR()],bussinessInfo:t.bussinessInfo_};if(t.publishCDNManager_){var s=t.publishCDNManager_.handleCDNConfigForJoinData(t.bussinessInfo_),o=s.bussinessInfo,a=s.pushUserCdnInfo;Object.assign(n,{bussinessInfo:o,pushUserCdnInfo:a})}t.log_.debug("join room signal data: ".concat(JSON.stringify(n))),t.joinTimeout_=setTimeout((function(){t.log_.error("join room timeout observed"),i(new nk({code:ik.JOIN_ROOM_FAILED,message:JR({key:"JOIN_ROOM_TIMEOUT"})}))}),5e3),ww.emit(2,{client:t}),t.signalChannel_.once(5,(function(e){t.clearJoinTimeout(),ww.emit(29,{client:t,error:e}),i(e)})),t.signalChannel_.send("join",n),t.signalChannel_.once(tk.JOIN_ROOM_RESULT,(function(e){t.clearJoinTimeout();var n=e.data,s=n.code,o=n.message,a=n.data;t.onPublishedUserList({data:{userList:a.publishers}}),ww.emit(3,{client:t,code:s}),0===s?(t.isJoined_=!0,t.log_.info("Join room success, start heartbeat"),t.startHeartbeat(),t.badCaseDetector_&&t.badCaseDetector_.start(),t.syncUserList(),t.startSyncUserListInterval(),r()):(t.log_.error("Join room failed result: "+s+" error: "+o),i(new nk({code:ik.JOIN_ROOM_FAILED,extraCode:s,message:JR({key:AR,data:{error:o,code:s}})})))}))}))}},{key:"reJoin",value:(O=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isJoined_){e.next=3;break}return this.log_.warn("reJoin abort"),e.abrupt("return");case 3:return this.isJoined_=!1,e.prev=4,this.log_.warn("reJoin pending: ".concat(this.joinOptions_.roomId)),this.subscriptionManager_&&this.subscriptionManager_.markAllStream(),this.signalChannel_.close(),e.next=10,this.signalChannel_.connect();case 10:return e.next=12,this.doJoin(r(r({},this.joinOptions_),{},{role:this.role_,privateMapKey:this.privateMapKey_}));case 12:this.log_.warn("reJoin success"),dk.logSuccessEvent({userId:this.userId_,eventType:"rejoin"}),this.checkConnectionsToReconnect(),this.republish(),this.mixTranscodeManager_&&this.mixTranscodeManager_.reStartMixTranscode(),e.next=25;break;case 19:e.prev=19,e.t0=e.catch(4),this.log_.warn("reJoin fail "+e.t0),this.reset(),dk.logFailedEvent({userId:this.userId_,eventType:"rejoin",error:e.t0}),this.emitter_.emit(tM,new nk({code:ik.JOIN_ROOM_FAILED,message:JR({key:"REJOIN_ROOM_FAILED",data:{roomId:this.joinOptions_.roomId}})}));case 25:case"end":return e.stop()}}),e,this,[[4,19]])}))),function(){return O.apply(this,arguments)})},{key:"republish",value:function(){var e=this;if(this.uplinkConnection_&&this.localStream_&&!this.uplinkConnection_.getIsReconnecting()){this.log_.warn("republish pending");var t=this.localStream_;this.doUnpublish(t).then((function(){return e.publish(t)})).then((function(){return e.log_.warn("republish success")})).catch((function(t){return e.log_.warn("republish fail "+t)}))}}},{key:"leave",value:(M=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return ww.emit(20,{client:this}),ok(this.userId_,{eventId:32789,eventDesc:"leaving room",timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_}),e.prev=2,e.next=5,this.doHeartbeat();case 5:e.next=9;break;case 7:e.prev=7,e.t0=e.catch(2);case 9:this.doLeave(),ww.emit(22,{client:this}),dk.logSuccessEvent({userId:this.userId_,eventType:"leave"}),t=Math.floor((hw()-this.joinedTimestamp_)/1e3),dk.logSuccessEvent({userId:this.userId_,eventType:"delta-leave",delta:t});case 14:case"end":return e.stop()}}),e,this,[[2,7]])}))),function(){return M.apply(this,arguments)})},{key:"doLeave",value:function(){this.isJoined_&&(ww.emit(21,{client:this}),this.log_.info("leave() => leaving room"),this.signalChannel_.send("leave"),this.reset())}},{key:"clearNetworkQuality",value:function(){this.networkQuality_&&(this.networkQuality_.stop(),this.networkQuality_=null)}},{key:"closeConnections",value:function(){var e=this;this.connections_.forEach((function(t){e.closeDownLink(t.getTinyId())}))}},{key:"clearJoinTimeout",value:function(){clearTimeout(this.joinTimeout_),this.joinTimeout_=-1}},{key:"destroy",value:function(){var e,t,r;if(this.isJoined_)throw this.log_.warn(HR.INVALID_DESTROY),new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_DESTROY"})});this.isDestroyed_||(this.log_.info("destroy client"),this.joinReject_&&(this.joinReject_(new nk({code:ik.INVALID_OPERATION,message:JR({key:DR,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.off("*"),null===(e=this.callDurationCalculator_)||void 0===e||e.destroy(),null===(t=this.keyPointManager_)||void 0===t||t.destroy(),null===(r=this.deviceDetector_)||void 0===r||r.destroy(),this.callDurationCalculator_=null,this.keyPointManager_=null,this.deviceDetector_=null,this.badCaseDetector_=null,this.publishCDNManager_=null,this.isDestroyed_=!0,ww.emit(33,{client:this}))}},{key:"reset",value:function(){this.keyPointManager_&&this.keyPointManager_.prepareReport(),this.mixTranscodeManager_&&(this.mixTranscodeManager_.reset(),this.mixTranscodeManager_=null),this.publishCDNManager_&&this.publishCDNManager_.reset(),this.userMap_.clear(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.mutedStates_.clear(),this.clearNetworkQuality(),this.badCaseDetector_&&this.callDurationCalculator_&&this.uploadAllCallStats(),this.closeUplink(),this.isJoined_=!1,this.signalChannel_&&(this.log_.info("destroying SignalChannel"),this.signalChannel_.close(),this.signalChannel_=null),this.stats_.reset()}},{key:"startSyncUserListInterval",value:function(){-1===this.syncUserListInterval_&&(this.syncUserListInterval_=eC.run(lR,this.syncUserList.bind(this)))}},{key:"stopSyncUserListInterval",value:function(){eC.clearTask(this.syncUserListInterval_),this.syncUserListInterval_=-1}},{key:"syncUserList",value:(C=o(i().mark((function e(){var t,r=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.getUserList();case 3:t=e.sent,0!==this.userMap_.size&&this.userMap_.forEach((function(e){t.findIndex((function(t){return t.userId===e.userId}))<0&&(r.log_.info("peer leave detected: ".concat(e.userId)),r.cleanUser({userId:e.userId,tinyId:e.tinyId}))})),t.forEach((function(e){var t=e.userId;r.userMap_.has(t)||t===r.userId_||(r.userMap_.set(t,e),r.emitter_.emit(GC,{userId:t}))})),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(0),this.log_.warn("sync user list failed: "+e.t0);case 11:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return C.apply(this,arguments)})},{key:"getUserList",value:function(){return this.signalChannel_?this.signalChannel_.sendWaitForResponse({command:"get_user_list",responseCommand:tk.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((function(e){var t=e.data,r=t.code,i=t.message;if(0===r)return(t.data&&t.data.userList||[]).map((function(e){var t=e.userId,r=e.srcTinyId,i=e.role;return new BV({userId:t,tinyId:r,role:i})}));throw JR({key:FR,data:{signalResponse:tk.USER_LIST_RES,code:r,message:i}})})):[]}},{key:"publish",value:(k=o(i().mark((function e(t){var r,n,s,o,a=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.setPublishState(0),this.isPublishing_=!0,r=hw(),ww.emit(27,{client:this,stream:t}),this.log_.info("publish() => publishing local stream"),n=new DV({userId:this.userId_,tinyId:this.tinyId_,client:this,isUplink:!0,signalChannel:this.signalChannel_,enableSEI:this.enableSEI_}),t.setConnection(n),n.initialize(),n.on($C,(function(e){var t=e.getCode();t!==ik.ICE_TRANSPORT_ERROR&&(t===ik.UPLINK_RECONNECTION_FAILED&&a.closeUplink(),a.emitter_.emit(tM,e))})),e.prev=9,e.next=12,n.publish(t);case 12:this.localStream_=e.sent,this.localStream_.getBeautyStatus()&&this.log_.info("beauty stream is published successfully"),this.log_.info("local stream is published successfully"),this.isPublishing_=!1,t.setPublishState(1),this.uplinkConnection_=n,s=hw(),o=s-r,dk.logSuccessEvent({userId:this.userId_,eventType:dT}),dk.logSuccessEvent({userId:this.userId_,eventType:"delta-publish",delta:o}),t.hasAudio()&&ok(this.userId_,{eventId:32769,eventDesc:"publish audio track",timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_}),t.hasVideo()&&ok(this.userId_,{eventId:32768,eventDesc:"publish video track",timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_}),this.networkQuality_&&this.networkQuality_.setUplinkConnection(this.uplinkConnection_),this.deviceDetector_&&this.deviceDetector_.setLocalStream(this.localStream_),ww.emit(120,{localStream:this.localStream_,client:this}),this.notPublishWithoutH264Supported_=!1,e.next=39;break;case 30:throw e.prev=30,e.t0=e.catch(9),e.t0 instanceof nk&&e.t0.getCode()===ik.NOT_SUPPORTED_H264&&(this.notPublishWithoutH264Supported_=!0),t.setPublishState(-1),n.close(),this.log_.error("failed to publish stream "+e.t0),this.isPublishing_=!1,dk.logFailedEvent({userId:this.userId_,eventType:dT,error:e.t0}),e.t0;case 39:case"end":return e.stop()}}),e,this,[[9,30]])}))),function(e){return k.apply(this,arguments)})},{key:"unpublish",value:(A=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.localStream_){e.next=2;break}return e.abrupt("return");case 2:return this.log_.info("unpublish() => unpublishing local stream"),e.prev=3,e.next=6,this.doUnpublish();case 6:dk.logSuccessEvent({userId:this.userId_,eventType:lT}),e.next=13;break;case 9:throw e.prev=9,e.t0=e.catch(3),dk.logFailedEvent({userId:this.userId_,eventType:lT,error:e.t0}),e.t0;case 13:case"end":return e.stop()}}),e,this,[[3,9]])}))),function(){return A.apply(this,arguments)})},{key:"doUnpublish",value:function(){var e=this;return this.signalChannel_.sendWaitForResponse({command:rk,commandDesc:"unpublish",responseCommand:tk.UNPUBLISH_RESULT}).then((function(){e.closeUplink()})).catch((function(){e.closeUplink()}))}},{key:"closeUplink",value:function(){this.uplinkConnection_&&(this.uplinkConnection_.getIsReconnecting()&&this.uplinkConnection_.stopReconnection(),this.uplinkConnection_.close(),this.uplinkConnection_=null,this.networkQuality_&&this.networkQuality_.setUplinkConnection(null),this.localStream_.hasAudio()&&ok(this.userId_,{eventId:32771,eventDesc:"unpublish audio track",timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_}),this.localStream_.hasVideo()&&ok(this.userId_,{eventId:32770,eventDesc:"unpublish video track",timestamp:Hg(),userId:this.userId_,tinyId:this.tinyId_}),this.localStream_.setClient(null),this.localStream_.setConnection(null),this.localStream_=null,this.deviceDetector_&&this.deviceDetector_.setLocalStream(null))}},{key:"closeDownLink",value:function(e){var t=this.connections_.get(e);t&&(t.getIsReconnecting()&&t.stopReconnection(),this.subscriptionManager_&&this.subscriptionManager_.delete(t.getUserId()),t.close(),this.connections_.delete(e),this.mutedStates_.delete(e))}},{key:"subscribe",value:(w=o(i().mark((function e(t,r){var n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.log_.info("subscribe() => subscribe to [".concat(t.getUserId(),"] ").concat(t.getType()," stream with options: ").concat(JSON.stringify(r))),iw(r)&&(r={audio:!0,video:!0}),iw(r.video)&&(r.video=!0),iw(r.audio)&&(r.audio=!0),e.prev=4,n=t.getConnection(),ww.emit(112,{client:this,stream:t}),e.next=9,n.subscribe(t,r);case 9:this.subscriptionManager_&&this.subscriptionManager_.addSubscriptionRecord(t.getUserId(),t,r),this.notSubscribeWithoutH264Supported_=!1,dk.logSuccessEvent({userId:this.userId_,eventType:hT}),e.next=22;break;case 14:throw e.prev=14,e.t0=e.catch(4),(s=e.t0 instanceof nk?e.t0.getCode():ik.UNKNOWN)===ik.NOT_SUPPORTED_H264&&(this.notSubscribeWithoutH264Supported_=!0),o=new nk({code:s,message:JR({key:"SUBSCRIBE_FAILED",data:{message:e.t0.message,stream:t}})}),dk.logFailedEvent({userId:this.userId_,eventType:hT,error:o}),this.log_.error(o),o;case 22:case"end":return e.stop()}}),e,this,[[4,14]])}))),function(e,t){return w.apply(this,arguments)})},{key:"unsubscribe",value:(T=o(i().mark((function e(t){var r;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.log_.info("unsubscribe() => unsubscribe to [".concat(t.getUserId(),"] ").concat(t.getType()," stream")),e.prev=1,r=t.getConnection(),e.next=5,r.unsubscribe(t);case 5:this.subscriptionManager_&&this.subscriptionManager_.addUnsubscriptionRecord(t.getUserId(),t),ww.emit(Cw,{client:this,stream:t}),dk.logSuccessEvent({userId:this.userId_,eventType:pT}),e.next=14;break;case 10:throw e.prev=10,e.t0=e.catch(1),dk.logFailedEvent({userId:this.userId_,eventType:pT,error:e.t0}),e.t0;case 14:case"end":return e.stop()}}),e,this,[[1,10]])}))),function(e){return T.apply(this,arguments)})},{key:"switchRole",value:(E=o(i().mark((function e(t){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.role_!==t){e.next=2;break}return e.abrupt("return");case 2:if(t!==QE||!this.localStream_){e.next=5;break}return e.next=5,this.unpublish(this.localStream_);case 5:return this.log_.info("switchRole() => switch role to: "+t),e.next=8,this.doSwitchRole(t);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return E.apply(this,arguments)})},{key:"doSwitchRole",value:function(e){var t,r,i=this,n={command:"change_role",data:{role:e===KE?20:21,privateMapKey:this.privateMapKey_},responseCommand:tk.SWITCH_ROLE_RES,retries:(null===(t=this.schedule_.config)||void 0===t||null===(r=t.retries)||void 0===r?void 0:r.switchRole)||1};return this.log_.info("switchRole signal data: "+JSON.stringify(n.data)),this.signalChannel_.sendWaitForResponseWithRetry(n).then((function(t){var r=t.data,n=r.code,s=r.message;if(0!==n)throw new nk({code:ik.SWITCH_ROLE_FAILED,message:JR({key:"SWITCH_ROLE_FAILED",data:{errMsg:s,errCode:n}})});i.role_=e})).catch((function(e){throw e instanceof nk&&e.getCode()===ik.API_CALL_TIMEOUT&&(e=new nk({code:ik.SWITCH_ROLE_FAILED,message:JR({key:"SWITCH_ROLE_TIMEOUT"})})),i.log_.error(e),e}))}},{key:"on",value:function(e,t,r){this.emitter_.on(e,t,r)}},{key:"off",value:function(e,t,r){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,r)}},{key:"getRemoteMutedState",value:function(){var e=this,t=[];return this.mutedStates_.forEach((function(i,n,s){var o=e.connections_.get(n);o&&t.push(r({userId:o.getUserId()},i))})),t}},{key:"getTransportStats",value:(b=o(i().mark((function e(){var t,r,n,s,o,a,c;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t={rtt:0,downlinksRTT:{}},!this.uplinkConnection_){e.next=6;break}return e.next=4,this.stats_.getSenderStats(this.uplinkConnection_);case 4:r=e.sent,t.rtt=r.rtt;case 6:n=R(this.connections_),e.prev=7,n.s();case 9:if((s=n.n()).done){e.next=17;break}return(o=S(s.value,2))[0],a=o[1],e.next=13,this.stats_.getReceiverStats(a);case 13:c=e.sent,t.downlinksRTT[c.userId]=c.rtt;case 15:e.next=9;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(7),n.e(e.t0);case 22:return e.prev=22,n.f(),e.finish(22);case 25:return e.abrupt("return",t);case 26:case"end":return e.stop()}}),e,this,[[7,19,22,25]])}))),function(){return b.apply(this,arguments)})},{key:"getLocalAudioStats",value:(_=o(i().mark((function e(){var t,r;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((t={})[this.userId_]={bytesSent:0,packetsSent:0},!this.uplinkConnection_){e.next=7;break}return e.next=5,this.stats_.getSenderStats(this.uplinkConnection_);case 5:r=e.sent,t[this.userId_]={bytesSent:r.audio.bytesSent,packetsSent:r.audio.packetsSent};case 7:return e.abrupt("return",t);case 8:case"end":return e.stop()}}),e,this)}))),function(){return _.apply(this,arguments)})},{key:"getLocalVideoStats",value:(y=o(i().mark((function e(){var t,r;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((t={})[this.userId_]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},!this.uplinkConnection_){e.next=7;break}return e.next=5,this.stats_.getSenderStats(this.uplinkConnection_);case 5:r=e.sent,t[this.userId_]={bytesSent:r.video.bytesSent,packetsSent:r.video.packetsSent,framesEncoded:r.video.framesEncoded,framesSent:r.video.framesSent,frameWidth:r.video.frameWidth,frameHeight:r.video.frameHeight};case 7:return e.abrupt("return",t);case 8:case"end":return e.stop()}}),e,this)}))),function(){return y.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(v=o(i().mark((function e(){var t,r,n,s,o,a,c,u;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t={},r=R(this.connections_),e.prev=2,r.s();case 4:if((n=r.n()).done){e.next=13;break}return(s=S(n.value,2))[0],o=s[1],a=o.getDelay(),c=a.audioDelay,e.next=9,this.stats_.getReceiverStats(o);case 9:(u=e.sent).hasAudio&&(t[u.userId]={bytesReceived:u.audio.bytesReceived,packetsReceived:u.audio.packetsReceived,packetsLost:u.audio.packetsLost,end2EndDelay:c});case 11:e.next=4;break;case 13:e.next=18;break;case 15:e.prev=15,e.t0=e.catch(2),r.e(e.t0);case 18:return e.prev=18,r.f(),e.finish(18);case 21:return e.abrupt("return",t);case 22:case"end":return e.stop()}}),e,this,[[2,15,18,21]])}))),function(){return v.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(g=o(i().mark((function e(){var t,r,n,s,o,a,c,u,d,l=arguments;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=l.length>0&&void 0!==l[0]?l[0]:eT,r={},n=R(this.connections_),e.prev=3,n.s();case 5:if((s=n.n()).done){e.next=15;break}return(o=S(s.value,2))[0],a=o[1],e.next=9,this.stats_.getReceiverStats(a);case 9:c=e.sent,u=a.getDelay(),d=u.videoDelay,t===eT&&c.hasVideo&&(r[c.userId]={bytesReceived:c.video.bytesReceived,packetsReceived:c.video.packetsReceived,packetsLost:c.video.packetsLost,framesDecoded:c.video.framesDecoded,frameWidth:c.video.frameWidth,frameHeight:c.video.frameHeight,end2EndDelay:d}),t===tT&&c.hasAuxiliary&&(r[c.userId]={bytesReceived:c.auxiliary.bytesReceived,packetsReceived:c.auxiliary.packetsReceived,packetsLost:c.auxiliary.packetsLost,framesDecoded:c.auxiliary.framesDecoded,frameWidth:c.auxiliary.frameWidth,frameHeight:c.auxiliary.frameHeight,end2EndDelay:d});case 13:e.next=5;break;case 15:e.next=20;break;case 17:e.prev=17,e.t0=e.catch(3),n.e(e.t0);case 20:return e.prev=20,n.f(),e.finish(20);case 23:return e.abrupt("return",r);case 24:case"end":return e.stop()}}),e,this,[[3,17,20,23]])}))),function(){return g.apply(this,arguments)})},{key:"getSdpSemantics",value:function(){return this.sdpSemantics_}},{key:"getIceServers",value:function(){return 0===this.turnServers_.length&&this.schedule_.iceServers?this.schedule_.iceServers:this.turnServers_}},{key:"getConnections",value:function(){return this.connections_}},{key:"getMutedStates",value:function(){return this.mutedStates_}},{key:"startHeartbeat",value:function(){-1===this.heartbeat_&&(this.log_.info("startHeartbeat..."),this.heartbeat_=eC.run(lR,this.doHeartbeat.bind(this),{delay:2e3}))}},{key:"stopHeartbeat",value:function(){-1!==this.heartbeat_&&(this.log_.info("stopHeartbeat"),eC.clearTask(this.heartbeat_),this.heartbeat_=-1,this.lastHeartBeatTime_=-1)}},{key:"doHeartbeat",value:(f=o(i().mark((function e(){var t,n,s,o,a;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.badCaseDetector_.getMonitorFreeze(),e.next=3,this.stats_.getStatsReport({uplinkConnection:this.uplinkConnection_,downlinkConnections:this.connections_,freezeMap:t});case 3:if(n=e.sent,ww.emit(23,{client:this,stats:n}),this.badCaseDetector_.resetMonitor(),this.signalChannel_){e.next=8;break}return e.abrupt("return");case 8:s=this.signalChannel_.isConnected()?ak(this.userId_):[],o=r(r({str_sdk_version:this.version_,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId_,uint64_tinyid:this.tinyId_},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:GT[this.networkType_]}},n),{},{msg_event_msg:s}),this.signalChannel_.send("quality_report",o),a=Date.now(),this.lastHeartBeatTime_>0&&a-this.lastHeartBeatTime_>1e4&&this.log_.warn("heartbeat took ".concat(a-this.lastHeartBeatTime_)),this.lastHeartBeatTime_=a,!this.isRelayChanged_&&this.isRelayMaybeFailed()&&(this.reJoin(),this.isRelayChanged_=!0);case 15:case"end":return e.stop()}}),e,this)}))),function(){return f.apply(this,arguments)})},{key:"onRemoteStreamAdded",value:function(e){var t=e.content,r=t.userId,i=t.tinyId,n=t.audio,s=t.bigVideo,o=t.auxVideo,a=t.smallVideo;if(null!==r){this.userMap_.has(r)||(this.userMap_.set(r,new BV({userId:r,tinyId:i,role:KE})),this.emitter_.emit(GC,{userId:r}));var c=this.connections_.get(i);if(c){if(c.getIsReconnecting())return;this.log_.warn("duplicated stream-added observed, rebuild the connection"),c.close(),this.connections_.delete(i)}var u={audio:n,video:s,auxiliary:o,smallVideo:a};this.log_.info("remote peer [".concat(r,"] published stream. trackState: ").concat(JSON.stringify(u))),this.createDownlinkConnection({userId:r,tinyId:i,trackState:u})}else this.log_.warn("received null userId on stream added")}},{key:"createDownlinkConnection",value:function(e){var t=this,r=e.userId,i=e.tinyId,n=e.trackState,s=new NV({userId:r,tinyId:i,client:this,isUplink:!1,signalChannel:this.signalChannel_,autoSubscribe:this.autoSubscribe_,trackState:n,enableSEI:this.enableSEI_});this.connections_.set(i,s),this.installDownlinkEvents(s,r,i),this.autoSubscribe_?(s.initialize(),s.connect().catch((function(){!s.getMainStream()&&s.hasMainStream()&&t.initRemoteStream({type:eT,userId:r,downlinkConnection:s}),!s.getAuxStream()&&s.hasAuxStream()&&t.initRemoteStream({type:tT,userId:r,downlinkConnection:s})}))):(s.hasMainStream()&&this.initRemoteStream({type:eT,userId:r,downlinkConnection:s}),s.hasAuxStream()&&this.initRemoteStream({type:tT,userId:r,downlinkConnection:s}))}},{key:"initRemoteStream",value:function(e){var t=e.type,r=e.userId,i=e.downlinkConnection,n=new IV({type:t,userId:r,client:this});n.setConnection(i),i.setRemoteStream(t===eT?XE:ZE,n),n.setIsStreamAddedEventEmitted(!0),ww.emit(111,{client:this,stream:n}),this.emitter_.emit(VC,{stream:n})}},{key:"installDownlinkEvents",value:function(e,t,r){var i=this;e.on(BC,(function(e){i.emitter_.emit(eM,e)})),e.on(LC,(function(e){e.stream.setIsStreamAddedEventEmitted(!0),ww.emit(111,{client:i,stream:e.stream}),i.emitter_.emit(VC,{stream:e.stream})})),e.on(xC,(function(e){i.changeBigSmallRecords_.delete(e.stream.getUserId()),e.stream.stop(),e.stream.setIsStreamAddedEventEmitted(!1),i.subscriptionManager_&&i.subscriptionManager_.deleteAutoRecoveryFlag(e.stream.getUserId(),e.stream.getType()),ww.emit(116,{client:i,stream:e.stream}),i.emitter_.emit(FC,{stream:e.stream})})),e.on(DC,(function(e){ww.emit(115,{client:i,stream:e.stream}),i.emitter_.emit(jC,{stream:e.stream})})),e.on(NC,(function(e){ww.emit(kw,{client:i,stream:e.stream}),i.emitter_.emit(WC,{stream:e.stream})})),e.on($C,(function(e){var t=e.getCode();t!==ik.ICE_TRANSPORT_ERROR&&(t===ik.DOWNLINK_RECONNECTION_FAILED&&i.closeDownLink(r),i.emitter_.emit(tM,e))}))}},{key:"onPeerJoin",value:function(e){var t=e.data.data,r=t.srcTinyId,i=t.userId,n=t.role;this.userMap_.has(i)||(this.userMap_.set(i,new BV({userId:i,tinyId:r,role:n})),this.emitter_.emit(GC,{userId:i}))}},{key:"onPeerLeave",value:function(e){var t=e.data.data,r=t.srcTinyId,i=t.userId,n=t.reason,s=void 0===n?0:n;this.log_.info("peer leave [".concat(i,"]: ").concat(dR[s])),this.cleanUser({userId:i,tinyId:r})}},{key:"cleanUser",value:function(e){var t=e.userId,r=e.tinyId;this.userMap_.delete(t),this.closeDownLink(r),this.emitter_.emit(HC,{userId:t})}},{key:"onPublishedUserList",value:function(e){var t=this;try{var r=e.data.userList.map((function(e){return e.userId}));this.connections_.forEach((function(e){var i=e.getUserId(),n=e.getTinyId();r.findIndex((function(e){return e===i}))<0&&(t.log_.info("peer unpublished detected [".concat(i,"]")),t.closeDownLink(n))})),e.data.userList.forEach((function(e){var r=e.userId,i=e.srcTinyId,n=e.flag;if(r!==t.userId_){var s=!!(1&n),o=!!(8&n),a=!!(4&n),c=!!(2&n),u=t.connections_.get(i);if(t.changeBigSmallRecords_.has(r)&&t.checkSubscribeBigSmallVideo(u,c),u){var d=u.getTrackState(),l=d.audio,h=d.video,p=d.auxiliary,m=d.smallVideo;!h&&s&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:WT,kind:AE}),!l&&o&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:WT,kind:wE}),!p&&a&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:WT,kind:kE}),!m&&c&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:WT,kind:CE}),h&&!s&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:qT,kind:AE}),l&&!o&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:qT,kind:wE}),p&&!a&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:qT,kind:kE}),m&&!c&&ww.emit(Aw,{client:t,tinyId:i,userId:r,action:qT,kind:CE})}else t.log_.info("peer published detected [".concat(r,"]")),t.onRemoteStreamAdded({content:{audio:o,bigVideo:s,auxVideo:a,smallVideo:c,userId:r,tinyId:i}})}}))}catch(e){}}},{key:"onUpdateRemoteMuteStat",value:function(e){var t=this,r=e.data;(r&&r.userList||[]).forEach((function(e){var r=e.srcTinyId,i=e.userId;if(0!==r&&r!==t.tinyId_){var n=t.connections_.get(r);if(n){var s=n.getMainStream();if(s&&s.getIsStreamAddedEventEmitted()){var o=!!(1&e.flag),a=!!(8&e.flag),c=!!(2&e.flag),u=!!(64&e.flag),d=!!(16&e.flag),l=t.mutedStates_.get(r);if(void 0===l)return t.mutedStates_.set(r,{hasAudio:a,hasVideo:o,hasSmall:c,audioMuted:u,videoMuted:d}),o?d?t.emitter_.emit(JC,{userId:i}):t.emitter_.emit(KC,{userId:i}):t.emitter_.emit(JC,{userId:i}),void(a?u?t.emitter_.emit(zC,{userId:i}):t.emitter_.emit(YC,{userId:i}):t.emitter_.emit(zC,{userId:i}));var h=!u&&a;(!l.audioMuted&&l.hasAudio)!==h&&(h?t.emitter_.emit(YC,{userId:i}):t.emitter_.emit(zC,{userId:i}));var p=!d&&o;(!l.videoMuted&&l.hasVideo)!==p&&(p?t.emitter_.emit(KC,{userId:i}):t.emitter_.emit(JC,{userId:i})),t.mutedStates_.set(r,{hasAudio:a,hasVideo:o,hasSmall:c,audioMuted:u,videoMuted:d})}}else t.mutedStates_.delete(r)}}))}},{key:"getEnv",value:function(){return this.env_}},{key:"getSubscriptionManager",value:function(){return this.subscriptionManager_}},{key:"startPublishCDNStream",value:(m=o(i().mark((function e(){var t,r=arguments;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=r.length>0&&void 0!==r[0]?r[0]:{},this.log_.info("startPublishCDNStream params: ".concat(JSON.stringify(t),"; isJoined: ").concat(this.isJoined_,"; isPublished: ").concat(!!this.localStream_)),this.localStream_){e.next=4;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:CR})});case 4:return e.next=6,this.publishCDNManager_.startPublishTencentCDN(t);case 6:if(!(t.appId&&t.bizId&&t.url)){e.next=9;break}return e.next=9,this.publishCDNManager_.startPublishGivenCDN(t);case 9:case"end":return e.stop()}}),e,this)}))),function(){return m.apply(this,arguments)})},{key:"stopPublishCDNStream",value:(p=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.publishCDNManager_.getIsPublishingTencentCDN()){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_OPERATION_STOP_PUBLISH_CDN"})});case 2:return this.log_.info("stopPublishCDNStream"),e.next=5,this.publishCDNManager_.stopPublishTencentCDN();case 5:if(!this.publishCDNManager_.getIsPublishingGivenCDN()){e.next=8;break}return e.next=8,this.publishCDNManager_.stopPublishGivenCDN();case 8:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{key:"startMixTranscode",value:(h=o(i().mark((function e(t){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isJoined_&&this.mixTranscodeManager_){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"START_MIX_TRANSCODE"})});case 2:return iw(t.mode)&&(t.mode=xT),e.prev=3,this.log_.info("startMixTranscode with config ".concat(JSON.stringify(t))),dk.uploadEvent({log:"mix-transcode-mode:".concat(t.mode),userId:this.userId_}),e.next=8,this.mixTranscodeManager_.startMixTranscode(t);case 8:dk.logSuccessEvent({userId:this.userId_,eventType:wT}),e.next=15;break;case 11:throw e.prev=11,e.t0=e.catch(3),dk.logFailedEvent({userId:this.userId_,eventType:wT,error:e.t0}),e.t0;case 15:case"end":return e.stop()}}),e,this,[[3,11]])}))),function(e){return h.apply(this,arguments)})},{key:"stopMixTranscode",value:(l=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isJoined_&&this.mixTranscodeManager_){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"STOP_MIX_TRANSCODE"})});case 2:return e.prev=2,e.next=5,this.mixTranscodeManager_.stopMixTranscode();case 5:dk.logSuccessEvent({userId:this.userId_,eventType:AT}),e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(2),dk.logFailedEvent({userId:this.userId_,eventType:AT,error:e.t0}),e.t0;case 12:case"end":return e.stop()}}),e,this,[[2,8]])}))),function(){return l.apply(this,arguments)})},{key:"getSystemResult",value:function(){return this.checkSystemResult_}},{key:"enableAudioVolumeEvaluation",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!sw(t))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:PR})});if(this.log_.info("enableAudioVolumeEvaluation with interval: "+t),t<=0)return this.enableAudioVolumeEvaluation_=!1,eC.clearTask(this.audioVolumeIntervalId_),void(this.audioVolumeIntervalId_=null);t=Math.floor(Math.max(t,16)),ww.emit(32,{interval:t}),this.audioVolumeIntervalId_&&(eC.clearTask(this.audioVolumeIntervalId_),this.audioVolumeIntervalId_=null),this.enableAudioVolumeEvaluation_=!0,this.audioVolumeIntervalId_=eC.run(hR,(function(){var t=[];if(e.localStream_){var r=Math.floor(100*e.localStream_.getAudioLevel());t.push({userId:e.userId_,audioVolume:r,stream:e.localStream_})}e.connections_.forEach((function(e){var r=e.getSubscribedMainStream();if(r){var i=Math.floor(100*r.getAudioLevel());t.push({userId:e.getUserId(),audioVolume:i,stream:r})}})),e.emitter_.emit(ZC,{result:t})}),{fps:1e3/t,backgroundTask:r})}},{key:"callExperimentalAPI",value:function(e,t){return CF.call(e,r({client:this},t))}},{key:"setProperty",value:function(e,t){var r="".concat(e,"_");iw(this[r])||(this[r]=t)}},{key:"uploadAllCallStats",value:function(){var e=this;this.callDurationCalculator_.getDurationMap().forEach((function(t,r){var i={userId:t.userId,type:t.type,duration:e.callDurationCalculator_.getDuration(r,AE),dataFreeze:e.badCaseDetector_.getDataFreezeDuration(r).dataFreeze,renderFreeze:e.badCaseDetector_.getRenderFreezeDuration(r).renderFreeze};dk.uploadEvent({log:"callStats-"+JSON.stringify(i),userId:e.userId_})})),this.badCaseDetector_.stop(),this.callDurationCalculator_.reset()}},{key:"enableSmallStream",value:(d=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isPublished()&&!this.isPublishing_){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"ENABLE_SMALL_STREAM_PUBLISHED"})});case 2:if(!kC()){e.next=7;break}this.setIsEnableSmallStream(!0),this.log_.info("SmallStream successfully enabled"),e.next=8;break;case 7:throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"NOT_SUPPORTED_SMALL_STREAM"})});case 8:case"end":return e.stop()}}),e,this)}))),function(){return d.apply(this,arguments)})},{key:"disableSmallStream",value:(c=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isPublished()&&!this.isPublishing_){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"DISABLE_SMALL_STREAM_PUBLISHED"})});case 2:this.setIsEnableSmallStream(!1),this.log_.info("SmallStream successfully disabled");case 4:case"end":return e.stop()}}),e,this)}))),function(){return c.apply(this,arguments)})},{key:"setSmallStreamProfile",value:function(e){var t=this;e&&e.framerate&&(e.frameRate=e.framerate),Object.keys(this.smallStreamConfig_).forEach((function(r){e[r]&&(t.smallStreamConfig_[r]=e[r])})),this.log_.info("setSmallStreamProfile: bitrate=".concat(this.smallStreamConfig_.bitrate,", frameRate=").concat(this.smallStreamConfig_.frameRate,", height=").concat(this.smallStreamConfig_.height,", width=").concat(this.smallStreamConfig_.width));var r=this.smallStreamConfig_,i=r.width,n=r.height,s=r.bitrate,o=r.frameRate;if(i<0||n<0||s<0||o<0)throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_SMALL_STREAM_PROFILE"})})}},{key:"setRemoteVideoStreamType",value:(s=o(i().mark((function e(t,r){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t instanceof IV){e.next=2;break}throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_PARAMETER_REMOTE_STREAM"})});case 2:if(t.getConnection()){e.next=4;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:kR})});case 4:if(t.getType()!==tT){e.next=6;break}return e.abrupt("return");case 6:e.t0=r,e.next="big"===e.t0||"small"===e.t0?9:12;break;case 9:return e.next=11,this.changeVideoType(t,r);case 11:case 12:return e.abrupt("break",13);case 13:case"end":return e.stop()}}),e,this)}))),function(e,t){return s.apply(this,arguments)})},{key:"changeVideoType",value:(n=o(i().mark((function e(t,r){var n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.getUserId(),s={stream:t,options:{video:"big"===r,smallVideo:"small"===r},isSubscribing:!1,reSubscribeCount:10},this.changeBigSmallRecords_.set(n,s),this.log_.info("set [".concat(n,"] ").concat(t.getType()," stream video prefer types: ").concat(r));case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"checkSubscribeBigSmallVideo",value:(t=o(i().mark((function e(t,r){var n,s,o,a,c,u,d,l,h,p,m;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.isBigStreamSubscribed||t.isSmallStreamSubscribed){e.next=2;break}return e.abrupt("return");case 2:if(n=t.getUserId(),s=this.changeBigSmallRecords_.get(n)||{},o=t.getSubscribeState(),a=o.video,c=o.smallVideo,u=s.stream,d=s.options,l=s.isSubscribing,h=s.reSubscribeCount,!(d.video&&a||d.smallVideo&&c&&r)){e.next=8;break}return e.abrupt("return");case 8:if(!l){e.next=10;break}return e.abrupt("return");case 10:if(p={video:d.video,smallVideo:d.smallVideo},!(r&&t.isBigStreamSubscribed||t.isSmallStreamSubscribed)){e.next=30;break}if(e.prev=12,!(d&&u&&!l&&h>=1)){e.next=23;break}return s.isSubscribing=!0,s.reSubscribeCount=h-1,m=u.getConnection(),!r&&m.isSmallStreamSubscribed&&(p={video:!0,smallVideo:!1}),e.next=20,null==m?void 0:m.subscribe(u,p);case 20:this.log_.info("change [".concat(n,"] to ").concat(p.smallVideo?"small":"big"," video successfully. count ").concat(10-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=10;case 23:e.next=30;break;case 25:e.prev=25,e.t0=e.catch(12),this.log_.info("change [".concat(n,"] to ").concat(p.smallVideo?"small":"big"," video failed. count ").concat(10-s.reSubscribeCount,".")),s.isSubscribing=!1,0===h&&this.changeBigSmallRecords_.delete(n);case 30:case"end":return e.stop()}}),e,this,[[12,25]])}))),function(e,r){return t.apply(this,arguments)})},{key:"setIsEnableSmallStream",value:function(e){this.isEnableSmallStream_=e}},{key:"getIsEnableSmallStream",value:function(){return this.isEnableSmallStream_}},{key:"smallStreamConfig",get:function(){return this.smallStreamConfig_}},{key:"isPublished",value:function(){return!!this.localStream_}},{key:"getUplinkConnection",value:function(){return this.uplinkConnection_}},{key:"getLocalStream",value:function(){return this.localStream_}},{key:"getMode",value:function(){return this.mode_}},{key:"getBadCaseDetector",value:function(){return this.badCaseDetector_}},{key:"getCallDurationCalculator",value:function(){return this.callDurationCalculator_}},{key:"getIsJoined",value:function(){return this.isJoined_}},{key:"getAllConnections",value:function(){var e=I(this.connections_.values());return this.uplinkConnection_&&e.push(this.uplinkConnection_),e}},{key:"isRelayMaybeFailed",value:function(){var e=this.getAllConnections();if(0===e.length)return!1;for(var t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}},{key:"getUseStringRoomId",value:function(){return this.useStringRoomId_}},{key:"checkConnectionsToReconnect",value:function(){var e=this;this.getAllConnections().forEach((function(t){if(!t.getIsReconnecting()){var r=t.getPeerConnection();r&&r.connectionState===cT&&(e.log_.warn("[".concat(t.getUserId(),"] pc is closed but not reconnect")),t.startReconnection())}}))}},{key:"getEnableAutoPlayDialog",value:function(){return this.enableAutoPlayDialog_}},{key:"sendSEIMessage",value:function(e,t){this.uplinkConnection_.sendSEI(e,t)}},{key:"setProxyServer",value:function(e){if(this.log_.info("set proxy server: ".concat(JSON.stringify(e))),nw(e)){if(!e.startsWith("wss://"))throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_PROXY"})});this.proxy_=e}else if(ZR(e)){var t=e.websocketProxy,r=e.loggerProxy;t&&(this.proxy_=t),r&&function(e){zE=e}(r)}}},{key:"setTurnServer",value:function(e){this.log_.info("set turn server: "+JSON.stringify(e));var t=[];Array.isArray(e)?e.forEach((function(e){return t.push(lw(e))})):ZR(e)&&t.push(lw(e)),this.turnServers_=t}}]),e}(),w(TF.prototype,"join",[cF,uF],Object.getOwnPropertyDescriptor(TF.prototype,"join"),TF.prototype),w(TF.prototype,"leave",[dF],Object.getOwnPropertyDescriptor(TF.prototype,"leave"),TF.prototype),w(TF.prototype,"getUserList",[lF],Object.getOwnPropertyDescriptor(TF.prototype,"getUserList"),TF.prototype),w(TF.prototype,"publish",[hF,pF],Object.getOwnPropertyDescriptor(TF.prototype,"publish"),TF.prototype),w(TF.prototype,"unpublish",[mF,fF],Object.getOwnPropertyDescriptor(TF.prototype,"unpublish"),TF.prototype),w(TF.prototype,"subscribe",[gF],Object.getOwnPropertyDescriptor(TF.prototype,"subscribe"),TF.prototype),w(TF.prototype,"unsubscribe",[vF],Object.getOwnPropertyDescriptor(TF.prototype,"unsubscribe"),TF.prototype),w(TF.prototype,"switchRole",[yF,_F],Object.getOwnPropertyDescriptor(TF.prototype,"switchRole"),TF.prototype),w(TF.prototype,"startPublishCDNStream",[bF],Object.getOwnPropertyDescriptor(TF.prototype,"startPublishCDNStream"),TF.prototype),w(TF.prototype,"startMixTranscode",[SF],Object.getOwnPropertyDescriptor(TF.prototype,"startMixTranscode"),TF.prototype),w(TF.prototype,"sendSEIMessage",[IF,EF],Object.getOwnPropertyDescriptor(TF.prototype,"sendSEIMessage"),TF.prototype),TF),OF=Mw({retryFunction:function(){var e=o(i().mark((function e(t){var r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!_C()){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,PF(t);case 4:if(r=e.sent,Lw.info("getUserMedia with constraints: "+JSON.stringify(r)),!r.audio){e.next=11;break}return e.next=9,KF.getMicrophones();case 9:n=e.sent,Lw.info("microphones: ".concat(JSON.stringify(n)));case 11:if(!r.video){e.next=16;break}return e.next=14,KF.getCameras();case 14:s=e.sent,Lw.info("cameras: ".concat(JSON.stringify(s)));case 16:return e.prev=16,e.next=19,navigator.mediaDevices.getUserMedia(r);case 19:return e.abrupt("return",e.sent);case 22:if(e.prev=22,e.t0=e.catch(16),"NotFoundError"!==e.t0.name){e.next=29;break}if(!s||0!==s.length){e.next=27;break}throw new nk({code:ik.DEVICE_NOT_FOUND,message:JR({key:"CAMERA_NOT_FOUND"})});case 27:if(!n||0!==n.length){e.next=29;break}throw new nk({code:ik.DEVICE_NOT_FOUND,message:JR({key:"MICROPHONE_NOT_FOUND"})});case 29:throw new nk({code:ik.INITIALIZE_FAILED,name:e.t0.name,message:e.t0.message,constraint:e.t0.constraint});case 30:case"end":return e.stop()}}),e,null,[[16,22]])})));return function(t){return e.apply(this,arguments)}}(),settings:{retries:3,timeout:500},onError:function(e,t,r){"NotReadableError"===e.name?t():r(e)},onRetrying:function(e){Lw.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))}});function PF(e){return LF.apply(this,arguments)}function LF(){return(LF=o(i().mark((function e(t){var n,s,o,a,c,u;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n={echoCancellation:t.echoCancellation,autoGainControl:t.autoGainControl,noiseSuppression:t.noiseSuppression},t.audio){e.next=5;break}n=!1,e.next=15;break;case 5:if(uk(t.microphoneId)){e.next=9;break}n=r({deviceId:t.useExact?{exact:t.microphoneId}:t.microphoneId,sampleRate:t.sampleRate,channelCount:t.channelCount},n),e.next=15;break;case 9:return n=r({sampleRate:t.sampleRate,channelCount:t.channelCount},n),e.next=12,KF.getMicrophones();case 12:s=e.sent,(o=s.filter((function(e){return e.deviceId.length>0}))).length>0&&(n.deviceId={exact:o[0].deviceId});case 15:return c={ideal:t.width,max:t.width},u={ideal:t.height,max:t.height},bI&&HI&&t.width*t.height<101376&&(c=t.width,u=t.height),a=!iw(t.facingMode)&&t.video?{facingMode:t.facingMode,width:c,height:u,frameRate:t.frameRate}:!uk(t.cameraId)&&t.video?{deviceId:t.useExact?{exact:t.cameraId}:t.cameraId,width:c,height:u,frameRate:t.frameRate}:!!t.video&&(!!iw(t.width)||{width:c,height:u,frameRate:t.frameRate}),e.abrupt("return",{audio:n,video:a});case 21:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var xF=function(){var e=o(i().mark((function e(t){var r,n,s,o,a,c,u,d,l;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!_C()){e.next=2;break}return e.abrupt("return");case 2:if(r=null,!(dE&&lE<74||pE)){e.next=27;break}return n=NF(t),Lw.info("getDisplayMedia with constraints: "+JSON.stringify(n)),e.next=8,navigator.mediaDevices.getDisplayMedia(n);case 8:if(s=e.sent,!t.screenAudio){e.next=14;break}return Lw.warn("Your browser not support capture system audio"),e.abrupt("return",s);case 14:if(!t.audio){e.next=24;break}return o=DF(t),Lw.info("getUserMedia with constraints: "+JSON.stringify(o)),e.next=19,navigator.mediaDevices.getUserMedia(o);case 19:return r=e.sent,s.addTrack(r.getAudioTracks()[0]),e.abrupt("return",s);case 24:return e.abrupt("return",s);case 25:e.next=53;break;case 27:if(!t.screenAudio){e.next=37;break}return t.audioConstraints={echoCancellation:!0,noiseSuppression:!0,sampleRate:44100},a=NF(t),Lw.info("getDisplayMedia with constraints: "+JSON.stringify(a)),e.next=33,navigator.mediaDevices.getDisplayMedia(a);case 33:return c=e.sent,e.abrupt("return",c);case 37:return u=NF(t),Lw.info("getDisplayMedia with constraints: "+JSON.stringify(u)),e.next=41,navigator.mediaDevices.getDisplayMedia(u);case 41:if(d=e.sent,!t.audio){e.next=52;break}return l=DF(t),Lw.info("getUserMedia with constraints: "+JSON.stringify(l)),e.next=47,navigator.mediaDevices.getUserMedia(l);case 47:return r=e.sent,d.addTrack(r.getAudioTracks()[0]),e.abrupt("return",d);case 52:return e.abrupt("return",d);case 53:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function DF(e){var t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return iw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}function NF(e){var t={},r={width:pE?{max:e.width}:{ideal:e.width,max:e.width},height:pE?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate};return iw(e.screenSource)||(r.displaySurface=e.screenSource),t.video=r,iw(e.audioConstraints)||(t.audio=e.audioConstraints),t}var $F,UF,BF,VF,FF,jF,WF,qF=new Map([["120p",{width:160,height:120,frameRate:15,bitrate:200}],["120p_2",{width:160,height:120,frameRate:15,bitrate:100}],["180p",{width:320,height:180,frameRate:15,bitrate:350}],["180p_2",{width:320,height:180,frameRate:15,bitrate:150}],["240p",{width:320,height:240,frameRate:15,bitrate:400}],["240p_2",{width:320,height:240,frameRate:15,bitrate:200}],["360p",{width:640,height:360,frameRate:15,bitrate:800}],["360p_2",{width:640,height:360,frameRate:15,bitrate:400}],["480p",{width:640,height:480,frameRate:15,bitrate:900}],["480p_2",{width:640,height:480,frameRate:15,bitrate:500}],["720p",{width:1280,height:720,frameRate:15,bitrate:1500}],["1080p",{width:1920,height:1080,frameRate:15,bitrate:2e3}],["1440p",{width:2560,height:1440,frameRate:30,bitrate:4860}],["4K",{width:3840,height:2160,frameRate:30,bitrate:9e3}]]),GF=new Map([["480p",{width:640,height:480,frameRate:5,bitrate:900}],["480p_2",{width:640,height:480,frameRate:30,bitrate:1e3}],["720p",{width:1280,height:720,frameRate:5,bitrate:1200}],["720p_2",{width:1280,height:720,frameRate:30,bitrate:3e3}],["1080p",{width:1920,height:1080,frameRate:5,bitrate:1600}],["1080p_2",{width:1920,height:1080,frameRate:30,bitrate:4e3}]]),HF=new Map([["standard",{sampleRate:48e3,channelCount:1,bitrate:40}],["standard-stereo",{sampleRate:48e3,channelCount:2,bitrate:64}],["high",{sampleRate:48e3,channelCount:1,bitrate:128}],["high-stereo",{sampleRate:48e3,channelCount:2,bitrate:192}]]),zF=($F=yV.apply(void 0,I(gV.LOCAL_STREAM.switchDevice)),UF=OV({retries:10,timeout:3e3,onRetryFailed:function(e){dk.logFailedEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:TT,error:e}),this.emitter_.emit(iM,new nk({code:ik.DEVICE_AUTO_RECOVER_FAILED,message:e.message}))}}),BF=vV(gV.LOCAL_STREAM.setAudioCaptureVolume),w((VF=function(e){l(I,e);var t,s,c,d,p,m,f,g,v,_,S=y(I);function I(e){var t;a(this,I);var i=r(r({},e),{isRemote:!1,type:"local"});return(t=S.call(this,i)).name_=QT,t.client_=null,t.video_=e.video,t.audio_=e.audio,t.cameraId_=e.cameraId,t.cameraGroupId_="",t.facingMode_=e.facingMode,t.microphoneId_=e.microphoneId,t.microphoneGroupId_="",t.videoSource_=e.videoSource,t.audioSource_=e.audioSource,t.screen_=e.screen,t.screenSource_=e.screenSource,t.screenAudio_=e.screenAudio,t.audioProfile_={echoCancellation:!!iw(e.echoCancellation)||e.echoCancellation,autoGainControl:!!iw(e.autoGainControl)||e.autoGainControl,noiseSuppression:!!iw(e.noiseSuppression)||e.noiseSuppression,sampleRate:48e3,channelCount:1,bitrate:40},t.videoProfile_=qF.get("480p_2"),t.screenProfile_=GF.get("1080p"),t.videoSetting_=null,t.muteState_={video:!1,audio:!1,auxVideo:!1},t.beautyStatus_=!1,t.prevAudioRecoverTime_=0,t.prevVideoRecoverTime_=0,t.isAudioRecovering_=!1,t.isVideoRecovering_=!1,t.initState(),t.canvas_=null,t.canvasInterval_=null,t.gain_={audioTrack:null,source:null,gainNode:null},t.captureVolume_=100,t.log_.info("stream created: "+t.id_),t}return u(I,[{key:"initState",value:function(){this.isAddingTrack_=!1,this.isRemovingTrack_=!1,this.setIsReadyToPublish(!1),this.setPublishState(-1)}},{key:"installEvents",value:function(){b(h(I.prototype),"installEvents",this).call(this),ww.on(120,this.onStreamPublished,this),ww.on(135,this.onVideoTrackStopped,this),ww.on(130,this.onVideoTrackStopped,this),ww.on(137,this.onAudioTrackStopped,this),ww.on(136,this.onAudioTrackStopped,this)}},{key:"uninstallEvents",value:function(){b(h(I.prototype),"uninstallEvents",this).call(this),ww.off(120,this.onStreamPublished,this),ww.off(135,this.onVideoTrackStopped,this),ww.off(130,this.onVideoTrackStopped,this),ww.off(137,this.onAudioTrackStopped,this),ww.off(136,this.onAudioTrackStopped,this)}},{key:"initialize",value:function(){var e=this;return new Promise((function(t,r){if(bC())r(new nk({code:ik.INVALID_OPERATION,message:JR({key:$R})}));else{if(iw(e.audio_)){var i=new MediaStream;return iw(e.audioSource_)||(i.addTrack(e.audioSource_),e.updateAudioPlayingState(!0)),iw(e.videoSource_)||(i.addTrack(e.videoSource_),e.updateVideoPlayingState(!0)),e.setMediaStream(i),dk.logSuccessEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:ST,kind:"custom"}),e.setIsReadyToPublish(!0),t()}e.screen_?(e.log_.info("initialize stream audio: "+e.audio_+" screenAudio: "+e.screenAudio_+" screen: "+e.screen_),xF({audio:e.audio_,screenAudio:e.screenAudio_,microphoneId:e.microphoneId_,screenSource:e.screenSource_,width:e.screenProfile_.width,height:e.screenProfile_.height,frameRate:e.screenProfile_.frameRate,sampleRate:e.audioProfile_.sampleRate,channelCount:e.audioProfile_.channelCount,autoGainControl:e.audioProfile_.autoGainControl,noiseSuppression:e.audioProfile_.noiseSuppression,echoCancellation:e.audioProfile_.echoCancellation}).then((function(r){e.setMediaStream(r),e.updateAudioPlayingState(e.audio_||e.screenAudio_),e.updateVideoPlayingState(!0);var i=e.getVideoTrack();return e.listenForScreenSharingStopped(i),e.setVideoContentHint("detail"),e.updateDeviceIdInUse(),e.setIsReadyToPublish(!0),e.log_.info(JSON.stringify(i.getSettings())),dk.logSuccessEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:ST,kind:"getDisplayMedia"}),t()})).catch((function(t){dk.logFailedEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:ST,kind:"getDisplayMedia",error:t}),e.log_.error("getDisplayMedia error observed "+t),r(t instanceof nk?t:new nk({code:ik.INITIALIZE_FAILED,name:t.name,message:t.message}))}))):(ww.emit(121,{stream:e,audio:e.audio_,video:e.video_}),e.log_.info("initialize stream audio: "+e.audio_+" video: "+e.video_),OF({audio:e.audio_,video:e.video_,facingMode:e.facingMode_,cameraId:e.cameraId_,microphoneId:e.microphoneId_,width:e.videoProfile_.width,height:e.videoProfile_.height,frameRate:e.videoProfile_.frameRate,sampleRate:e.audioProfile_.sampleRate,channelCount:e.audioProfile_.channelCount,autoGainControl:e.audioProfile_.autoGainControl,noiseSuppression:e.audioProfile_.noiseSuppression,echoCancellation:e.audioProfile_.echoCancellation}).then((function(r){return ww.emit(122,{stream:e,audio:e.audio_,video:e.video_}),e.setMediaStream(r),r.getTracks().forEach((function(t){t.kind===AE&&CC&&(e.videoSetting_=t.getSettings()),MC&&e.log_.info("".concat(t.kind," capabilities: ").concat(JSON.stringify(t.getCapabilities())))})),e.updateAudioPlayingState(e.audio_),e.updateVideoPlayingState(e.video_),e.updateDeviceIdInUse(),e.log_.info("gotStream hasAudio: "+e.hasAudio()+" hasVideo: "+e.hasVideo()),e.setIsReadyToPublish(!0),dk.logSuccessEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:ST,kind:"getUserMedia"}),t()})).catch((function(t){ww.emit(123,{stream:e,audio:e.audio_,video:e.video_,error:t}),dk.logFailedEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:ST,kind:"getUserMedia",error:t}),e.log_.error("getUserMedia error observed "+t),r(t)})))}}))}},{key:"listenForScreenSharingStopped",value:function(e){var t=this;e.addEventListener("ended",(function(e){t.log_.info("screen sharing was stopped because the video track is ended"),t.emitter_.emit("screen-sharing-stopped")}))}},{key:"muteAudio",value:function(){var e=b(h(I.prototype),"muteAudio",this).call(this);return e&&(this.log_.info("localStream mute audio"),this.sendMutedFlag(wE,!0)),e}},{key:"muteVideo",value:function(){var e=b(h(I.prototype),"muteVideo",this).call(this);return e&&(this.log_.info("localStream mute video"),this.sendMutedFlag(AE,!0)),e}},{key:"unmuteAudio",value:function(){var e=b(h(I.prototype),"unmuteAudio",this).call(this);return e&&(this.log_.info("localStream unmute audio"),this.sendMutedFlag(wE,!1)),e}},{key:"unmuteVideo",value:function(){var e=b(h(I.prototype),"unmuteVideo",this).call(this);return e&&(this.log_.info("localStream unmute video"),this.sendMutedFlag(AE,!1)),e}},{key:"sendMutedFlag",value:function(e,t){this.setMuteState(e,t);var r=this.getConnection();if(r){r.sendMutedFlag(this.muteState_);var i=r.getUserId(),n=r.getTinyId(),s="".concat(t?OE:PE," local ").concat(e," track");ok(i,{eventId:e===wE?t?32772:32774:t?32773:32775,eventDesc:s,timestamp:Hg(),userId:i,tinyId:n})}}},{key:"setMuteState",value:function(e,t){this.muteState_[e]=t,this.log_.info("set ".concat(e," muted state: [").concat(t?"mute":"unmute","]"))}},{key:"setAudioProfile",value:function(e){var t;"object"===n(e)?t=e:void 0===(t=HF.get(e))&&(t=HF.get("standard")),this.log_.info("setAudioProfile: "+JSON.stringify(t)),this.audioProfile_=r(r({},this.audioProfile_),t)}},{key:"setVideoProfile",value:(_=o(i().mark((function e(t){var n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.connection_||yC()){e.next=2;break}throw new nk({code:ik.NOT_SUPPORTED,message:JR({key:"NOT_SUPPORTED_PROFILE"})});case 2:if(ZR(t)?n=r(r({},this.videoProfile_),t):nw(t)&&(n=qF.get(t),iw(n)&&(n=qF.get("480p_2"))),n&&n.width*n.height>921600&&_E&&(n.width=1280,n.height=720,this.log_.warn("reset to 1280 * 720 on iOS 13~14")),this.log_.info("setVideoProfile "+JSON.stringify(n)),!(s=this.getVideoTrack())){e.next=9;break}return e.next=9,s.applyConstraints(n);case 9:if(o=this.videoProfile_.bitrate!==n.bitrate,this.videoProfile_=n,!o||!this.connection_){e.next=15;break}return e.next=14,this.connection_.setBandwidth(n.bitrate,AE);case 14:this.connection_.updateMediaSettings(this.mediaStream_);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return _.apply(this,arguments)})},{key:"getVideoBitrate",value:function(){return this.screen_?this.screenProfile_.bitrate:this.videoProfile_.bitrate}},{key:"getAudioBitrate",value:function(){return this.audioProfile_.bitrate}},{key:"setScreenProfile",value:function(e){var t=e;nw(e)&&(t=GF.get(e)||GF.get("1080p")),this.log_.info("setScreenProfile "+JSON.stringify(e)),this.screenProfile_=t}},{key:"getVideoProfile",value:function(){return this.screen_?this.screenProfile_:this.videoProfile_}},{key:"getAudioProfile",value:function(){return this.audioProfile_}},{key:"setVideoContentHint",value:function(e){var t=this.getVideoTrack();t&&"contentHint"in t&&(this.log_.info("set video track contentHint to: "+e),t.contentHint=e,t.contentHint!==e&&this.log_.warn("Invalid video track contentHint: "+e))}},{key:"switchDevice",value:(v=o(i().mark((function e(t,r){var n,s,o,a,c,u,d,l,h,p,m,f,g,v,y,_,b;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(n=t===wE)){e.next=8;break}if(this.microphoneId_!==r){e.next=4;break}return e.abrupt("return");case 4:this.microphoneId_=r,this.audio_=!0,e.next=12;break;case 8:if(this.cameraId_!==r){e.next=10;break}return e.abrupt("return");case 10:"user"===r||r===ME?this.facingMode_=r:this.cameraId_=r,this.video_=!0;case 12:if(this.getMediaStream()){e.next=14;break}return e.abrupt("return");case 14:return this.setIsReadyToPublish(!1),this.log_.info("switchDevice "+t+" to: "+r),n||((s=this.getVideoTrack())&&s.stop(),eE&&(o=this.getAudioTrack())&&(this.log_.info("stop audio track first in huawei env"),o.stop())),n&&(a=this.getAudioTrack(),c=this.getMicrophoneTrackMixed(),a&&a.stop(),c&&c.stop()),e.next=20,OF({audio:this.audio_&&t===wE||eE,video:this.video_&&t===AE,facingMode:"user"===r||r===ME?r:void 0,cameraId:this.cameraId_,microphoneId:this.microphoneId_,width:this.videoProfile_.width,height:this.videoProfile_.height,frameRate:this.videoProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount,useExact:!0});case 20:if(u=e.sent,d=null,!n){e.next=27;break}(l=u.getAudioTracks()[0])&&this.isAudioTrackMixed()?(h=this.getAudioTrack(),p=KF.AudioMixerPlugin.getAudioTrackMap(),m=KF.AudioMixerPlugin.mix({targetTrack:l,sourceList:p.get(h.id).sourceList,trackList:p.get(h.id).trackList}),d=m):d=l,e.next=36;break;case 27:if(!(d=u.getVideoTracks()[0])||!this.isVideoTrackBeautified()){e.next=32;break}return e.next=31,this.generateBeautyTrack(d);case 31:d=e.sent;case 32:if(!(f=u.getAudioTracks()[0])||!eE){e.next=36;break}return e.next=36,this.replaceTrack_(f);case 36:return e.next=38,this.replaceTrack_(d);case 38:this.updateDeviceIdInUse(),(g=this.getConnection())&&(v=g.getUserId(),y=g.getTinyId(),_=32780,b="switch camera",n&&(_=32781,b="switch microphone"),ok(v,{eventId:_,eventDesc:b,timestamp:Hg(),userId:v,tinyId:y})),this.log_.info("switch ".concat(n?"microphone":"camera"," success ")),this.setIsReadyToPublish(!0);case 43:case"end":return e.stop()}}),e,this)}))),function(e,t){return v.apply(this,arguments)})},{key:"addTrack",value:(g=o(i().mark((function e(t){var r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isAddingTrack_){e.next=2;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_ADD_TRACK_REPETITIVE"})});case 2:if(!this.isRemovingTrack_){e.next=4;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_ADD_TRACK_REMOVING"})});case 4:if(0!==this.publishState_){e.next=6;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_ADD_TRACK_PUBLISHING"})});case 6:if(r=this.getMediaStream()){e.next=9;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:xR})});case 9:if(!(t.kind===wE&&r.getAudioTracks().length>0||t.kind===AE&&r.getVideoTracks().length>0)){e.next=11;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_ADD_TRACK_NUMBER"})});case 11:if(t.kind===AE&&CC&&(n=t.getSettings(),!this.videoSetting_||n.width===this.videoSetting_.width&&n.height===this.videoSetting_.height||this.log_.warn("video resolution of the track (".concat(n.width," x ").concat(n.height,") shall be kept the same as the previous: ").concat(this.videoSetting_.width," x ").concat(this.videoSetting_.height,". It may cause abnormal Cloud Recording."))),e.prev=12,this.isAddingTrack_=!0,this.keepMuteState(t),r.addTrack(t),!(s=this.getConnection())){e.next=20;break}return e.next=20,s.addTrack(t);case 20:t.kind===wE?(this.audio_=!0,this.updateAudioPlayingState(!0)):(this.video_=!0,this.updateVideoPlayingState(!0)),this.isAddingTrack_=!1,e.next=29;break;case 24:throw e.prev=24,e.t0=e.catch(12),r.removeTrack(t),this.isAddingTrack_=!1,e.t0;case 29:case"end":return e.stop()}}),e,this,[[12,24]])}))),function(e){return g.apply(this,arguments)})},{key:"removeTrack",value:(f=o(i().mark((function e(t){var r,n;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.kind!==wE){e.next=2;break}throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_REMOVE_AUDIO_TRACK"})});case 2:if(!this.isAddingTrack_){e.next=4;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_REMOVE_AUDIO_ADDING"})});case 4:if(!this.isRemovingTrack_){e.next=6;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_REMOVE_AUDIO_ON"})});case 6:if(0!==this.publishState_){e.next=8;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_REMOVE_TRACK_PUBLISHING"})});case 8:if(r=this.getMediaStream()){e.next=11;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:xR})});case 11:if(-1!==r.getTracks().indexOf(t)){e.next=13;break}throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_REMOVE_TRACK_NOT_PUBLISHING"})});case 13:if(1!==r.getTracks().length){e.next=15;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_REMOVE_TRACK_NUMBER"})});case 15:if(e.prev=15,this.isRemovingTrack_=!0,!(n=this.getConnection())){e.next=21;break}return e.next=21,n.removeTrack(t);case 21:r.removeTrack(t),t.kind===wE?(this.audio_=!1,this.updateAudioPlayingState(!1)):(this.video_=!1,this.updateVideoPlayingState(!1)),this.isRemovingTrack_=!1,e.next=30;break;case 26:throw e.prev=26,e.t0=e.catch(15),this.isRemovingTrack_=!1,e.t0;case 30:case"end":return e.stop()}}),e,this,[[15,26]])}))),function(e){return f.apply(this,arguments)})},{key:"replaceTrack",value:(m=o(i().mark((function e(t){var r,n,s;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.getMediaStream()){e.next=3;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:"INVALID_INITIALIZE_LOCAL_STREAM"})});case 3:if(0!==this.publishState_){e.next=5;break}throw new nk({code:ik.INVALID_OPERATION,message:JR({key:LR})});case 5:if(!(t.kind===wE&&r.getAudioTracks().length<=0||t.kind===AE&&r.getVideoTracks().length<=0)){e.next=7;break}throw new nk({code:ik.INVALID_PARAMETER,message:JR({key:"INVALID_REMOVE_TRACK_NOT_PUBLISHED",data:t})});case 7:if(t.kind===AE&&CC&&(n=t.getSettings(),!this.videoSetting_||n.width===this.videoSetting_.width&&n.height===this.videoSetting_.height||this.log_.warn("video resolution of the track (".concat(n.width," x ").concat(n.height,") shall be kept the same as the previous: ").concat(this.videoSetting_.width," x ").concat(this.videoSetting_.height,". It may cause abnormal Cloud Recording."))),this.keepMuteState(t),t.kind!==wE){e.next=18;break}if(r.removeTrack(r.getAudioTracks()[0]),r.addTrack(t),b(h(I.prototype),"restartAudio",this).call(this),!this.gain_.gainNode){e.next=16;break}return this.reconnectGainNode(t),e.abrupt("return");case 16:e.next=21;break;case 18:r.removeTrack(r.getVideoTracks()[0]),r.addTrack(t),b(h(I.prototype),"restartVideo",this).call(this);case 21:if(!(s=this.getConnection())){e.next=25;break}return e.next=25,s.replaceTrack(t);case 25:case"end":return e.stop()}}),e,this)}))),function(e){return m.apply(this,arguments)})},{key:"recoverCapture",value:(p=o(i().mark((function e(t){var r,n,s,o,a,c,u,d,l,h,p,m,f,g,v,y,_;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.mediaStream_){e.next=2;break}return e.abrupt("return");case 2:return this.log_.warn("recoverCapture() trying "+JSON.stringify(t)),r=this.audio_&&t.audio,n=this.video_&&t.video,e.prev=5,e.next=8,KF.getCameras();case 8:return s=e.sent,e.next=11,KF.getMicrophones();case 11:if(o=e.sent,n&&0===s.length&&(n=!1,this.log_.warn("recoverCapture() video flag is true, but no camera detected, set video to false")),r&&0===o.length&&(r=!1,this.log_.warn("recoverCapture() audio flag is true, but no microphone detected, set audio to false")),!1!==r||!1!==n){e.next=17;break}return this.log_.warn("recoverCapture() both audio and video are false, aborted"),e.abrupt("return");case 17:return a=t&&s.findIndex((function(e){return e.deviceId===t.cameraId}))>=0,c=t&&o.findIndex((function(e){return e.deviceId===t.microphoneId}))>=0,e.next=21,OF({audio:r,video:n,cameraId:a?t.cameraId:void 0,microphoneId:c?t.microphoneId:void 0,facingMode:this.facingMode_,width:this.videoProfile_.width,height:this.videoProfile_.height,frameRate:this.videoProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount});case 21:u=e.sent,d=u.getTracks(),l=0;case 24:if(!(l<d.length)){e.next=51;break}if((h=d[l]).kind!==wE||!this.isAudioTrackMixed()){e.next=37;break}if(p=this.getAudioTrack(),m=KF.AudioMixerPlugin.getAudioTrackMap(),(f=m.get(p.id)).hasMicrophone){e.next=33;break}return h.stop(),e.abrupt("continue",48);case 33:return g=KF.AudioMixerPlugin.mix({targetTrack:h,sourceList:f.sourceList,trackList:f.trackList}),e.next=36,this.replaceTrack_(g);case 36:return e.abrupt("continue",48);case 37:if(h.kind!==AE||!this.isVideoTrackBeautified()){e.next=44;break}return e.next=40,this.generateBeautyTrack(h);case 40:return v=e.sent,e.next=43,this.replaceTrack_(v);case 43:return e.abrupt("continue",48);case 44:return h.kind===wE&&(null===(y=this.getAudioTrack())||void 0===y||y.stop()),h.kind===AE&&(null===(_=this.getVideoTrack())||void 0===_||_.stop()),e.next=48,this.replaceTrack_(h);case 48:l++,e.next=24;break;case 51:this.updateDeviceIdInUse(),dk.logSuccessEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:TT}),this.log_.warn("recoverCapture() successfully"),this.emitter_.emit("device-auto-recovered",{isCamera:t.video,isMicrophone:t.audio,cameraId:this.cameraId_,microphoneId:this.microphoneId_}),e.next=61;break;case 57:throw e.prev=57,e.t0=e.catch(5),this.log_.warn("recoverCapture() failed, "+e.t0),e.t0;case 61:case"end":return e.stop()}}),e,this,[[5,57]])}))),function(e){return p.apply(this,arguments)})},{key:"replaceTrack_",value:(d=o(i().mark((function e(t){var r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.mediaStream_.getAudioTracks(),n=this.mediaStream_.getVideoTracks(),!(t.kind===wE&&r.length<=0||t.kind===AE&&n.length<=0)){e.next=5;break}return this.log_.info("there is no previous ".concat(t.kind," track, replacement ignored")),e.abrupt("return");case 5:if(this.keepMuteState(t),t.kind!==wE){e.next=15;break}if(this.mediaStream_.removeTrack(r[0]),this.mediaStream_.addTrack(t),b(h(I.prototype),"restartAudio",this).call(this),!this.gain_.gainNode){e.next=13;break}return this.reconnectGainNode(t),e.abrupt("return");case 13:e.next=19;break;case 15:CC&&(s=t.getSettings(),!this.videoSetting_||s.width===this.videoSetting_.width&&s.height===this.videoSetting_.height||this.log_.warn("the resolution of video track to be replaced (".concat(s.width," x ").concat(s.height,") is different from the previous video settings (").concat(this.videoSetting_.width," x ").concat(this.videoSetting_.height,"). It may cause a cloud recording exception"))),this.mediaStream_.removeTrack(n[0]),this.mediaStream_.addTrack(t),b(h(I.prototype),"restartVideo",this).call(this);case 19:if(!(o=this.getConnection())){e.next=23;break}return e.next=23,o.replaceTrack(t);case 23:case"end":return e.stop()}}),e,this)}))),function(e){return d.apply(this,arguments)})},{key:"updateDeviceIdInUse",value:function(){var e=this;if(!this.mediaStream_)return this.cameraId_="",this.cameraGroupId_="",this.microphoneId_="",void(this.microphoneGroupId_="");CC&&this.mediaStream_.getTracks().forEach((function(t){if(t.kind===wE&&e.isAudioTrackMixed()){var r=e.getMicrophoneTrackMixed();if(r){var i=r.getSettings(),n=i.deviceId,s=i.groupId;n&&(e.microphoneId_=n,e.microphoneGroupId_=s)}}else if(t.kind===AE&&e.isVideoTrackBeautified()){var o=e.getBeautyOriginTrack();if(o){var a=o.getSettings(),c=a.deviceId,u=a.groupId;c&&(e.cameraId_=c,e.cameraGroupId_=u)}}else{var d=t.getSettings(),l=d.deviceId,h=d.groupId;l&&(t.kind===wE?(e.microphoneId_=l,e.microphoneGroupId_=h):t.kind!==AE||e.screen_||(e.cameraId_=l,e.cameraGroupId_=h))}}));var t=this.mediaStream_.getAudioTracks(),r=this.mediaStream_.getVideoTracks();t&&0===t.length&&(this.microphoneId_="",this.microphoneGroupId_=""),r&&0===r.length&&(this.cameraId_="",this.cameraGroupId_="")}},{key:"isAudioTrackMixed",value:function(){if(KF.AudioMixerPlugin){var e=KF.AudioMixerPlugin.getAudioTrackMap(),t=this.getAudioTrack();if(e&&t&&e.has(t.id))return!0}return!1}},{key:"getMicrophoneTrackMixed",value:function(){if(KF.AudioMixerPlugin){var e=KF.AudioMixerPlugin.getAudioTrackMap(),t=this.getAudioTrack();if(e&&t&&e.has(t.id)){var r=e.get(t.id);return r.hasMicrophone?r.microphoneTrack:null}}return null}},{key:"isVideoTrackBeautified",value:function(){if(KF.beautyTrackMap){var e=KF.beautyTrackMap,t=this.getVideoTrack();if(t&&e.has(t.id))return!0}return!1}},{key:"getBeautyOriginTrack",value:function(){if(KF.beautyTrackMap){var e=KF.beautyTrackMap,t=this.getVideoTrack();if(t&&e.has(t.id)){var r=e.get(t.id);if(r.originTrack)return r.originTrack}}return null}},{key:"generateBeautyTrack",value:(c=o(i().mark((function e(t){var r,n,s,o;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=null,n=this.getVideoTrack(),s=KF.beautyTrackMap.get(n.id),o=s.param,s.type){e.next=8;break}r=s.pluginInstance.generateBeautyTrack(t),e.next=22;break;case 8:e.t0=s.type,e.next="beauty"===e.t0?11:"virtual"===e.t0?13:"mixed"===e.t0?17:21;break;case 11:return r=s.pluginInstance.generateBeautyTrack(t),e.abrupt("break",22);case 13:return e.next=15,s.pluginInstance.generateVirtualTrack({videoTrack:t,type:o.type,img:o.img});case 15:case 19:return r=e.sent,e.abrupt("break",22);case 17:return e.next=19,s.pluginInstance.generateMixedTrack({videoTrack:t,type:o.type,img:o.img});case 21:return e.abrupt("break",22);case 22:return s.pluginInstance.deleteSource(n.id),this.log_.info("regenerate beauty track, track id = ".concat(t.id)),e.abrupt("return",r);case 25:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"getScreen",value:function(){return this.screen_}},{key:"hasScreenTrack",value:function(){if(this.screen_)return!0;var e=this.getVideoTrack();return!!e&&("detail"===e.contentHint||"text"===e.contentHint)}},{key:"getVideo",value:function(){return this.video_}},{key:"getAudio",value:function(){return this.audio_}},{key:"getCameraId",value:function(){return this.cameraId_}},{key:"getMicrophoneId",value:function(){return this.microphoneId_}},{key:"getMicrophoneGroupId",value:function(){return this.microphoneGroupId_}},{key:"getIsReadyToPublish",value:function(){return this.isReadyToPublish_}},{key:"setIsReadyToPublish",value:function(e){this.isReadyToPublish_=e}},{key:"setPublishState",value:function(e){this.publishState_=e}},{key:"setBeautyStatus",value:function(e){this.beautyStatus_=!!e}},{key:"getBeautyStatus",value:function(){return this.beautyStatus_}},{key:"onStreamPublished",value:function(e){var t=e.localStream,r=e.client;t===this&&(this.client_=r,this.log_.setUserId(r.getUserId()),this.log_.setSdkAppId(r.getSDKAppId()),this.syncMuteState())}},{key:"syncMuteState",value:function(){var e=this.getAudioTrack(),t=this.getVideoTrack();if(e){var r=!e.enabled;this.setMuteState(wE,r)}if(t){var i=!t.enabled;this.setMuteState(AE,i)}this.connection_&&this.connection_.sendMutedFlag(this.muteState_)}},{key:"keepMuteState",value:function(e){e instanceof MediaStreamTrack&&this.muteState_[e.kind]&&(e.enabled=!1,this.log_.warn("prev ".concat(e.kind," track is muted, keep mute state")))}},{key:"onVideoTrackStopped",value:(s=o(i().mark((function e(t){var r,n,s,o,a=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.stream,n=t.type,r===this&&this.video_&&this.cameraId_&&!this.isVideoRecovering_&&(!(HI&&pE||yI&&Number(gE)>=15.1)||n!==OE)){e.next=3;break}return e.abrupt("return");case 3:if(!(Date.now()-this.prevVideoRecoverTime_<2e3)){e.next=6;break}return setTimeout((function(){return a.onVideoTrackStopped({stream:r,type:n})}),2e3),e.abrupt("return");case 6:if(!(s=this.getVideoTrack())){e.next=14;break}return o=s.getSettings().deviceId,e.next=11,KF.getCameras();case 11:if(!(e.sent.findIndex((function(e){return e.deviceId===o}))<0)){e.next=14;break}return e.abrupt("return");case 14:n===OE?setTimeout((function(){var e=a.getVideoTrack();null!=e&&e.muted&&"visible"===document.visibilityState&&a.recoverVideoCapture(n)}),1e3):this.recoverVideoCapture(n);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"onAudioTrackStopped",value:(t=o(i().mark((function e(t){var r,n,s,o,a,c,u=this;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.stream,n=t.type,r===this&&this.audio_&&this.microphoneId_&&!this.isAudioRecovering_&&(!(HI&&pE||yI&&Number(gE)>=15.1)||n!==OE)){e.next=3;break}return e.abrupt("return");case 3:if(!(Date.now()-this.prevAudioRecoverTime_<2e3)){e.next=6;break}return setTimeout((function(){return u.onAudioTrackStopped({stream:r,type:n})}),2e3),e.abrupt("return");case 6:if(!(s=this.getAudioTrack())){e.next=14;break}return o=s.getSettings(),a=o.groupId,c=o.deviceId,e.next=11,KF.getMicrophones();case 11:if(!(e.sent.findIndex((function(e){return e.deviceId===c&&(iw(a)||a===e.groupId)}))<0)){e.next=14;break}return e.abrupt("return");case 14:n===OE?setTimeout((function(){var e=u.getAudioTrack();null!=e&&e.muted&&"visible"===document.visibilityState&&u.recoverAudioCapture(n)}),1e3):this.recoverAudioCapture(n);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"recoverAudioCapture",value:function(e){var t=this;this.prevAudioRecoverTime_=Date.now(),dk.uploadEvent({log:"stat-local-audio-".concat(e),userId:this.userId_}),this.isAudioRecovering_=!0,this.recoverCapture({audio:!0,video:!1,microphoneId:this.microphoneId_}).then((function(){t.isAudioRecovering_=!1})).catch((function(){t.isAudioRecovering_=!1}))}},{key:"recoverVideoCapture",value:function(e){var t=this;this.isVideoRecovering_||(this.prevVideoRecoverTime_=Date.now(),dk.uploadEvent({log:"stat-local-video-".concat(e),userId:this.userId_}),this.isVideoRecovering_=!0,this.recoverCapture({audio:!1,video:!0,cameraId:this.cameraId_}).then((function(){t.isVideoRecovering_=!1})).catch((function(){t.isVideoRecovering_=!1})))}},{key:"setAudioVolume",value:function(e){b(h(I.prototype),"setAudioVolume",this).call(this,e)}},{key:"clearCanvas",value:function(){this.canvasInterval_&&(eC.clearTask(this.canvasInterval_),this.canvasInterval_=null,this.canvas_=null)}},{key:"genCanvasTrack",value:function(e){var t=this;this.log_.info("gen canvas track");var r=e.getSettings(),i=r.width,n=r.height,s=r.frameRate;this.canvas_=document.createElement("canvas");var o=this.canvas_.getContext("2d");return this.canvas_.width=i,this.canvas_.height=n,this.canvasInterval_=eC.run(hR,(function(){if(t.hasVideo()){var e=t.getVideoTrack().getSettings();e.width===t.canvas_.width&&e.height===t.canvas_.height||(t.canvas_.width=e.width,t.canvas_.height=e.height)}t.videoPlayer_&&t.videoPlayer_.element_&&o.drawImage(t.videoPlayer_.element_,0,0,t.canvas_.width,t.canvas_.height)}),{fps:Math.max(15,s)}),this.canvas_.captureStream().getVideoTracks()[0]}},{key:"setClient",value:function(e){this.client_=e}},{key:"setAudioCaptureVolume",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!this.hasAudio()||t<0||!vC())return!1;if(this.captureVolume_===t)return!0;this.captureVolume_=t,this.log_.info("setCaptureVolume "+t),t/=100;var r=yw();if(this.gain_.gainNode)this.gain_.gainNode.gain.value=t;else{var i,n=new MediaStream;n.addTrack(this.getAudioTrack());var s=r.createMediaStreamDestination(),o=r.createMediaStreamSource(n),a=r.createGain();a.gain.value=t,o.connect(a),a.connect(s);var c=s.stream.getAudioTracks()[0],u=function(t){return e.log_.info("gained audio track ".concat(t))};c.onmute=function(){return u("muted")},c.onunmute=function(){return u("unmuted")},c.onended=function(){return u("ended")},this.gain_={source:o,audioTrack:c,gainNode:a},null===(i=this.connection_)||void 0===i||i.replaceTrack(c),b(h(I.prototype),"restartAudio",this).call(this)}return!0}},{key:"getGainedTrack",value:function(){return this.gain_.audioTrack}},{key:"reconnectGainNode",value:function(e){this.log_.warn("reconnect gain node");var t=new MediaStream;t.addTrack(e);var r=yw().createMediaStreamSource(t);r.connect(this.gain_.gainNode),this.gain_.source.disconnect(),this.gain_.source=r}},{key:"close",value:function(){this.setIsReadyToPublish(!1);var e=this.gain_,t=e.audioTrack,r=e.source,i=e.gainNode;i&&(r.disconnect(),i.disconnect(),t.onmute=null,t.onunmute=null,t.onended=null,t.stop(),this.gain_={source:null,gainNode:null,audioTrack:null}),b(h(I.prototype),"close",this).call(this)}}]),I}(SV)).prototype,"switchDevice",[$F],Object.getOwnPropertyDescriptor(VF.prototype,"switchDevice"),VF.prototype),w(VF.prototype,"recoverCapture",[UF],Object.getOwnPropertyDescriptor(VF.prototype,"recoverCapture"),VF.prototype),w(VF.prototype,"setAudioCaptureVolume",[BF],Object.getOwnPropertyDescriptor(VF.prototype,"setAudioCaptureVolume"),VF.prototype),VF),JF=0,YF=0,KF=new(FF=vV(gV.TRTC.createClient),jF=vV(gV.TRTC.createStream),w((WF=function(){function e(){a(this,e),this.name_="TRTC",this.VERSION=$o,this.Logger={loggerManager:Lw,LogLevel:cR,setLogLevel:function(e){Lw.setLogLevel(e),e<=1&&function(){if(!SE())return!1;var e=localStorage.getItem(sR);e&&!function(e){var t=e.saveTime&&(new Date).getTime()-e.saveTime>=HT,r=!e.saveVersion||e.saveVersion!==$o;return t||r}(JSON.parse(e))||(Lw.info("init debug info"),function(){var e=new XMLHttpRequest;if(e.open("GET","https://web.sdk.qcloud.com/trtc/webrtc/download/error-message/0.0.3/script.js",!1),e.send(null),4===e.readyState&&200===e.status){var t=document.createElement("script");t.type="text/javascript",t.text=e.responseText,document.body.appendChild(t),localStorage.setItem(sR,JSON.stringify({message:e.responseText,saveTime:(new Date).getTime(),saveVersion:$o})),document.body.removeChild(t)}}())}()},enableUploadLog:function(){Lw.enableUploadLog()},disableUploadLog:function(){Lw.warn("disableUploadLog"),Lw.disableUploadLog()}}}var t,n,s,c,d;return u(e,[{key:"checkSystemRequirements",value:(d=o(i().mark((function e(){return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,lC();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e)}))),function(){return d.apply(this,arguments)})},{key:"isScreenShareSupported",value:function(){return pC()}},{key:"isSmallStreamSupported",value:function(){return kC()}},{key:"getDevices",value:(c=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!bC()&&!_C()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return e.kind!==UE||e.deviceId!=aR})).map((function(e,t){var r=e.label;e.label||(r=e.kind+"_"+t);var i={label:r,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(i.groupId=e.groupId),e.getCapabilities&&(i.getCapabilities=function(){return e.getCapabilities()}),i})));case 6:case"end":return e.stop()}}),e)}))),function(){return c.apply(this,arguments)})},{key:"getCameras",value:(s=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!bC()&&!_C()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return e.kind===BE})).map((function(e,t){var r=e.label;e.label||(r="camera_"+t);var i={label:r,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(i.groupId=e.groupId),e.getCapabilities&&(i.getCapabilities=function(){return e.getCapabilities()}),i})));case 6:case"end":return e.stop()}}),e)}))),function(){return s.apply(this,arguments)})},{key:"getMicrophones",value:(n=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!bC()&&!_C()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return e.kind===UE&&e.deviceId!==aR})).map((function(e,t){var r=e.label;e.label||(r="microphone_"+t);var i={label:r,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(i.groupId=e.groupId),e.getCapabilities&&(i.getCapabilities=function(){return e.getCapabilities()}),i})));case 6:case"end":return e.stop()}}),e)}))),function(){return n.apply(this,arguments)})},{key:"getSpeakers",value:(t=o(i().mark((function e(){var t;return i().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!bC()&&!_C()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return"audiooutput"===e.kind})).map((function(e,t){var r=e.label;e.label||(r="speaker_"+t);var i={label:r,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(i.groupId=e.groupId),i})));case 6:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})},{key:"createClient",value:function(e){xw&&(xw=!1,Lw.getLogLevel()!=KF.Logger.LogLevel.NONE&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: "+"".concat(nR,"index.html")),console.info("* Changelog: https://cloud.tencent.com/document/product/647/38958"),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),Lw.info("TRTC Web SDK Version: 4.14.7"),Lw.info("UserAgent: "+navigator.userAgent),Lw.info("URL of current page: "+location.href));var t={version:this.VERSION},i=new MF(r(r(r({},t),e),{},{seq:++JF}));return ww.emit(30,{client:i}),i}},{key:"createStream",value:function(e){return new zF(r(r({},e),{},{seq:++YF}))}}]),e}()).prototype,"createClient",[FF],Object.getOwnPropertyDescriptor(WF.prototype,"createClient"),WF.prototype),w(WF.prototype,"createStream",[jF],Object.getOwnPropertyDescriptor(WF.prototype,"createStream"),WF.prototype),WF);return KF}()}).call(this,r(7))},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){r.d(t,"a",(function(){return o}));var i=r(0),n=r(3),s=r(4);function o(e){return i.d(e)&&s.a(Object(n.a)(e),"[native code]")}},function(e,t){var r,i,n=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(e){if(r===setTimeout)return setTimeout(e,0);if((r===s||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{i="function"==typeof clearTimeout?clearTimeout:o}catch(e){i=o}}();var c,u=[],d=!1,l=-1;function h(){d&&c&&(d=!1,c.length?u=c.concat(u):l=-1,u.length&&p())}function p(){if(!d){var e=a(h);d=!0;for(var t=u.length;t;){for(c=u,u=[];++l<t;)c&&c[l].run();l=-1,t=u.length}c=null,d=!1,function(e){if(i===clearTimeout)return clearTimeout(e);if((i===o||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}(e)}}function m(e,t){this.fun=e,this.array=t}function f(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];u.push(new m(e,t)),1!==u.length||d||a(p)},m.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=f,n.addListener=f,n.once=f,n.off=f,n.removeListener=f,n.removeAllListeners=f,n.emit=f,n.prependListener=f,n.prependOnceListener=f,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},function(e,t){var r=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,names:["value","uri","config"],format:function(e){return null!=e.config?"extmap:%s %s %s":"extmap:%s %s"}},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_]*):(.*)/,names:["id","attribute","value"],format:"ssrc:%d %s:%s"},{push:"ssrcGroups",reg:/^ssrc-group:(\w*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{push:"invalid",names:["value"]}]};Object.keys(r).forEach((function(e){r[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))},function(e,t,r){var i=r(17);e.exports=function(e){var t,n={stun:(e||{}).stun||r(18),turn:(e||{}).turn||r(19)},s=(e||{}).stunCount||2,o=(e||{}).turnCount||0;function a(e,t){for(var r,s=[],o=[].concat(n[e]);o.length&&s.length<t;)r=Math.random()*o.length|0,s=s.concat(o.splice(r,1));return s.map((function(t){return"string"==typeof t||t instanceof String?i(e+":"+t):t}))}return t=[].concat(a("stun",s)),o&&(t=t.concat(a("turn",o))),t}},function(e,t,r){t.Interop=r(20)},function(e,t,r){const i=r(26)("h264-profile-level-id");i.log=console.info.bind(console),t.ProfileConstrainedBaseline=1,t.ProfileBaseline=2,t.ProfileMain=3,t.ProfileConstrainedHigh=4,t.ProfileHigh=5,t.Level1_b=0,t.Level1=10,t.Level1_1=11,t.Level1_2=12,t.Level1_3=13,t.Level2=20,t.Level2_1=21,t.Level2_2=22,t.Level3=30,t.Level3_1=31,t.Level3_2=32,t.Level4=40,t.Level4_1=41,t.Level4_2=42,t.Level5=50,t.Level5_1=51,t.Level5_2=52;class n{constructor(e,t){this.profile=e,this.level=t}}t.ProfileLevelId=n;const s=new n(1,31);class o{constructor(e){this._mask=~u("x",e),this._maskedValue=u("1",e)}isMatch(e){return this._maskedValue===(e&this._mask)}}class a{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const c=[new a(66,new o("x1xx0000"),1),new a(77,new o("1xxx0000"),1),new a(88,new o("11xx0000"),1),new a(66,new o("x0xx0000"),2),new a(88,new o("10xx0000"),2),new a(77,new o("0x0x0000"),3),new a(100,new o("00000000"),5),new a(100,new o("00001100"),4)];function u(e,t){return(t[0]===e)<<7|(t[1]===e)<<6|(t[2]===e)<<5|(t[3]===e)<<4|(t[4]===e)<<3|(t[5]===e)<<2|(t[6]===e)<<1|(t[7]===e)<<0}function d(e={}){const t=e["level-asymmetry-allowed"];return 1===t||"1"===t}t.parseProfileLevelId=function(e){if("string"!=typeof e||6!==e.length)return null;const t=parseInt(e,16);if(0===t)return null;const r=255&t,s=t>>8&255,o=t>>16&255;let a;switch(r){case 11:a=0!=(16&s)?0:11;break;case 10:case 12:case 13:case 20:case 21:case 22:case 30:case 31:case 32:case 40:case 41:case 42:case 50:case 51:case 52:a=r;break;default:return i("parseProfileLevelId() | unrecognized level_idc:%s",r),null}for(const e of c)if(o===e.profile_idc&&e.profile_iop.isMatch(s))return new n(e.profile,a);return i("parseProfileLevelId() | unrecognized profile_idc/profile_iop combination"),null},t.profileLevelIdToString=function(e){if(0==e.level)switch(e.profile){case 1:return"42f00b";case 2:return"42100b";case 3:return"4d100b";default:return i("profileLevelIdToString() | Level 1_b not is allowed for profile:%s",e.profile),null}let t;switch(e.profile){case 1:t="42e0";break;case 2:t="4200";break;case 3:t="4d00";break;case 4:t="640c";break;case 5:t="6400";break;default:return i("profileLevelIdToString() | unrecognized profile:%s",e.profile),null}let r=e.level.toString(16);return 1===r.length&&(r="0"+r),`${t}${r}`},t.parseSdpProfileLevelId=function(e={}){const r=e["profile-level-id"];return r?t.parseProfileLevelId(r):s},t.isSameProfile=function(e={},r={}){const i=t.parseSdpProfileLevelId(e),n=t.parseSdpProfileLevelId(r);return Boolean(i&&n&&i.profile===n.profile)},t.generateProfileLevelIdForAnswer=function(e={},r={}){if(!e["profile-level-id"]&&!r["profile-level-id"])return i("generateProfileLevelIdForAnswer() | no profile-level-id in local and remote params"),null;const s=t.parseSdpProfileLevelId(e),o=t.parseSdpProfileLevelId(r);if(!s)throw new TypeError("invalid local_profile_level_id");if(!o)throw new TypeError("invalid remote_profile_level_id");if(s.profile!==o.profile)throw new TypeError("H264 Profile mismatch");const a=d(e)&&d(r),c=s.level,u=function(e,t){return 0===e?10!==t&&0!==t:0===t?10!==e:e<t}(l=c,h=o.level)?l:h;var l,h;const p=a?c:u;return i("generateProfileLevelIdForAnswer() | result: [profile:%s, level:%s]",s.profile,p),t.profileLevelIdToString(new n(s.profile,p))}},function(e,t,r){(function(e){var i=void 0!==e&&e||"undefined"!=typeof self&&self||window,n=Function.prototype.apply;function s(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new s(n.call(setTimeout,i,arguments),clearTimeout)},t.setInterval=function(){return new s(n.call(setInterval,i,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},s.prototype.unref=s.prototype.ref=function(){},s.prototype.close=function(){this._clearFn.call(i,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},r(15),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,r(7))},function(e,t,r){(function(e,t){!function(e,r){if(!e.setImmediate){var i,n,s,o,a,c=1,u={},d=!1,l=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,"[object process]"==={}.toString.call(e.process)?i=function(e){t.nextTick((function(){m(e)}))}:function(){if(e.postMessage&&!e.importScripts){var t=!0,r=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=r,t}}()?(o="setImmediate$"+Math.random()+"$",a=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(o)&&m(+t.data.slice(o.length))},e.addEventListener?e.addEventListener("message",a,!1):e.attachEvent("onmessage",a),i=function(t){e.postMessage(o+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){m(e.data)},i=function(e){s.port2.postMessage(e)}):l&&"onreadystatechange"in l.createElement("script")?(n=l.documentElement,i=function(e){var t=l.createElement("script");t.onreadystatechange=function(){m(e),t.onreadystatechange=null,n.removeChild(t),t=null},n.appendChild(t)}):i=function(e){setTimeout(m,0,e)},h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),r=0;r<t.length;r++)t[r]=arguments[r+1];var n={callback:e,args:t};return u[c]=n,i(c),c++},h.clearImmediate=p}function p(e){delete u[e]}function m(e){if(d)setTimeout(m,0,e);else{var t=u[e];if(t){d=!0;try{!function(e){var t=e.callback,r=e.args;switch(r.length){case 0:t();break;case 1:t(r[0]);break;case 2:t(r[0],r[1]);break;case 3:t(r[0],r[1],r[2]);break;default:t.apply(void 0,r)}}(t)}finally{p(e),d=!1}}}}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,r(7),r(9))},function(e,t){class r extends AudioWorkletProcessor{constructor(){super(),this.audioLevel=0}static get parameterDescriptors(){return[{name:"averaging",defaultValue:.95},{name:"output",defaultValue:1}]}process(e,t,r){let i,n;i=r.averaging.length?r.averaging[0]:r.averaging,n=r.output.length?r.output[0]:r.output;const s=e[0],o=t[0],a=s[0];if(!a)return!0;const c=a.length;let u,d=0;for(let e=0;e<c;e++)u=a[e],d+=u*u;const l=Math.sqrt(d/c);if(this.audioLevel=Math.max(l,this.audioLevel*i),n)for(let e=0;e<s.length;e++){const t=s[e],r=o[e];for(let e=0;e<t.length;e++)r[e]=t[e]}return this.port.postMessage(this.audioLevel),!0}}registerProcessor("meter-processor",r)},function(e,t){var r=["stun:","turn:"];e.exports=function(e){var t,i,n=(e||{}).url||e,s={};return"string"==typeof n||n instanceof String?(n=n.trim(),(t=r[r.indexOf(n.slice(0,5))])?(i=(n=n.slice(5)).split("@"),s.username=e.username,s.credential=e.credential,i.length>1&&(n=i[1],i=i[0].split(":"),s.username=i[0],s.credential=(e||{}).credential||i[1]||""),s.url=t+n,s.urls=[s.url],s):e):e}},function(e){e.exports=JSON.parse('["stun.l.google.com:19302","stun1.l.google.com:19302","stun2.l.google.com:19302","stun3.l.google.com:19302","stun4.l.google.com:19302","stun.ekiga.net","stun.ideasip.com","stun.schlund.de","stun.stunprotocol.org:3478","stun.voiparound.com","stun.voipbuster.com","stun.voipstunt.com","stun.voxgratia.org"]')},function(e){e.exports=JSON.parse("[]")},function(e,t,r){var i=r(21),n=r(25);function s(){this.cache={mlB2UMap:{},mlU2BMap:{}}}e.exports=s,s.prototype.candidateToUnifiedPlan=function(e){var t=new RTCIceCandidate(e);return t.sdpMLineIndex=this.cache.mlB2UMap[t.sdpMLineIndex],t},s.prototype.candidateToPlanB=function(e){var t=new RTCIceCandidate(e);if(0===t.sdpMid.indexOf("audio"))t.sdpMid="audio";else{if(0!==t.sdpMid.indexOf("video"))throw new Error("candidate with "+t.sdpMid+" not allowed");t.sdpMid="video"}return t.sdpMLineIndex=this.cache.mlU2BMap[t.sdpMLineIndex],t},s.prototype.getFirstSendingIndexFromAnswer=function(e){if(!this.cache.answer)return null;var t=i.parse(this.cache.answer);if(t&&t.media&&Array.isArray(t.media))for(var r=0;r<t.media.length;r++)if(t.media[r].type==e&&(!t.media[r].direction||"sendrecv"===t.media[r].direction||"sendonly"===t.media[r].direction))return r;return null},s.prototype.toPlanB=function(e){var t=this;if("object"!=typeof e||null===e||"string"!=typeof e.sdp)return console.warn("An empty description was passed as an argument."),e;var r=i.parse(e.sdp);if(void 0===r.media||!Array.isArray(r.media)||0===r.media.length)return console.warn("The description has no media."),e;if(r.media.length<=3&&r.media.every((function(e){return-1!==["video","audio","data"].indexOf(e.mid)})))return console.warn("This description does not look like Unified Plan."),e;for(var n=e.sdp,s=!1,o=0;o<r.media.length;o++)r.media[o].rtp.forEach((function(e){if("NULL"===e.codec){s=!0;var r=i.parse(t.cache.offer);e.codec=r.media[o].rtp[0].codec}}));s&&(n=i.write(r)),this.cache[e.type]=n;var a=r.media;r.media=[];var c={},u=[];a.forEach((function(e){if(("string"!=typeof e.rtcpMux||"rtcp-mux"!==e.rtcpMux)&&"inactive"!==e.direction)throw new Error("Cannot convert to Plan B because m-lines without the rtcp-mux attribute were found.");if(void 0!==c[e.type]&&"inactive"!==c[e.type].direction||(c[e.type]=e),e.protocol!=c[e.type].protocol)throw new Error("Cannot convert to Plan B because m-lines have different protocols and this library does not have support for that");if(e.payloads!=c[e.type].payloads)throw new Error("Cannot convert to Plan B because m-lines have different payloads and this library does not have support for that")})),a.forEach((function(e){if("application"===e.type)return r.media.push(e),void u.push(e.mid);"object"==typeof e.sources&&Object.keys(e.sources).forEach((function(t){"object"!=typeof c[e.type].sources&&(c[e.type].sources={}),c[e.type].sources[t]=e.sources[t],void 0!==e.msid&&(c[e.type].sources[t].msid=e.msid)})),void 0!==e.ssrcGroups&&Array.isArray(e.ssrcGroups)&&(void 0!==c[e.type].ssrcGroups&&Array.isArray(c[e.type].ssrcGroups)||(c[e.type].ssrcGroups=[]),c[e.type].ssrcGroups=c[e.type].ssrcGroups.concat(e.ssrcGroups)),c[e.type]===e&&(e.mid=e.type,delete e.bundleOnly,delete e.msid,e.type==a[0].type?(u.unshift(e.type),r.media.unshift(e)):(u.push(e.type),r.media.push(e)))})),void 0!==r.groups&&r.groups.some((function(e){if("BUNDLE"===e.type)return e.mids=u.join(" "),!0})),r.msidSemantic={semantic:"WMS",token:"*"};var d=i.write(r);return new RTCSessionDescription({type:e.type,sdp:d})},s.prototype.toUnifiedPlan=function(e){var t=this;if("object"!=typeof e||null===e||"string"!=typeof e.sdp)return console.warn("An empty description was passed as an argument."),e;var r=i.parse(e.sdp);if(void 0===r.media||!Array.isArray(r.media)||0===r.media.length)return console.warn("The description has no media."),e;if(r.media.length>3||!r.media.every((function(e){return-1!==["video","audio","data"].indexOf(e.mid)})))return console.warn("This description does not look like Plan B."),e;var s=[];r.media.forEach((function(e){s.push(e.mid)}));var o,a,c=!1;if(void 0!==r.groups&&Array.isArray(r.groups)&&(c=r.groups.every((function(e){return"BUNDLE"!==e.type||n.apply(e.mids.sort(),[s.sort()])}))),!c){var u=!1;if(r.media.forEach((function(e){"inactive"!==e.direction&&(u=!0)})),u)throw new Error("Cannot convert to Unified Plan because m-lines that are not bundled were found.")}if("answer"===e.type)o="offer";else{if("offer"!==e.type)throw new Error("Type '"+e.type+"' not supported.");o="answer"}void 0!==this.cache[o]&&(a=i.parse(this.cache[o]));var d,l,h,p,m={audio:{},video:{}},f={},g=0,v=0,y={},_={},b={},S={};if(r.media.forEach((function(r){if(("string"!=typeof r.rtcpMux||"rtcp-mux"!==r.rtcpMux)&&"inactive"!==r.direction)throw new Error("Cannot convert to Unified Plan because m-lines without the rtcp-mux attribute were found.");if("application"!==r.type){var i=r.sources,n=r.ssrcGroups,s=r.port;if(void 0!==r.candidates&&(d=void 0!==d?d.concat(r.candidates):r.candidates),void 0!==l&&void 0!==r.iceUfrag&&l!=r.iceUfrag)throw new Error("Only BUNDLE supported, iceUfrag must be the same for all m-lines.\n\tLast iceUfrag: "+l+"\n\tNew iceUfrag: "+r.iceUfrag);if(void 0!==r.iceUfrag&&(l=r.iceUfrag),void 0!==h&&void 0!==r.icePwd&&h!=r.icePwd)throw new Error("Only BUNDLE supported, icePwd must be the same for all m-lines.\n\tLast icePwd: "+h+"\n\tNew icePwd: "+r.icePwd);if(void 0!==r.icePwd&&(h=r.icePwd),void 0!==p&&void 0!==r.fingerprint&&(p.type!=r.fingerprint.type||p.hash!=r.fingerprint.hash))throw new Error("Only BUNDLE supported, fingerprint must be the same for all m-lines.\n\tLast fingerprint: "+JSON.stringify(p)+"\n\tNew fingerprint: "+JSON.stringify(r.fingerprint));void 0!==r.fingerprint&&(p=r.fingerprint),_[r.type]=r.payloads,b[r.type]=r.rtcpFb,S[r.type]=r.rtp;var o={};void 0!==n&&Array.isArray(n)&&n.forEach((function(e){void 0!==e.ssrcs&&Array.isArray(e.ssrcs)&&e.ssrcs.forEach((function(t){void 0===o[t]&&(o[t]=[]),o[t].push(e)}))}));var c={};if("object"==typeof i)delete r.sources,delete r.ssrcGroups,delete r.candidates,delete r.iceUfrag,delete r.icePwd,delete r.fingerprint,delete r.port,delete r.mid,Object.keys(i).forEach((function(n){var u;"offer"!==e.type||i[n].msid?(void 0!==o[n]&&Array.isArray(o[n])&&o[n].some((function(e){return e.ssrcs.some((function(e){if("object"==typeof c[e])return u=c[e],!0}))})),"object"==typeof u?(u.sources[n]=i[n],delete i[n].msid):(u=Object.create(r),c[n]=u,void 0!==i[n].msid&&(u.msid=i[n].msid,delete i[n].msid),u.sources={},u.sources[n]=i[n],u.ssrcGroups=o[n],void 0!==a&&void 0!==a.media&&Array.isArray(a.media)&&a.media.forEach((function(e){"object"==typeof e.sources&&Object.keys(e.sources).forEach((function(t){t===n&&(u.mid=e.mid)}))})),void 0===u.mid&&(u.mid=[r.type,"-",n].join("")),u.candidates=d,u.iceUfrag=l,u.icePwd=h,u.fingerprint=p,u.port=s,f[u.mid]=u,y[v]=u.sources,t.cache.mlU2BMap[v]=g,void 0===t.cache.mlB2UMap[g]&&(t.cache.mlB2UMap[g]=v),v++)):m[r.type][n]=i[n]}));else{var u=r;u.candidates=d,u.iceUfrag=l,u.icePwd=h,u.fingerprint=p,u.port=s,f[u.mid]=u,t.cache.mlU2BMap[v]=g,void 0===t.cache.mlB2UMap[g]&&(t.cache.mlB2UMap[g]=v)}g++}else f[r.mid]=r})),r.media=[],s=[],"answer"===e.type)for(var I=0;I<a.media.length;I++){var E=a.media[I];delete E.msid,delete E.sources,delete E.ssrcGroups,void 0===y[I]?E.direction&&"sendrecv"!==E.direction?"sendonly"===E.direction&&(E.direction="inactive"):E.direction="recvonly":E.direction&&"sendrecv"!==E.direction?"recvonly"===E.direction&&(E.direction="sendonly"):E.direction="sendrecv",E.sources=y[I],E.candidates=d,E.iceUfrag=l,E.icePwd=h,E.fingerprint=p,E.rtp=S[E.type],E.payloads=_[E.type],E.rtcpFb=b[E.type],r.media.push(E),"string"==typeof E.mid&&s.push(E.mid)}else void 0!==a&&void 0!==a.media&&Array.isArray(a.media)&&a.media.forEach((function(e){s.push(e.mid),void 0!==f[e.mid]?r.media.push(f[e.mid]):(delete e.msid,delete e.sources,delete e.ssrcGroups,e.direction&&"sendrecv"!==e.direction||(e.direction="sendonly"),e.direction&&"recvonly"!==e.direction||(e.direction="inactive"),function(e){void 0!==e.setup&&("active"===e.setup?e.setup="passive":"passive"===e.setup&&(e.setup="active"))}(e),r.media.push(e))})),Object.keys(f).forEach((function(e){if(-1===s.indexOf(e))if(s.push(e),"recvonly"===f[e].direction){var t=!1;r.media.some((function(r){if(("sendrecv"===r.direction||"sendonly"===r.direction)&&r.type===f[e].type)return Object.keys(f[e].sources).forEach((function(t){r.sources[t]=f[e].sources[t]})),t=!0,!0})),t||r.media.push(f[e])}else r.media.push(f[e])}));["audio","video"].forEach((function(e){if(r&&r.media&&Array.isArray(r.media)){var i=null;if(Object.keys(m[e]).length>0&&null===(i=t.getFirstSendingIndexFromAnswer(e)))for(var n=0;n<r.media.length;n++)if(r.media[n].type===e){i=n;break}if(i&&r.media.length>i){var s=r.media[i];Object.keys(m[e]).forEach((function(t){s.sources&&s.sources[t]&&console.warn("Replacing an existing SSRC."),s.sources||(s.sources={}),s.sources[t]=m[e][t]}))}}})),void 0!==r.groups&&r.groups.some((function(e){if("BUNDLE"===e.type)return e.mids=s.join(" "),!0})),r.msidSemantic={semantic:"WMS",token:"*"};var T=i.write(r);return this.cache[e.type]=T,new RTCSessionDescription({type:e.type,sdp:T})}},function(e,t,r){var i=r(22);t.write=function(e,t){return void 0!==e&&void 0!==e.media&&Array.isArray(e.media)&&e.media.forEach((function(e){void 0!==e.sources&&0!==Object.keys(e.sources).length&&(e.ssrcs=[],Object.keys(e.sources).forEach((function(t){var r=e.sources[t];Object.keys(r).forEach((function(i){e.ssrcs.push({id:t,attribute:i,value:r[i]})}))})),delete e.sources),void 0!==e.ssrcGroups&&Array.isArray(e.ssrcGroups)&&e.ssrcGroups.forEach((function(e){void 0!==e.ssrcs&&Array.isArray(e.ssrcs)&&(e.ssrcs=e.ssrcs.join(" "))}))})),void 0!==e&&void 0!==e.groups&&Array.isArray(e.groups)&&e.groups.forEach((function(e){void 0!==e.mids&&Array.isArray(e.mids)&&(e.mids=e.mids.join(" "))})),i.write(e,t)},t.parse=function(e){var t=i.parse(e);return void 0!==t&&void 0!==t.media&&Array.isArray(t.media)&&t.media.forEach((function(e){void 0!==e.ssrcs&&Array.isArray(e.ssrcs)&&(e.sources={},e.ssrcs.forEach((function(t){e.sources[t.id]||(e.sources[t.id]={}),e.sources[t.id][t.attribute]=t.value})),delete e.ssrcs),void 0!==e.ssrcGroups&&Array.isArray(e.ssrcGroups)&&e.ssrcGroups.forEach((function(e){"string"==typeof e.ssrcs&&(e.ssrcs=e.ssrcs.split(" "))}))})),void 0!==t&&void 0!==t.groups&&Array.isArray(t.groups)&&t.groups.forEach((function(e){"string"==typeof e.mids&&(e.mids=e.mids.split(" "))})),t}},function(e,t,r){var i=r(23),n=r(24);t.write=n,t.parse=i.parse,t.parseFmtpConfig=i.parseFmtpConfig,t.parsePayloads=i.parsePayloads,t.parseRemoteCandidates=i.parseRemoteCandidates},function(e,t,r){var i=function(e){return String(Number(e))===e?Number(e):e},n=function(e,t,r){var n=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:n&&!t[e.name]&&(t[e.name]={});var s=e.push?{}:n?t[e.name]:t;!function(e,t,r,n){if(n&&!r)t[n]=i(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(t[r[s]]=i(e[s+1]))}(r.match(e.reg),s,e.names,e.name),e.push&&t[e.push].push(s)},s=r(10),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(e){var t={},r=[],i=t;return e.split(/(\r\n|\r|\n)/).filter(o).forEach((function(e){var t=e[0],o=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),i=r[r.length-1]);for(var a=0;a<(s[t]||[]).length;a+=1){var c=s[t][a];if(c.reg.test(o))return n(c,i,o)}})),t.media=r,t};var a=function(e,t){var r=t.split("=");return 2===r.length&&(e[r[0]]=i(r[1])),e};t.parseFmtpConfig=function(e){return e.split(/\;\s?/).reduce(a,{})},t.parsePayloads=function(e){return e.split(" ").map(Number)},t.parseRemoteCandidates=function(e){for(var t=[],r=e.split(" ").map(i),n=0;n<r.length;n+=3)t.push({component:r[n],ip:r[n+1],port:r[n+2]});return t}},function(e,t,r){var i=r(10),n=/%[sdv%]/g,s=function(e){var t=1,r=arguments,i=r.length;return e.replace(n,(function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},o=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(r[t.name][o]):i.push(r[t.names[n]])}else i.push(r[t.name]);return s.apply(null,i)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c=["i","c","b","a"];e.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||a,n=t.innerOrder||c,s=[];return r.forEach((function(t){i[t].forEach((function(r){r.name in e&&null!=e[r.name]?s.push(o(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){s.push(o(t,r,e))}))}))})),e.media.forEach((function(e){s.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(r){r.name in e&&null!=e[r.name]?s.push(o(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){s.push(o(t,r,e))}))}))}))})),s.join("\r\n")+"\r\n"}},function(e,t){e.exports=function e(t){if(!t)return!1;if(this.length!=t.length)return!1;for(var r=0,i=this.length;r<i;r++)if(this[r]instanceof Array&&t[r]instanceof Array){if(!e.apply(this[r],[t[r]]))return!1}else if(this[r]!=t[r])return!1;return!0}},function(e,t,r){(function(i){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))})),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&void 0!==i&&"env"in i&&(e=i.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(27)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this,r(9))},function(e,t,r){e.exports=function(e){function t(e){let r,n,s,o=null;function a(...e){if(!a.enabled)return;const i=a,n=Number(new Date),s=n-(r||n);i.diff=s,i.prev=r,i.curr=n,r=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,n)=>{if("%%"===r)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];r=s.call(i,t),e.splice(o,1),o--}return r})),t.formatArgs.call(i,e),(i.log||t.log).apply(i,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=i,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function i(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").split(/[\s,]+/),n=i.length;for(r=0;r<n;r++)i[r]&&("-"===(e=i[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,i;for(r=0,i=t.skips.length;r<i;r++)if(t.skips[r].test(e))return!1;for(r=0,i=t.names.length;r<i;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=r(28),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},function(e,t){var r=1e3,i=6e4,n=60*i,s=24*n;function o(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}e.exports=function(e,t){t=t||{};var a=typeof e;if("string"===a&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*s;case"hours":case"hour":case"hrs":case"hr":case"h":return o*n;case"minutes":case"minute":case"mins":case"min":case"m":return o*i;case"seconds":case"second":case"secs":case"sec":case"s":return o*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===a&&isFinite(e))return t.long?function(e){var t=Math.abs(e);return t>=s?o(e,t,s,"day"):t>=n?o(e,t,n,"hour"):t>=i?o(e,t,i,"minute"):t>=r?o(e,t,r,"second"):e+" ms"}(e):function(e){var t=Math.abs(e);return t>=s?Math.round(e/s)+"d":t>=n?Math.round(e/n)+"h":t>=i?Math.round(e/i)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},function(e,t,r){r.r(t);var i=r(1);class n{constructor(e){this.worker=e,this.handleEvents()}handleEvents(){this.worker.addEventListener("message",(e=>{var t;let r=e.data.data;setTimeout((()=>{this.worker.postMessage({type:"pong",id:r.id})}),Math.max(null!==(t=r.timeout)&&void 0!==t?t:0,4))}))}}t.default=function(e){try{new n(e)}catch(e){i.error("new WorkerSetTimeout failed")}}},function(e,t,r){r.r(t),r.d(t,"Logger",(function(){return uo})),r.d(t,"Events",(function(){return lo})),r.d(t,"createStream",(function(){return ho})),r.d(t,"createClient",(function(){return po})),r.d(t,"setEnv",(function(){return mo})),r.d(t,"setVTRequestTimeout",(function(){return fo})),r.d(t,"useRoomChannelType",(function(){return go})),r.d(t,"forcePlanBSimulcast",(function(){return vo})),r.d(t,"setCustomUrl",(function(){return yo})),r.d(t,"addProxies",(function(){return _o})),r.d(t,"setCanary",(function(){return bo})),r.d(t,"removeProxies",(function(){return So})),r.d(t,"checkSystemSupport",(function(){return Io})),r.d(t,"supportScreenSharing",(function(){return Eo})),r.d(t,"isSmallStreamSupported",(function(){return To})),r.d(t,"getPermissions",(function(){return Ro})),r.d(t,"base64Decode",(function(){return wo})),r.d(t,"enumAudioInputDevices",(function(){return Ao})),r.d(t,"enumAudioOutputDevices",(function(){return ko})),r.d(t,"enumVideoDevices",(function(){return Co})),r.d(t,"version",(function(){return Mo})),r.d(t,"RenderProcess",(function(){return Oo}));var i={};r.r(i),r.d(i,"STREAM_ADDED",(function(){return w})),r.d(i,"STREAM_REMOVED",(function(){return A})),r.d(i,"STREAM_UPDATED",(function(){return k})),r.d(i,"STREAM_PUBLISHED",(function(){return C})),r.d(i,"STREAM_SUBSCRIBED",(function(){return M})),r.d(i,"MUTE_VIDEO",(function(){return O})),r.d(i,"UNMUTE_VIDEO",(function(){return P})),r.d(i,"MUTE_AUDIO",(function(){return L})),r.d(i,"UNMUTE_AUDIO",(function(){return x})),r.d(i,"ERROR",(function(){return D})),r.d(i,"PEER_JOINED",(function(){return N})),r.d(i,"PEER_LEAVED",(function(){return $})),r.d(i,"CLIENT_BANNED",(function(){return U})),r.d(i,"USER_KICKED",(function(){return B})),r.d(i,"TOKEN_WILL_EXPIRE",(function(){return V})),r.d(i,"TOKEN_EXPIRE",(function(){return F})),r.d(i,"ROOM_CLOSED",(function(){return j})),r.d(i,"SYNC_ROOM_COMPLETED",(function(){return W}));var n={};r.r(n),r.d(n,"VIDEO_TRACK_ENDED",(function(){return X})),r.d(n,"AUDIO_TRACK_ENDED",(function(){return Z})),r.d(n,"VIDEO_TRACK_MUTE",(function(){return ee})),r.d(n,"AUDIO_TRACK_MUTE",(function(){return te})),r.d(n,"VIDEO_TRACK_UNMUTE",(function(){return re})),r.d(n,"AUDIO_TRACK_UNMUTE",(function(){return ie})),r.d(n,"TRACK_UPDATE",(function(){return ne})),r.d(n,"PLAYER_STATE_CHANGED",(function(){return se})),r.d(n,"CONNECT_ERROR",(function(){return oe})),r.d(n,"CONNECT_SUCCESS",(function(){return ae})),r.d(n,"CONNECT_RECONNECTING",(function(){return ce})),r.d(n,"PLAYER_VIDEO_RENDERED",(function(){return ue})),r.d(n,"PLAYER_AUDIO_RENDERED",(function(){return de})),r.d(n,"AUDIO_LEVEL",(function(){return le})),r.d(n,"CLOSE",(function(){return he}));var s={};r.r(s),r.d(s,"add",(function(){return _r})),r.d(s,"has",(function(){return br})),r.d(s,"clear",(function(){return Sr})),r.d(s,"all",(function(){return Ir})),r.d(s,"remove",(function(){return Er}));var o=r(0);function a(e){return 0===e}function c(e){return 1===e}function u(e){return"video"===e.kind}function d(e){return"audio"===e.kind}let l="production";const h="2.20.3-boom";let p,m=15,f=null;function g(){return m}let v=0,y=!1,_=[];function b(){return p}function S(){return v}const I={4096:1001,4097:1002,16385:4001,16386:4002,16387:4003,16388:4e3,16389:4004,16448:4005,16449:4006,16450:4007,65535:9e3},E="contact with BaiJiaYun for more information",T={1e3:{name:"local error",message:E},1001:{name:"param invalid",message:"参数类型错误"},1002:{name:"invalid operation",message:"非法操作"},1003:{name:"not support",message:"不支持"},4e3:{name:"join channel error",message:"进入频道失败"},4001:{name:"signal setup failed",message:"信令通道建立失败"},4002:{name:"signal error",message:"信令通道错误"},4003:{name:"ice transport error",message:"ICE Tansport 连接错误"},4004:{name:"create offer failed",message:"创建 sdp offer 失败"},4005:{name:"client banned",message:"用户被踢出"},4006:{name:"media server timeout",message:"媒体传输超时"},4007:{name:"subscription timeout",message:"订阅远端流超时"},4008:{name:"media publish error",message:"推流错误"},5e3:{name:"fetch fail",message:"网络请求失败,请检查网络状态"},5001:{name:"userSig error",message:"userSig 验证失败"},9e3:{name:"unknow",message:E},1010:{name:"permission deny",message:"权限验证失败"}};class R extends Error{constructor(e,t,r,i){if(super(),this.RTCType=b(),this.code=e,this.error=r,this.BRTCErrorFlag=!0,c(this.RTCType)&&r&&r.getCode){let e=I[r.getCode()];e&&(this.code=e)}this.eName=i||(T[this.code]?T[this.code].name:"BRTCError"),this.message=`[webrtc_type: ${this.RTCType}] [code: ${this.code}] [error_name: ${this.eName}] ${t||(T[this.code]?T[this.code].message:"unkown")}`}static instanceOf(e){return!(!e||!e.BRTCErrorFlag)}getCode(){return this.code}}const w="stream-added",A="stream-removed",k="stream-updated",C="stream-published",M="stream-subscribed",O="mute-video",P="unmute-video",L="mute-audio",x="unmute-audio",D="error",N="peer-joined",$="peer-leaved",U="client-banned",B="user-kicked",V="token-will-expire",F="token-expire",j="room-closed",W="sync-room-completed";function q(e,t){return!t&&o.i(e)&&!/^0[0-9]+/.test(e)&&/^[0-9]{1,15}$/g.test(e)?+e:e}var G=r(2);function H(e,t,r){if(o.d(e))return o.a(r)?e.apply(t,r):t!==G.m?e.call(t,r):r!==G.m?e(r):e()}var z=r(5);function J(){return Date.now()}var Y=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function K(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){let r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))}function Q(e=0){return J()+e}const X="video-track-ended",Z="audio-track-ended",ee="video-track-mute",te="audio-track-mute",re="video-track-unmute",ie="audio-track-unmute",ne="track-update",se="player-state-changed",oe="connect-error",ae="connect-success",ce="connect-reconnecting",ue="player-video-rendered",de="player-audio-rendered",le="audio-level",he="close";var pe=r(1),me=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class fe{constructor(e,t,r){var i;this.element=e,this.options=t,this.logger=r,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.backgroundColor=null!==(i=t.backgroundColor)&&void 0!==i?i:"black",this.container.style.overflow="hidden",e.appendChild(this.container)}playVideo(){if(!1===this.options.video)return;const e=this.stream.getVideoTrack();if(!e)return;if(!this.video){this.video=document.createElement("video"),this.video.autoplay=!0,this.video.playsInline=!0,this.video.muted=this.options.muted,this.video.style.width="100%",this.video.style.height="100%",this.video.style.position="absolute";let e="";this.options.rotateX&&(e=`rotateX(${this.options.rotateX}deg)`),this.options.rotateY&&(e=`${e} rotateY(${this.options.rotateY}deg)`),e&&(this.video.style.transform=e),this.video.style.objectFit=this.options.fit,this.video.id="video_"+this.stream.getStreamId(),this.container.appendChild(this.video),this.video.addEventListener("playing",(()=>{this.videoStatus="PLAYING",this.stream&&(this.stream.fire(se,{type:"video",state:this.videoStatus,reason:"playing"}),this.log(`stream video playing, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))})),this.video.addEventListener("pause",(()=>{this.videoStatus="PAUSED",this.stream&&(this.stream.fire(se,{type:"video",state:this.videoStatus,reason:"pause"}),this.log(`stream video pause, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))})),this.video.addEventListener("stalled",(()=>{this.videoStatus="PAUSED",this.stream&&(this.stream.fire(se,{type:"video",state:this.videoStatus,reason:"stalled"}),this.log(`stream video stalled, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))})),this.video.addEventListener("loadeddata",(()=>{this.stream&&(this.stream.fire(ue),this.log(`stream video loadeddata, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))}))}let t=new MediaStream;t.addTrack(e),this.video.srcObject=null,this.video.srcObject=t,this.videoStatus="STOPPED"}playAudio(){if(!1===this.options.audio)return;const e=this.stream.getAudioTrack();if(!e)return;this.audio||(this.audio=document.createElement("audio"),this.audio.autoplay=!0,this.audio.playsInline=!0,this.audio.muted=this.options.muted,this.audio.id="audio_"+this.stream.getStreamId(),this.container.appendChild(this.audio),this.stream.getAudioDeviceId()&&this.setSinkId(this.stream.getAudioDeviceId()),this.audio.volume=o.f(this.stream.getAudioVolume())?this.stream.getAudioVolume():1,this.audio.addEventListener("playing",(()=>{this.audioStatus="PLAYING",this.stream&&(this.stream.fire(se,{type:"audio",state:this.audioStatus,reason:"playing"}),this.log(`stream audio playing, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))})),this.audio.addEventListener("pause",(()=>{this.audioStatus="PAUSED",this.stream&&(this.stream.fire(se,{type:"audio",state:this.audioStatus,reason:"pause"}),this.log(`stream audio pause, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))})),this.audio.addEventListener("stalled",(()=>{this.audioStatus="PAUSED",this.stream&&(this.stream.fire(se,{type:"audio",state:this.audioStatus,reason:"stalled"}),this.log(`stream audio stalled, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))})),this.audio.addEventListener("loadeddata",(()=>{this.stream&&(this.stream.fire(de),this.log(`stream audio loadeddata, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"))})));let t=new MediaStream;t.addTrack(e),this.audio.srcObject=null,this.audio.srcObject=t,this.audioStatus="STOPPED"}setSinkId(e){return me(this,void 0,void 0,(function*(){this.audio&&o.d(this.audio.setSinkId)&&(yield this.audio.setSinkId(e))}))}setVolume(e){this.audio&&(this.audio.volume=e)}play(e){return me(this,void 0,void 0,(function*(){this.stream=e,this.container.id="player_"+e.getStreamId(),this.stream.hasAudio()&&this.playAudio(),this.stream.hasVideo()&&this.playVideo();try{this.audio&&(yield this.audio.play()),this.video&&(yield this.video.play())}catch(e){this.log(`stream play error, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}, name: ${(null==e?void 0:e.name)||"unknow"}, message: ${(null==e?void 0:e.message)||"unknow"}`,"AbortError"===e.name?pe.DEBUG:pe.ERROR,"player"),this.stream.fire(se,{type:"error",reason:e})}}))}replay(e,t=!0,r=!0){return me(this,void 0,void 0,(function*(){this.log(`stream replay, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player"),this.stream=e;try{this.stream.hasAudio()&&r&&this.playAudio(),this.stream.hasVideo()&&t&&this.playVideo(),this.stream.hasAudio()&&r&&this.audio&&(yield this.audio.play()),this.stream.hasVideo()&&t&&this.video&&(yield this.video.play())}catch(e){this.log(`stream replay error, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}, name: ${(null==e?void 0:e.name)||"unknow"}, message: ${(null==e?void 0:e.message)||"unknow"}`,"AbortError"===e.name?pe.DEBUG:pe.ERROR,"player"),this.stream.fire(se,{type:"error",reason:e})}}))}muteVideo(){this.video&&(this.video.srcObject=void 0,this.videoStatus="STOPPED")}muteAudio(){this.audio&&(this.audio.srcObject=void 0,this.audioStatus="STOPPED")}unmuteVideo(){if(this.video&&this.stream&&"STOPPED"===this.videoStatus){let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e}}unmuteAudio(){if(this.audio&&this.stream&&"STOPPED"===this.audioStatus){let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e}}destroy(){this.element.removeChild(this.container),this.audio&&(this.audio.srcObject=null),this.video&&(this.video.srcObject=null),this.audio=null,this.video=null,this.container=null,this.log(`stream player destroy, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player")}resume(){return me(this,void 0,void 0,(function*(){this.video&&this.video.play(),this.audio&&(yield function(){return Y(this,void 0,void 0,(function*(){}))}(),this.audio.play()),this.log(`stream player resume, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,pe.INFO,"player")}))}getVideoFrame(){if(this.video&&"STOPPED"!==this.videoStatus){const e=document.createElement("canvas");return e.width=this.video.videoWidth,e.height=this.video.videoHeight,e.getContext("2d").drawImage(this.video,0,0),e.toDataURL("image/png")}}log(e,t,r){this.logger?this.logger.log(e,t,r):pe.log(t,e,r)}}class ge{constructor(e=10){this.queue=[],this.win=e}addData(e,t){for(;this.queue.length>=this.win;)this.queue.shift();this.queue.push([Number(e),Number(t)])}reset(){this.queue.length=0}getPacketLossRate(){let e,t=this.queue.length;if(0==t)e=0;else if(t<this.win){let r=this.queue[t-1][0];e=this.queue[t-1][1]/r}else if(t===this.win){let r=Math.abs(this.queue[t-1][0]-this.queue[0][0]);e=Math.abs(this.queue[t-1][1]-this.queue[0][1])/r}else e=0;return e>=1&&(e=1),Number.isNaN(e)&&(e=0),Math.max(Math.round(100*e),0)}}class ve{constructor(e=1){this.sample=e,this.audioPackLost=new ge(2),this.videoPackLost=new ge(2),this.audioBytesBefore=this.audioBytesNow=0,this.videoBytesBefore=this.videoBytesNow=0,this.frameBefore=this.frameNow=0}addData(e,t,r,i,n,s,o){this.audioPackLost.addData(r,i),this.videoPackLost.addData(n,s),this.audioBytesBefore=this.audioBytesNow,this.audioBytesNow=e,this.videoBytesBefore=this.videoBytesNow,this.videoBytesNow=t,this.frameBefore=this.frameNow,this.frameNow=o}getAudioPacketLoss(){return this.audioPackLost.getPacketLossRate()}getVideoPacketLoss(){return this.videoPackLost.getPacketLossRate()}getAudioBitrate(){return this.audioBytesBefore?Math.max(Math.round(8*(this.audioBytesNow-this.audioBytesBefore)/1e3/this.sample),0):0}getVideoBitrate(){return this.videoBytesBefore?Math.max(Math.round(8*(this.videoBytesNow-this.videoBytesBefore)/1e3/this.sample),0):0}getFrameRate(){return this.frameBefore?Math.max(Math.round((this.frameNow-this.frameBefore)/this.sample),0):0}destroy(){this.sample=null,this.audioPackLost=null,this.videoPackLost=null,this.audioBytesBefore=this.audioBytesNow=null,this.videoBytesBefore=this.videoBytesNow=null,this.frameBefore=this.frameNow=null}}function ye(e,t,r){if(!e)return;const{length:i}=e;if(i)if(r)for(let r=i-1;r>=0&&t(e[r],r)!==G.d;r--);else for(let r=0;r<i&&t(e[r],r)!==G.d;r++);}function _e(e,t){e[e.length]=t}function be(e,t,r){o.a(t)?ye(t,(function(t){r(e,t)})):r(e,t)}function Se(e,t){be(e,t,_e)}function Ie(e,t,r){let i=0;return ye(e,(function(n,s){(r===G.d?n==t:n===t)&&(e.splice(s,1),i++)}),G.l),i}function Ee(e,t,r){return function(e,t,r){let i=G.f;return ye(e,(function(e,n){if(r===G.d?e==t:e===t)return i=n,G.d})),i}(e,t,r)>=0}function Te(e){return o.a(e)?e:H(G.a.slice,e)}class Re{constructor(e,t){this.type=e,this.phase=Re.PHASE_CURRENT,t&&(this.originalEvent=t)}preventDefault(){const e=this;if(!e.isPrevented){const{originalEvent:t}=e;t&&t.preventDefault(),e.isPrevented=G.l}return e}stopPropagation(){const e=this;if(!e.isStoped){const{originalEvent:t}=e;t&&t.stopPropagation(),e.isStoped=G.l}return e}prevent(){return this.preventDefault()}stop(){return this.stopPropagation()}}Re.PHASE_CURRENT=0,Re.PHASE_UPWARD=1,Re.PHASE_DOWNWARD=G.f;var we=r(4);const Ae={};function ke(e,t){const r=Ae.hasOwnProperty(e)?Ae[e]:Ae[e]=e.split(G.h);for(let e=0,i=r.length-1;e<=i&&t(r[e],e===i)!==G.d;e++);}function Ce(e){return e!==G.m}function Me(e){return Ce(e)?Object.keys(e):[]}function Oe(e,t){for(let r in e)if(t(e[r],r)===G.d)break}function Pe(e,t){return o.h(e)?o.h(t)?(Oe(t,(function(t,r){e[r]=t})),e):e:t}function Le(e,t,r){return Pe(Pe(e,t),r)}function xe(e,t){let r=e;return o.a(e)?t?(r=[],ye(e,(function(e,i){r[i]=xe(e,t)}))):r=e.slice():o.h(e)&&(r={},Oe(e,(function(e,i){r[i]=t?xe(e,t):e}))),r}function De(e,t,r){let i;return ke(t,(function(t,r){if(e==G.g)return i=G.m,G.d;{let n=e[t],s=n!==G.m;r?i=s?n:G.m:e=n}})),i===G.m&&(i=r),i}function Ne(e){let t=[];const r=(e,r)=>{r=o.d(r)?r():null==r?"":r,t[t.length]=encodeURIComponent(e)+"="+encodeURIComponent(r)};return(o.a(e)||o.e(e))&&(o.a(e)?ye(e,((e,t)=>{r(t,e)})):Oe(e,((e,t)=>{r(t,e)}))),t.join("&").replace(/%20/g,"+")}class $e{constructor(e){this.ns=e||G.d,this.listeners={}}fire(e,t,r){let i=this,n=o.i(e)?i.parse(e):e,s=i.listeners[n.type],a=G.l;if(s){s=xe(s);const e=t&&t[0]instanceof Re?t[0]:G.m;ye(s,(function(o){if(!Ve(n.ns,o,G.l)||!Ee(s,o)||r&&!r(n,t,o))return;e&&(e.listener=o.fn);let c=H(o.fn,o.ctx,t);return e&&(e.listener=G.m),o.num=o.num?o.num+1:1,o.num===o.max&&i.off(n,o.fn),e&&(c===G.d?e.prevent().stop():e.isStoped&&(c=G.d)),c===G.d?a=G.d:void 0}))}return a}on(e,t){const r=this,i=r.listeners,n=o.d(t)?{fn:t}:t;if(o.h(n)&&o.d(n.fn)){const t=o.i(e)?r.parse(e):e;n.ns=t.ns,Se(i[t.type]||(i[t.type]=[]),n)}return this}one(e,t){return o.d(t)?t={fn:t,max:1}:t.max=1,this.on(e,t)}off(e,t){const r=this,i=r.listeners;if(e){const n=o.i(e)?r.parse(e):e,s=n.type,a=n.ns,c=Be(t),u=function(e,t){ye(e,(function(t,r){c(t)&&e.splice(r,1)}),G.l),e.length||delete i[t]},d=function(e,t){ye(e,(function(t,r){Ve(a,t)&&e.splice(r,1)}),G.l),e.length||delete i[t]};s?i[s]&&u(i[s],s):a&&Oe(i,d)}else r.listeners={}}has(e,t){let r=this.listeners,i=o.i(e)?this.parse(e):e,n=i.type,s=i.ns,a=G.l,c=Be(t),u=function(e){return ye(e,(function(e){if(Ve(s,e))return a=G.d})),a};return n?r[n]&&ye(r[n],(function(e){if(c(e))return a=G.d})):s&&Oe(r,u),!a}parse(e){const t={type:e,ns:G.c};if(this.ns){const r=we.b(e,G.h);r>=0&&(t.type=we.c(e,0,r),t.ns=we.c(e,r+1))}return t}}function Ue(){return G.l}function Be(e){return o.d(e)?function(t){return e===t.fn}:Ue}function Ve(e,t,r){const{ns:i}=t;return i&&e?i===e:r?G.l:G.d}function Fe(e,t,r){let i;return function(){let n=this;if(!i){const s=Te(arguments);r&&H(e,n,s),i=setTimeout((function(){i=G.m,r||H(e,n,s)}),t)}}}var je=r(3);class We extends class{constructor(e,t){this.audioWorkletNode=new AudioWorkletNode(e,t)}connect(e){this.audioWorkletNode.connect(e)}getNode(){return this.audioWorkletNode}disconnect(){this.audioWorkletNode.disconnect()}getParameters(e){const t=this.audioWorkletNode.parameters;if(o.d(t.get))return t.get(e);t.forEach(((t,r)=>{if(r===e)return t}))}}{constructor(e){super(e,"meter-processor"),this.audioLevel=0,this.audioWorkletNode.port.onmessage=e=>{this.audioLevel=e.data}}getAudioLevel(){return this.audioLevel}}const qe="\nfunction webpackBootstrapFunc (modules) {\n var installedModules = {};\n function __webpack_require__(moduleId) {\n if(installedModules[moduleId])\n return installedModules[moduleId].exports;\n var module = installedModules[moduleId] = {\n i: moduleId,\n l: false,\n exports: {}\n };\n modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n module.l = true;\n return module.exports;\n }\n __webpack_require__.m = modules;\n __webpack_require__.c = installedModules;\n __webpack_require__.i = function(value) { return value; };\n __webpack_require__.d = function(exports, name, getter) {\n if(!__webpack_require__.o(exports, name)) {\n Object.defineProperty(exports, name, {\n configurable: false,\n enumerable: true,\n get: getter\n });\n }\n };\n __webpack_require__.r = function(exports) {\n Object.defineProperty(exports, '__esModule', { value: true });\n };\n __webpack_require__.n = function(module) {\n var getter = module && module.__esModule ?\n function getDefault() { return module['default']; } :\n function getModuleExports() { return module; };\n __webpack_require__.d(getter, 'a', getter);\n return getter;\n };\n __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n __webpack_require__.p = \"/\";\n __webpack_require__.oe = function(err) { console.error(err); throw err; };\n var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE);\n return f.default || f;\n}\n";function Ge(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function He(e,t,i){const n={};n[i]=[];let s=t.toString();const o=s.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!o)return n;const a=o[1];let c,u=new RegExp("(\\\\n|\\W)"+Ge(a)+"\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");for(;c=u.exec(s);)"dll-reference"!==c[3]&&n[i].push(c[3]);for(u=new RegExp("\\("+Ge(a)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)',"g");c=u.exec(s);)e[c[2]]||(n[i].push(c[1]),e[c[2]]=r(c[1]).m),n[c[2]]=n[c[2]]||[],n[c[2]].push(c[4]);const d=Object.keys(n);for(let e=0;e<d.length;e++)for(let t=0;t<n[d[e]].length;t++)l=n[d[e]][t],isNaN(1*l)||(n[d[e]][t]=1*n[d[e]][t]);var l;return n}function ze(e){return Object.keys(e).reduce((function(t,r){return t||e[r].length>0}),!1)}var Je=function(e,t){t=t||{};const i={main:r.m},n=t.all?{main:Object.keys(i.main)}:function(e,t){const r={main:[t]},i={main:[]},n={main:{}};for(;ze(r);){const t=Object.keys(r);for(let s=0;s<t.length;s++){let o=t[s],a=r[o].pop();if(n[o]=n[o]||{},n[o][a]||!e[o][a])continue;n[o][a]=!0,i[o]=i[o]||[],i[o].push(a);let c=He(e,e[o][a],o),u=Object.keys(c);for(let e=0;e<u.length;e++)r[u[e]]=r[u[e]]||[],r[u[e]]=r[u[e]].concat(c[u[e]])}}return i}(i,e);let s="";Object.keys(n).filter((function(e){return"main"!==e})).forEach((function(e){let t=0;for(;n[e][t];)t++;n[e].push(t),i[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",s=s+"var "+e+" = ("+qe.replace("ENTRY_MODULE",JSON.stringify(t))+")({"+n[e].map((function(t){return JSON.stringify(t)+": "+i[e][t].toString()})).join(",")+"});\n"})),s=t.simple?"("+i.main[e].toString().replace(/^function(module, exports) {\\n*/,"")+")(null, null)":s+"new (("+qe.replace("ENTRY_MODULE",JSON.stringify(e))+")({"+n.main.map((function(e){return JSON.stringify(e)+": "+i.main[e].toString()})).join(",")+"}))(self);";const o=new window.Blob([s],{type:"text/javascript"});return t.bare?o:(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(o)},Ye=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const Ke={averaging:.95};let Qe;const Xe="function"==typeof AudioWorkletNode;let Ze;class et{constructor(e={}){this.options=Le({},Ke,e),this.readyed=!1,Qe||function(){let e=window.AudioContext||window.webkitAudioContext;if(Qe=new e,Xe){const e=Je(16,{simple:!0});Ze=Qe.audioWorklet.addModule(e)}}()}ready(){return Ye(this,void 0,void 0,(function*(){this.readyed||(Xe?yield new Promise((e=>{Ze.then((()=>{this.createWorkletNode(),e()}))})):this.createScriptProcessorNode(),this.node.connect(Qe.destination),this.readyed=!0,"suspended"===Qe.state&&this.resume())}))}createWorkletNode(){this.node=new We(Qe);const e=this.node.getParameters("output"),t=this.node.getParameters("averaging");e.value=0,t.value=this.options.averaging}createScriptProcessorNode(){const e=Qe.createScriptProcessor(2048,1,1);e.onaudioprocess=t=>{const r=t.inputBuffer.getChannelData(0);let i=0;for(let e=0;e<r.length;e++)i+=r[e]*r[e];const n=Math.sqrt(i/r.length);e.volume=Math.max(n,e.volume*e.averaging)},e.volume=0,e.averaging=this.options.averaging,this.node=e}connect(e){return Ye(this,void 0,void 0,(function*(){if("audio"===e.kind){if(this.readyed||(yield this.ready()),e===this.track)return;this.disconnect(),this.track=e,this.mediaStream=new MediaStream,this.mediaStream.addTrack(this.track),this.mediaSourceNode=Qe.createMediaStreamSource(this.mediaStream),Xe?this.mediaSourceNode.connect(this.node.getNode()):this.mediaSourceNode.connect(this.node)}}))}getVolume(){return this.node?Xe?this.node.getAudioLevel():this.node.volume:0}disconnect(){this.mediaSourceNode&&(this.mediaSourceNode.disconnect(),this.mediaSourceNode=null),this.track=null,this.mediaStream=null}resume(){return Ye(this,void 0,void 0,(function*(){if(Qe&&"suspended"===Qe.state)return Qe.resume()}))}destroy(){this.disconnect(),this.node&&(this.node.disconnect(),this.node=null),this.readyed=!1}}function tt(e,t){return o.g(e)?+e:t!==G.m?t:0}function rt(e,t,r=!1){const i=t.split("."),n=e.split(".");for(let e=0;e<n.length;e++){if(r&&e==n.length-1&&tt(n[e])>=tt(i[e]))return n.length>=i.length;if(tt(n[e])>tt(i[e]))return!0;if(tt(n[e])<tt(i[e]))return!1;if(e===i.length-1&&e===n.length-1)return r;if(e===i.length-1)return!0;if(e===n.length-1)return!1}return!0}var it;function nt(e){return o.i(e)&&e.split(".").shift()||""}!function(e){e.ALIPAY="alipay",e.WECHAT="wechat",e.DING_TALK="dingtalk",e.BAIDU_APP="baiduApp",e.BAIDU="baidu",e.UC="uc",e.QQ="qq",e.QQ_APP="qqApp",e.IE="ie",e.EDGE="edge",e.CHROME="chrome",e.FIREFOX="firefox",e.OPERA="opera",e.SAFARI="safari",e.NEW_EDGE="newEdge"}(it||(it={}));const st=[[it.ALIPAY,/alipay/],[it.WECHAT,/micromessenger/],[it.DING_TALK,/dingtalk[ \/]([\d_.]+)/],[it.BAIDU_APP,/baiduboxapp/],[it.BAIDU,/baidubrowser/],[it.BAIDU,/bdbrowser/],[it.UC,/ucbrowser/],[it.UC,/ucweb/],[it.QQ,/qqbrowser[ \/]([\d_.]+)/],[it.QQ_APP,/qq/],[it.IE,/iemobile[ \/]([\d_.]+)/],[it.IE,/msie[ \/]([\d_.]+)/],[it.IE,/trident[ \/]([\d_.]+)/,4],[it.EDGE,/edge[ \/]([\d_.]+)/],[it.NEW_EDGE,/edg[ \/]([\d_.]+)/],[it.CHROME,/chrome[ \/]([\d_.]+)/],[it.FIREFOX,/firefox[ \/]([\d_.]+)/],[it.OPERA,/opera(?:.*version)?[ \/]([\d_.]+)/],[it.SAFARI,/version[ \/]([\d_.]+) safari/],[it.SAFARI,/version[ \/]([\d_.]+) \S* safari/],[it.SAFARI,/safari/]],ot={},at={},ct=function(e){let t,r;return ye(st,(i=>{let n=i[1].exec(e);if(n)return t=i[0],r=n[1],r&&(r=r.replace(/_/g,"."),i[2]&&(r=parseInt(r,10)+i[2]+".0")),!1})),{name:t||"",version:r||"",majorVersion:(ot[t]||nt)(r),checkVersion:at[t]||rt}}((navigator.userAgent||"").toLowerCase());ct.name&&(ct[ct.name]=!0);var ut=ct;function dt(e){if(o.i(e))return e;if(o.h(e)){if(o.i(e.message))return e.message;if(o.i(e.msg))return e.msg;if(o.d(e.toString))return e.toString()}return"unknow"}class lt{constructor(e,t,r){this.task=e,this.timeout=t,this.interval=r}start(){const e=this;e.stop();let t=e.timeout;const r=e.interval,i=function(){!1!==e.task()&&e.timer?e.timer=setTimeout(i,e.interval):e.stop()};null==t&&(t=r),e.timer=setTimeout(i,t)}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null)}updateInterval(e){this.interval=e}isStarted(){return!!this.timer}destroy(){this.stop(),this.task=this.timeout=this.interval=null}}function ht(e){if(e&&R.instanceOf(e))return e.getCode();const t=dt(e);return"request timeout"===t?9001:"stream has already destroyed"===t?4010:9e3}function pt(e){if(e){if(R.instanceOf(e))return null;if(o.d(e.getCode))return e.getCode();if(Ce(e.code))return e.code}return null}var mt=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class ft{constructor(e,t,r,i,n){if(this.uid=r,this.type=e,this.stream=n,this.webrtcType=i,this.iceStartTS=0,this.destroyed=!1,this.sid=t||K(),this.emitter=new $e(!0),this.reportCollector=new ve(2),this.audioTrackEventHandler={ended:()=>{this.audioMuteTimer&&(clearTimeout(this.audioMuteTimer),this.audioMuteTimer=null),this.emitter&&this.fire(Z),this.log(`${this.sid} Stream audioTrack ended, userId: ${this.uid}`,pe.DEBUG,"stream")},mute:()=>{this.getAudioOn()&&(this.audioMuteTimer&&clearTimeout(this.audioMuteTimer),this.audioMuteTimer=setTimeout((()=>{this.log(`${this.sid} Stream audioTrack mute, userId: ${this.uid}`,this.isLocalStream()?pe.WARN:pe.DEBUG,"stream"),this.fire(te),this.audioMuteTimer=null}),3e3))},unmute:()=>{this.audioMuteTimer?(clearTimeout(this.audioMuteTimer),this.audioMuteTimer=null):(this.log(`${this.sid} Stream audioTrack unmute, userId: ${this.uid}`,pe.DEBUG,"stream"),this.fire(ie))}},this.videoTrackEventHandler={ended:()=>{this.videoMuteTimer&&(clearTimeout(this.videoMuteTimer),this.videoMuteTimer=null),this.emitter&&this.fire(X),this.log(`${this.sid} Stream videoTrack ended, userId: ${this.uid}`,pe.DEBUG,"stream")},mute:()=>{this.getVideoOn()&&(this.videoMuteTimer&&clearTimeout(this.videoMuteTimer),this.videoMuteTimer=setTimeout((()=>{this.log(`${this.sid} Stream videoTrack mute, userId: ${this.uid}`,this.isLocalStream()?pe.WARN:pe.DEBUG,"stream"),this.fire(ee),this.videoMuteTimer=null}),3e3))},unmute:()=>{this.videoMuteTimer?(clearTimeout(this.videoMuteTimer),this.videoMuteTimer=null):(this.log(`${this.sid} Stream videoTrack unmute, userId: ${this.uid}`,pe.DEBUG,"stream"),this.fire(re))}},this.stream&&this.isLocalStream()&&this.addTrackEvents(),this.debounceReplay=Fe((()=>{this.playing&&this.player&&this.player.replay(this)}),100),(this.isLocalStream()||c(this.webrtcType)||(ut.safari||ut.firefox)&&a(this.webrtcType))&&!ut.dingtalk){try{this.soundMeter=new et}catch(e){this.soundMeter=null}this.audioLevelTimer=new lt((()=>{this.fire(le,this.getAudioLevel())}),0,1e3)}this.playing=!1}isStream(e){return this.stream===e}isLocalStream(){return this.type===ft.STREAM_TYPE_LOCAL}isScreenStream(){return!1}isPlaying(){return this.playing}isDestroyed(){return this.destroyed}getWebRTCType(){return this.webrtcType}getUserId(){return this.uid}setUserId(e){this.uid=e}getStreamId(){return this.sid}setStreamId(e){this.sid=e}getStream(){return this.stream}setStream(e,t){this.removeTrackEvents(),this.removeHandleEvents(),this.stream=t,this.webrtcType=e,this.isLocalStream()&&this.addTrackEvents(),this.handleEvents(),this.playing&&this.player&&this.debounceReplay(),this.log("setStream, userId: "+this.uid,pe.DEBUG,"stream")}getClient(){return this.client}setClient(e){this.client=e}syncClientOptions(e){o.f(e.audioLevelInterval)&&this.audioLevelTimer&&this.audioLevelTimer.updateInterval(e.audioLevelInterval)}setLogger(e){this.logger=e}setCollection(e){this.collection=e}getCollection(){return this.collection}setVolumeMeter(){this.audioTrack&&this.soundMeter&&this.soundMeter.connect(this.audioTrack),this.audioLevelTimer&&!this.audioLevelTimer.isStarted()&&this.audioLevelTimer.start()}hasVideo(){return!!this.stream&&(this.isLocalStream()?!!this.videoTrack:this.stream.hasVideo())}hasAudio(){return!!this.stream&&(this.isLocalStream()?!!this.audioTrack:this.stream.hasAudio())}getVideoOn(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(a(this.webrtcType))return this.stream.getVideoEnable();if(c(this.webrtcType)){if(this.isLocalStream()&&this.videoTrack)return this.videoTrack.enabled;if(!this.isLocalStream()&&t){let e=!1;return ye(t.getRemoteMutedState(),((t,r)=>{const i=this.getUserId();if(o.f(i)&&q(t.userId,!1)===i||o.i(i)&&q(t.userId,!0)===i)return e=!t.videoMuted,!1})),e}}return!1}getAudioOn(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(a(this.webrtcType))return this.stream.getAudioEnable();if(c(this.webrtcType)){if(this.isLocalStream()&&this.audioTrack)return this.audioTrack.enabled;if(!this.isLocalStream()&&t){let e=!1;return ye(t.getRemoteMutedState(),((t,r)=>{const i=this.getUserId();if(o.f(i)&&q(t.userId,!1)===i||o.i(i)&&q(t.userId,!0)===i)return e=!t.audioMuted,!1})),e}}return!1}get audioTrack(){return this.stream?this.stream.getAudioTrack():null}get videoTrack(){return this.stream?this.stream.getVideoTrack():null}getAudioTrack(){if(this.stream)return this.audioTrack}getVideoTrack(){if(this.stream)return this.videoTrack}getMediaStream(){if(this.stream)return a(this.webrtcType)?this.stream.getStream():c(this.webrtcType)?this.stream.mediaStream_:void 0}muteVideo(){return mt(this,void 0,void 0,(function*(){if(this.hasVideo())try{const e={stream:this.getActionStreamId(),type:0};return this.type===ft.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.muteVideo():c(this.webrtcType)&&this.stream.muteVideo():this.type===ft.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.muteVideo(),this.stutter&&this.stutter.resetVideo()),this.playing&&this.player&&this.player.muteVideo(),e.remote_id=Object(je.a)(this.getUserId())),this.reportAction("videoDisable",0,null,null,e),!0}catch(e){return this.reportAction("videoDisable",ht(e),null,null,{stream:this.getActionStreamId()},pt(e)),!1}return!1}))}unmuteVideo(){return mt(this,void 0,void 0,(function*(){if(this.hasVideo())try{const e={stream:this.getActionStreamId(),type:0};return this.type===ft.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.unmuteVideo():c(this.webrtcType)&&this.stream.unmuteVideo():this.type===ft.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.unmuteVideo(),this.stutter&&this.stutter.resetVideo()),this.playing&&this.player&&this.player.unmuteVideo(),e.remote_id=Object(je.a)(this.getUserId())),this.reportAction("videoEnable",0,null,null,e),!0}catch(e){return this.reportAction("videoEnable",ht(e),null,null,{stream:this.getActionStreamId()},pt(e)),!1}return!1}))}muteAudio(){return mt(this,void 0,void 0,(function*(){if(this.hasAudio())try{const e={stream:this.getActionStreamId(),type:0};return this.type===ft.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.muteAudio():c(this.webrtcType)&&this.stream.muteAudio():this.type===ft.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.muteAudio(),this.stutter&&this.stutter.resetAudio()),this.playing&&this.player&&this.player.muteAudio(),e.remote_id=Object(je.a)(this.getUserId())),this.reportAction("audioDisable",0,null,null,e),!0}catch(e){return this.reportAction("audioDisable",ht(e),null,null,{stream:this.getActionStreamId()},pt(e)),!1}return!1}))}unmuteAudio(){return mt(this,void 0,void 0,(function*(){if(this.hasAudio())try{const e={stream:this.getActionStreamId(),type:0};return this.type===ft.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.unmuteAudio():c(this.webrtcType)&&this.stream.unmuteAudio():this.type===ft.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.unmuteAudio(),this.stutter&&this.stutter.resetAudio()),this.playing&&this.player&&this.player.unmuteAudio(),e.remote_id=Object(je.a)(this.getUserId())),this.reportAction("audioEnable",0,null,null,e),!0}catch(e){return this.reportAction("audioEnable",ht(e),null,null,{stream:this.getActionStreamId()},pt(e)),!1}return!1}))}play(e,t){return mt(this,void 0,void 0,(function*(){if(t=Object.assign({fit:"contain",muted:!1,audio:!0,video:!0},t||{}),!this.stream)throw new R(1002,"没有流可以播放");if(!e)throw new R(1002,"videoId 值非法");if(this.playing)this.log(`${this.sid} stream is already playing, userId: ${this.uid}`,pe.WARN,"stream");else{if(o.i(e)){const t="#"+e;if(!(e=document.querySelector(t)))return void this.log(`${this.sid} stream cannot play because of cannot found the container, videoId: ${t}, userId: ${this.uid}`,pe.ERROR,"stream")}this.player&&this.player.destroy(),this.player=new fe(e,t,this.logger),this.playing=!0;try{yield this.player.play(this)}catch(e){throw this.log(`${this.sid} stream play error, userId: ${this.uid}, error: ${dt(e)}`,pe.ERROR,"stream"),e}this.log(`${this.sid} stream play, userId: ${this.uid}, options: ${JSON.stringify(t)}`,pe.INFO,"stream")}}))}replay(){return mt(this,void 0,void 0,(function*(){if(!this.stream)throw new R(1002,"没有流可以播放");this.playing&&this.player?yield this.player.replay(this):this.log(`${this.sid} stream is not playing, userId: ${this.uid}`,pe.WARN,"stream")}))}resume(){return mt(this,void 0,void 0,(function*(){if(this.player){try{yield this.player.resume(),this.playing=!0}catch(e){throw e}this.log(`${this.sid} stream resume, userId: ${this.uid}`,pe.DEBUG,"stream")}this.soundMeter&&this.soundMeter.resume()}))}stop(){this.player&&(this.player.destroy(),this.player=null,this.log(`${this.sid} stream stop, userId: ${this.uid}`,pe.DEBUG,"stream")),this.playing=!1}close(){this.stop(),this.stream&&(this.removeHandleEvents(),this.removeTrackEvents(),a(this.webrtcType)?this.stream.destroy():c(this.webrtcType)&&this.stream.close(),this.log(`${this.sid} stream close, userId: ${this.uid}`,pe.DEBUG,"stream")),this.emitter&&(this.client=null,this.stutter&&(this.stutter.destroy(),this.stutter=null),this.reportCollector&&(this.reportCollector.destroy(),this.reportCollector=null),this.fire(he),this.emitter.off(),this.emitter=null),this.soundMeter&&(this.soundMeter.destroy(),this.soundMeter=null),this.audioLevelTimer&&(this.audioLevelTimer.destroy(),this.audioLevelTimer=null),this.debounceReplay=null,this.audioTrackEventHandler=null,this.videoTrackEventHandler=null,this.destroyed=!0}destroy(){this.close()}getAudioLevel(){return this.stream?this.stream.getAudioLevel()||(this.soundMeter?this.soundMeter.getVolume():0):0}fire(e,t){this.emitter&&this.emitter.fire(e,t?[t]:void 0)}on(e,t){return this.emitter&&this.emitter.on(e,{fn:t,ctx:this}),this}one(e,t){return this.emitter&&this.emitter.on(e,{fn:t,ctx:this,max:1}),this}has(e,t){return!!this.emitter&&this.emitter.has(e,t)}off(e,t){return this.emitter&&this.emitter.off(e,t),this}getAudioDeviceId(){return this.audioDeviceId}getAudioVolume(){return this.audioVolume}getVideoFrame(){if(this.hasVideo()&&this.player&&this.playing)return this.player.getVideoFrame();throw new R(1002,"流没有 videoTrack 或者没有播放")}getMSIP(){return a(this.webrtcType)&&this.stream&&this.stream.getMsmsIP()||""}setICEStartTS(e){this.iceStartTS=e}getMediaNodeIp(){return this.stream&&a(this.webrtcType)?this.stream.getSelectedMsmsIP():""}addTrackEvents(){this.addAudioTrackEvents(),this.addVideoTrackEvents()}removeTrackEvents(){this.removeAudioTrackEvents(),this.removeVideoTrackEvents()}addVideoTrackEvents(){if(this.hasVideo()){let e=this.videoTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceVideoTrack()||e),e&&Oe(this.videoTrackEventHandler,((t,r)=>{e.addEventListener(r,t)}))}}removeVideoTrackEvents(){if(this.hasVideo()){let e=this.videoTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceVideoTrack()||e),e&&Oe(this.videoTrackEventHandler,((t,r)=>{e.removeEventListener(r,t)}))}this.videoMuteTimer&&(clearTimeout(this.videoMuteTimer),this.videoMuteTimer=null)}addAudioTrackEvents(){if(this.hasAudio()){let e=this.audioTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceAudioTrack()||e),e&&Oe(this.audioTrackEventHandler,((t,r)=>{e.addEventListener(r,t)}))}}removeAudioTrackEvents(){if(this.stream&&this.stream._volumeMeter&&(this.stream._volumeMeter.disconnect(),this.stream._volumeMeter=null),this.hasAudio()){let e=this.audioTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceAudioTrack()||e),e&&Oe(this.audioTrackEventHandler,((t,r)=>{e.removeEventListener(r,t)}))}this.audioMuteTimer&&(clearTimeout(this.audioMuteTimer),this.audioMuteTimer=null)}removeHandleEvents(){this.stream&&a(this.webrtcType)&&this.stream.off()}handleEvents(){this.stream&&a(this.webrtcType)&&(this.stream.on("stream-connection-error",(()=>{this.stream&&this.fire(oe);const e={stream:this.getActionStreamId(),flow:this.type===ft.STREAM_TYPE_LOCAL?1:2,msip:this.stream.getMsmsIP()||""};this.type===ft.STREAM_TYPE_LOCAL?e.user=Object(je.a)(this.getUserId()):e.remote_id=Object(je.a)(this.getUserId()),this.reportAction("mediaChannelDisconnect",4003,null,null,e)})),this.stream.on("stream-disconnected",(()=>{this.stream&&this.fire(oe);const e={stream:this.getActionStreamId(),flow:this.type===ft.STREAM_TYPE_LOCAL?1:2,msip:this.stream.getMsmsIP()||""};this.type===ft.STREAM_TYPE_LOCAL?e.user=Object(je.a)(this.getUserId()):e.remote_id=Object(je.a)(this.getUserId()),this.reportAction("mediaChannelDisconnect",4003,null,null,e)})),this.stream.on("stream-connection-success",(()=>{this.stream&&this.fire(ae);const e={stream:this.getActionStreamId(),flow:this.type===ft.STREAM_TYPE_LOCAL?1:2,msip:this.stream.getMsmsIP()||""};this.type===ft.STREAM_TYPE_LOCAL?e.user=Object(je.a)(this.getUserId()):e.remote_id=Object(je.a)(this.getUserId()),this.reportAction("mediaChannelConnect",0,this.iceStartTS,Q(),e)})),this.stream.on("stream-reconnecting",(()=>{this.stream&&this.fire(ce)})),this.stream.on("stream-replaced",(e=>{this.stream&&this.player&&this.player.replay(this,!!e.video,!!e.audio),e.video&&this.fire(ne,{type:"video",track:e.video}),e.audio&&this.fire(ne,{type:"audio",track:e.audio})})),this.stream.on("stream-update",(e=>{(null==e?void 0:e.trackUpdate)&&(this.stream&&this.player&&this.player.replay(this),this.audioTrack&&this.fire(ne,{type:"audio",track:this.audioTrack}),this.videoTrack&&this.fire(ne,{type:"video",track:this.videoTrack}))})),this.stream.on("video-adaptation-changed",(e=>{this.isLocalStream()&&this.reportAction("videoAdaptationChanged",0,null,null,{stream:this.getActionStreamId(),adaptation:JSON.stringify(e)})})),this.stream.on("stream-audio-level",(e=>{this.audioLevelTimer&&(this.audioLevelTimer.destroy(),this.audioLevelTimer=null),this.soundMeter&&(this.soundMeter.destroy(),this.soundMeter=null),this.fire(le,e)})),this.stream.on("stream-video-adaption",(e=>{this.fire("stream-video-adaption",{videoEnable:e.video_enable}),e.video_enable?this.reportAction("videoDisable",0,null,null,{stream:this.getActionStreamId(),remote_id:Object(je.a)(this.getUserId()),type:1}):this.reportAction("videoEnable",0,null,null,{stream:this.getActionStreamId(),remote_id:Object(je.a)(this.getUserId()),type:1})})),this.stream.on("video-layer-status-changed",(e=>{if(this.fire("video-layer-status-changed",e),o.f(e.layer))e.enable?this.reportAction("videoLayerEnable",0,null,null,{stream:this.getActionStreamId(),type:2,layer:e.layer}):this.reportAction("videoLayerDisable",0,null,null,{stream:this.getActionStreamId(),type:2,layer:e.layer});else for(let t=0;t<this.stream.getLayerCount();t++)e.enable?this.reportAction("videoLayerEnable",0,null,null,{stream:this.getActionStreamId(),type:2,layer:t}):this.reportAction("videoLayerDisable",0,null,null,{stream:this.getActionStreamId(),type:2,layer:t});this.muteDetect&&this.muteDetect.resetVideo()})),this.stream.on("stream-sei-message",(e=>{this.fire("stream-sei-message",{data:e.data,payloadType:e.payload})})))}reportAction(e,t,r,i,n,s){this.collection&&this.collection.action(e,t,r,i,n,s)}getAudioRTPStats(e){if(!e)return{};for(let t=0;t<e.rtps.length;t++)if("audio"===e.rtps[t].kind)return e.rtps[t]}getVideoRTPStats(e,t=!0){var r,i,n,s,o,a,c,u;if(e){let d;for(let l=0;l<e.rtps.length;l++)if("video"===e.rtps[l].kind){if(t&&"r1"===e.rtps[l].rid)return e.rtps[l];if(!t&&"r0"===e.rtps[l].rid)return e.rtps[l];d?t?((null===(r=d.resolution)||void 0===r?void 0:r.width)<(null===(i=e.rtps[l].resolution)||void 0===i?void 0:i.width)||(null===(n=d.resolution)||void 0===n?void 0:n.height)<(null===(s=e.rtps[l].resolution)||void 0===s?void 0:s.height))&&(d=e.rtps[l]):((null===(o=d.resolution)||void 0===o?void 0:o.width)>(null===(a=e.rtps[l].resolution)||void 0===a?void 0:a.width)||(null===(c=d.resolution)||void 0===c?void 0:c.height)>(null===(u=e.rtps[l].resolution)||void 0===u?void 0:u.height))&&(d=e.rtps[l]):d=e.rtps[l]}return d}return{}}log(e,t,r){this.logger?this.logger.log(e,t,r):pe.log(t,e,r)}getActionStreamId(){return c(this.webrtcType)?Object(je.a)(this.getUserId()):this.getStreamId()}setAudioEncodeDataPipe(e){a(this.webrtcType)&&this.stream&&this.stream.setAudioEncodeDataPipe(e)}setVideoEncodeDataPipe(e){a(this.webrtcType)&&this.stream&&this.stream.setVideoEncodeDataPipe(e)}requestKeyFrame(){a(this.webrtcType)&&this.stream&&this.stream.requestKeyFrame()}}ft.STREAM_TYPE_LOCAL=0,ft.STREAM_TYPE_REMOTE=1;class gt{constructor(e,t=6){this.win=t,this.threshold=e,this.packetLoss=new ge(this.win)}add(e,t){this.packetLoss.addData(e,t)}judge(){return this.packetLoss.getPacketLossRate()>this.threshold}getAvgLoss(){return this.packetLoss.getPacketLossRate()}destroy(){this.win=this.threshold=this.packetLoss=null}reset(){this.packetLoss&&this.packetLoss.reset()}}class vt{constructor(e,t=6){this.win=t,this.threshold=e,this.queue=[],this.maxFrameRate=0}updateMaxFrameRate(e){e>this.maxFrameRate&&(this.maxFrameRate=e)}add(e){this.updateMaxFrameRate(e),this.queue.push(e),this.queue.length>this.win&&this.queue.shift()}judge(){if(!this.queue.length)return!1;const e=this.queue.reduce(((e,t)=>e+t),0);return this.maxFrameRate<=5?e/this.queue.length<=Math.floor(.4*this.maxFrameRate):e/this.queue.length<=this.threshold}destroy(){this.win=this.threshold=this.queue=null}reset(){this.queue.length=0}}class yt{constructor(e,t=6){this.win=t,this.threshold=e,this.delayInvalidCount=0}add(e){-1===e||e>this.threshold?this.delayInvalidCount++:this.delayInvalidCount=0}judge(){return this.delayInvalidCount>this.win}destroy(){this.win=this.threshold=this.delayInvalidCount=null}reset(){this.delayInvalidCount=0}}class _t{constructor(e=1,t=48e3){this.channel=e,this.sampleRate=t,this.concealedSamples=0,this.totalSamplesReceived=0,this.concealmentEvents=0,this.totalAudioEnergy=0,this.totalSamplesDuration=0,this.silentConcealedSamples=0,this.samplesFactor=0,this.eventFactor=0,this.level=0,this.slientPercent=0}add(e,t,r,i,n,s){t!==this.totalSamplesReceived?this.samplesFactor=(e-this.concealedSamples)/(t-this.totalSamplesReceived):this.samplesFactor=0,r!==this.concealmentEvents?(this.eventFactor=(e-this.concealedSamples)/(r-this.concealmentEvents),this.eventFactor=1e3*this.eventFactor/(this.channel*this.sampleRate)):this.eventFactor=0,n!==this.totalSamplesDuration?this.level=(i-this.totalAudioEnergy)/(n-this.totalSamplesDuration):this.level=0,e&&(this.slientPercent=s/e),this.concealedSamples=e,this.totalSamplesReceived=t,this.concealmentEvents=r,this.totalAudioEnergy=i,this.totalSamplesDuration=n,this.silentConcealedSamples=s}judge(){return this.eventFactor>80||this.samplesFactor>.2}reset(){this.concealedSamples=0,this.totalSamplesReceived=0,this.concealmentEvents=0,this.totalAudioEnergy=0,this.totalSamplesDuration=0,this.silentConcealedSamples=0,this.samplesFactor=0,this.eventFactor=0,this.level=0,this.slientPercent=0}}class bt{constructor(e,t,r={}){this.threshold=e,this.isPush=t,this.options=r,this.audioPacketLossStutter=new gt(t?this.threshold.audio_loss_rate_threshold:this.threshold.down_audio_loss_rate_threshold),this.videoPacketLossStutter=new gt(t?this.threshold.video_loss_rate_threshold:this.threshold.down_video_loss_rate_threshold),this.frameRateStutter=new vt(this.threshold.send_frame_rate_threshold),this.audioframeDelayStutter=new yt(this.threshold.audio_frame_render_interval_threshold),this.videoframeDelayStutter=new yt(this.threshold.video_frame_render_interval_threshold),ut.chrome&&!this.isPush&&(this.audioStutter=new _t(this.options.channel,this.options.sampleRate))}addFrameRate(e){this.frameRateStutter.add(e)}addAudioLoss(e,t){this.audioPacketLossStutter.add(e,t)}addVideoLoss(e,t){this.videoPacketLossStutter.add(e,t)}addAudioFrameDelay(e){this.audioframeDelayStutter.add(e)}addVideoFrameDelay(e){this.videoframeDelayStutter.add(e)}addAudioStutterData(e,t,r,i,n,s){this.audioStutter&&this.audioStutter.add(e,t,r,i,n,s)}judgeAudioStutter(){return!this.isPush&&this.audioStutter?this.audioStutter.judge():this.audioPacketLossStutter.judge()||this.audioframeDelayStutter.judge()}judegVideoStutter(){return this.videoPacketLossStutter.judge()||this.frameRateStutter.judge()&&this.videoPacketLossStutter.getAvgLoss()>10||this.videoframeDelayStutter.judge()}destroy(){this.audioPacketLossStutter.destroy(),this.videoPacketLossStutter.destroy(),this.frameRateStutter.destroy(),this.audioframeDelayStutter.destroy(),this.videoframeDelayStutter.destroy(),this.audioPacketLossStutter=this.videoPacketLossStutter=this.audioframeDelayStutter=this.videoframeDelayStutter=this.frameRateStutter=this.audioStutter=null}resetAudio(){this.audioStutter&&this.audioStutter.reset(),this.audioPacketLossStutter&&this.audioPacketLossStutter.reset(),this.audioframeDelayStutter&&this.audioframeDelayStutter.reset()}resetVideo(){this.videoPacketLossStutter&&this.videoPacketLossStutter.reset(),this.frameRateStutter&&this.frameRateStutter.reset(),this.videoPacketLossStutter&&this.videoPacketLossStutter.reset(),this.videoframeDelayStutter&&this.videoframeDelayStutter.reset()}}var St=r(6),It=r.n(St);const Et=pe.DEBUG,Tt=pe.INFO,Rt=pe.WARN,wt=pe.ERROR,At=void 0!==typeof console?console:null,kt=/BRTC/.test(Object(je.a)((function(){})))?Et:Rt;function Ct(e,t,r,i){let n=[];return o.f(b())&&n.push(b()),r&&n.push(r),i&&n.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function Mt(){if(window){const e=window.BRTC_LOG_LEVEL;if(e>=Et&&e<=6)return e}return kt}const Ot={[Et]:function(e,t,r,i=[]){At&&Mt()<=Et&&(i.unshift(Ct("DEBUG",e,t,r)),At.log.apply(At.log,i))},[Tt]:function(e,t,r,i=[]){At&&Mt()<=Tt&&(i.unshift(Ct("INFO",e,t,r)),At.log.apply(At.log,i))},[Rt]:function(e,t,r,i=[]){At&&Mt()<=Rt&&(i.unshift(Ct("WARN",e,t,r)),At.warn.apply(At.warn,i))},[wt]:function(e,t,r,i=[]){At&&Mt()<=wt&&(i.unshift(Ct("ERROR",e,t,r)),At.error.apply(At.error,i))}};var Pt,Lt;!function(e){e.CAMERA="camera",e.SCREEN="screen",e.FILE="file"}(Pt||(Pt={})),function(e){e[e.PACKETS_LOST_SCALE=1]="PACKETS_LOST_SCALE"}(Lt||(Lt={}));var xt=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class Dt extends ft{constructor(e,t,r,i){super(ft.STREAM_TYPE_REMOTE,i,e,t,r),this.audioVolume=1,a(this.webrtcType)&&this.handleEvents(),this.subscribed=!1,this.unpublished=!1,this.stream&&a(this.webrtcType)&&(this.videoOn=this.stream.getVideoEnable(),this.audioOn=this.stream.getAudioEnable()),this.log(`${this.sid} RemoteStream create, userId: ${this.uid}`,Et,"stream")}setStream(e,t){super.setStream(e,t),this.stream&&a(this.webrtcType)&&(this.videoOn=this.stream.getVideoEnable(),this.audioOn=this.stream.getAudioEnable())}isSubscribed(){return this.subscribed}isUnpublish(){return this.unpublished}getType(){var e;if(!this.stream)return"main";if(a(this.webrtcType)){const e=this.stream.getType();return e===Pt.SCREEN||e===Pt.FILE?"assist":"main"}return c(this.webrtcType)?"auxiliary"===(null===(e=this.stream)||void 0===e?void 0:e.getType())?"assist":"main":void 0}setAudioOutput(e){return xt(this,void 0,void 0,(function*(){this.audioDeviceId=e,this.stream&&this.playing&&this.player&&(yield this.player.setSinkId(this.audioDeviceId),this.reportAction("deviceChange",0,null,null,{type:"speaker",device_id:e,stream:this.getActionStreamId()}),this.log(`${this.sid} RemoteStream setAudioOutput, userId: ${this.uid}, deviceId: ${e}`,Tt,"stream"))}))}setAudioVolume(e){this.audioVolume=e,this.playing&&this.player&&(this.player.setVolume(this.audioVolume),this.log(`${this.sid} RemoteStream setAudioVolume, userId: ${this.uid}, volume: ${e}`,Tt,"stream"))}play(e,t={}){const r=Object.create(null,{play:{get:()=>super.play}});return xt(this,void 0,void 0,(function*(){this.audioDeviceId&&this.setAudioOutput(this.audioDeviceId);try{yield r.play.call(this,e,t),t.muted||this.setAudioVolume(this.audioVolume)}catch(e){throw e}}))}getStats(){var e;return xt(this,void 0,void 0,(function*(){const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(t){if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),r=this.getVideoRTPStats(e);return{videoBytesReceived:De(r,"statistics.bytesReceived",0),videoPacketsReceived:De(r,"statistics.packetsReceived",0),videoPacketsLost:De(r,"statistics.packetsLost",0),videoNacksCount:De(r,"statistics.googNacksSent",0),audioBytesReceived:De(t,"statistics.bytesReceived",0),audioPacketsReceived:De(t,"statistics.packetsReceived",0),audioPacketsLost:De(t,"statistics.packetsLost",0),audioNacksCount:De(t,"statistics.googNacksSent",0),width:De(r,"resolution.width",0),height:De(r,"resolution.height",0),rtt:De(e,"transport.0.rtt",0),framesDecoded:De(r,"statistics.framesDecoded",0)}}if(c(this.webrtcType)){let e=yield t.getRemoteVideoStats();if(!this.client)throw new R(1010,"已被取消订阅");let r=yield t.getRemoteAudioStats();if(!this.client)throw new R(1010,"已被取消订阅");let i=yield t.getTransportStats(),n=e[this.uid],s=r[this.uid];return{videoBytesReceived:De(n,"bytesReceived",0),videoPacketsReceived:De(n,"packetsReceived",0),videoPacketsLost:De(n,"packetsLost",0),videoNacksCount:0,audioBytesReceived:De(s,"bytesReceived",0),audioPacketsReceived:De(s,"packetsReceived",0),audioPacketsLost:De(s,"packetsLost",0),audioNacksCount:0,width:De(n,"frameWidth",0),height:De(n,"frameHeight",0),rtt:De(i,"rtt",0),framesDecoded:De(n,"framesDecoded",0)}}}return{}}))}getReportStats(e){var t,r,i;return xt(this,void 0,void 0,(function*(){if(!this.stutter){const i=this.getAudioTrack(),n={};if(i&&o.d(i.getSettings)){const e=i.getSettings();n.channels=null!==(t=e.channelCount)&&void 0!==t?t:1,n.sampleRate=null!==(r=e.sampleRate)&&void 0!==r?r:48e3}this.stutter=new bt(e,!1,n)}let n={bandwidth:{upload:0,download:0},bitrate:{audio:{upload:0,download:0},video:{upload:0,download:0}},packetLoss:{audio:{upload:0,download:0},video:{upload:0,download:0}},resolution:{width:0,height:0},framerate:0,audioLevel:0,transport:[{ip:"",type:"",localIp:"",localCandidateType:"",remoteCandidateType:"",networkType:"",rtt:0}],quality:{audio:{jitter:0,interruptionCount:0,interruptionDuration:0},video:{jitter:0,interruptionCount:0,interruptionDuration:0}},statistics:{audio:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0},video:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0,framesEncoded:0,framesDecoded:0,framesSent:0},bweforvideo:{googAvailableReceiveBandwidth:0,googAvailableSendBandwidth:0,googRetransmitBitrate:0,googTransmitBitrate:0,googTargetEncBitrate:0},ice:{packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0}},cpu:{appCpu:0,systemCpu:0}};const s=null===(i=this.client)||void 0===i?void 0:i.getClient();if(s)if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),r=this.getVideoRTPStats(e);n.audioLevel=this.getAudioLevel(),e.bandwidth&&(n.bandwidth=e.bandwidth),e.bitrate&&(n.bitrate=e.bitrate),e.packetLoss&&(n.packetLoss=e.packetLoss),e.transport&&(n.transport=e.transport),e.bweforvideo&&(n.statistics.bweforvideo={googAvailableReceiveBandwidth:e.bweforvideo.availableReceiveBandwidth,googAvailableSendBandwidth:e.bweforvideo.availableSendBandwidth,googRetransmitBitrate:e.bweforvideo.retransmitBitrate,googTransmitBitrate:e.bweforvideo.transmitBitrate,googTargetEncBitrate:e.bweforvideo.targetEncBitrate}),e.ice&&(n.statistics.ice=e.ice),t&&(n.quality.audio=t.qa,n.statistics.audio=t.statistics),r&&(n.quality.video=r.qa,n.statistics.video=r.statistics,n.resolution=r.resolution,n.framerate=r.framerate),this.stutter.addFrameRate(De(n,"framerate",0)),this.stutter.addVideoLoss(De(n,"statistics.video.packetsReceived",0)+De(n,"statistics.video.packetsLost",0),De(n,"statistics.video.packetsLost",0)),this.stutter.addAudioLoss(De(n,"statistics.audio.packetsReceived",0)+De(n,"statistics.audio.packetsLost",0),De(n,"statistics.audio.packetsLost",0)),this.stutter.addAudioFrameDelay(De(n,"quality.audio.frameDelay",0)),this.stutter.addVideoFrameDelay(De(n,"quality.video.frameDelay",0)),this.stutter.addAudioStutterData(De(n,"statistics.audio.concealedSamples",0),De(n,"statistics.audio.totalSamplesReceived",0),De(n,"statistics.audio.concealmentEvents",0),De(n,"statistics.audio.totalAudioEnergy",0),De(n,"statistics.audio.totalSamplesDuration",0),De(n,"statistics.audio.silentConcealedSamples",0)),!this.firstAudioShow&&De(n,"statistics.audio.packetsReceived",0)>0&&(this.reportAction("firstAudioPlay",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(J()-this.subscribeTS,0),remote_id:Object(je.a)(this.getUserId()),has_player:!!this.player,speaker_device_id:this.audioDeviceId||"default"}),this.firstAudioShow=!0),!this.firstVideoShow&&De(n,"statistics.video.framesDecoded",0)>0&&(this.reportAction("firstVideoShow",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(J()-this.subscribeTS,0),remote_id:Object(je.a)(this.getUserId()),has_player:!!this.player}),this.firstVideoShow=!0)}else{let e=yield s.getRemoteVideoStats();if(!this.client)throw new R(1010,"已被取消订阅");let t=yield s.getRemoteAudioStats();if(!this.client)throw new R(1010,"已被取消订阅");let r=yield s.getTransportStats(),i=e[this.uid],o=t[this.uid];this.reportCollector.addData(De(o,"bytesReceived",0),De(i,"bytesReceived",0),De(o,"packetsReceived",0),De(o,"packetsLost",0),De(i,"packetsReceived",0),De(i,"packetsLost",0),De(i,"framesDecoded",0)),n.bitrate.audio.download=this.reportCollector.getAudioBitrate(),n.bitrate.video.download=this.reportCollector.getVideoBitrate(),n.packetLoss.audio.download=this.reportCollector.getAudioPacketLoss(),n.packetLoss.video.download=this.reportCollector.getVideoPacketLoss(),n.framerate=this.reportCollector.getFrameRate(),n.resolution.width=De(i,"frameWidth",0),n.resolution.height=De(i,"frameHeight",0),n.transport[0].rtt=Math.round(De(r,"rtt",0)),n.audioLevel=this.getAudioLevel(),n.bandwidth.download=this.reportCollector.getAudioBitrate()+this.reportCollector.getVideoBitrate(),n.statistics.audio.bytesReceived=De(o,"bytesReceived",0),n.statistics.audio.packetsReceived=De(o,"packetsReceived",0),n.statistics.audio.packetsLost=De(o,"packetsLost",0),n.statistics.video.bytesReceived=De(i,"bytesReceived",0),n.statistics.video.packetsReceived=De(i,"packetsReceived",0),n.statistics.video.framesDecoded=De(i,"framesDecoded",0),n.statistics.video.packetsLost=De(i,"packetsLost",0),this.stutter.addFrameRate(n.framerate),this.stutter.addVideoLoss(n.statistics.video.packetsReceived+n.statistics.video.packetsLost,n.statistics.video.packetsLost),this.stutter.addAudioLoss(n.statistics.audio.packetsReceived+n.statistics.audio.packetsLost,n.statistics.audio.packetsLost),!this.firstAudioShow&&De(o,"packetsReceived",0)>0&&(this.reportAction("firstAudioPlay",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(J()-this.subscribeTS,0),remote_id:Object(je.a)(this.getUserId()),has_player:!!this.player,speaker_device_id:this.audioDeviceId||"default"}),this.firstAudioShow=!0),!this.firstVideoShow&&De(i,"framesDecoded",0)>0&&(this.reportAction("firstVideoShow",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(J()-this.subscribeTS,0),remote_id:Object(je.a)(this.getUserId()),has_player:!!this.player}),this.firstVideoShow=!0)}return n}))}getExtraReport(){if(this.stutter){const e=this.stutter.judgeAudioStutter(),t=this.stutter.judegVideoStutter();let r=Pt.CAMERA;return a(this.webrtcType)&&this.stream&&(r=this.stream.getSourceType()),{event:e||t?1:0,audio_stutter:this.getAudioOn()&&this.getAudioSubscribed()&&e?1:0,video_stutter:this.getVideoOn()&&this.getVideoSubscribed()&&t?1:0,downLink:0,streamSource:r}}}onMediaUpdate(e){if(!this.stream||!a(this.webrtcType))return;const t=this.stream.getVideoEnable()&&this.stream.hasVideo(),r=this.stream.getAudioEnable()&&this.stream.hasAudio(),i=t!==this.videoOn,n=r!==this.audioOn;if(this.videoOn=t,this.audioOn=r,i){const r=t?P:O;this.log(`client event ${r}, userId: ${e.getUserId()}, streamUserId: ${this.uid}`,Tt,"client"),e.fire(r,{stream:this})}if(n){const t=r?x:L;this.log(`client event ${t}, userId: ${e.getUserId()}, streamUserId: ${this.uid}`,Tt,"client"),e.fire(t,{stream:this})}}onSubscribe(){this.firstVideoShow=!1,this.firstAudioShow=!1,this.subscribeTS=J(),this.addTrackEvents(),this.subscribed=!0,this.player&&this.playing&&this.replay(),this.setVolumeMeter()}onUnsubscribe(){this.removeTrackEvents(),this.subscribed=!1}setUnpublish(){this.unpublished=!0}hasSmallStream(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(a(this.webrtcType))return this.stream.getSimulcast()>1;if(c(this.webrtcType)&&t){let e=!1;return ye(t.getRemoteMutedState(),((t,r)=>{const i=this.getUserId();if(o.f(i)&&q(t.userId,!1)===i||o.i(i)&&q(t.userId,!0)===i)return e=!!t.hasSmall,!1})),e}return!1}getVideoAdaptionEnable(){return!(!a(this.webrtcType)||!this.stream)&&this.stream.getVideoAdaptionEnable()}destroy(){this.subscribed=!1,super.destroy()}getVideoSubscribed(){var e,t;return a(this.webrtcType)?this.stream.getVideoSubscribed():null!==(t=null===(e=this.subscribeOptions)||void 0===e?void 0:e.videoEnable)&&void 0!==t&&t}getAudioSubscribed(){var e,t;return a(this.webrtcType)?this.stream.getAudioSubscribed():null!==(t=null===(e=this.subscribeOptions)||void 0===e?void 0:e.audioEnable)&&void 0!==t&&t}}var Nt=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const $t=[w,A,k,C,M,O,P,L,x,D,N,$,U,B,V,F,j,W],Ut={1:{[w]:"stream-added",[A]:"stream-removed",[k]:"stream-updated",[C]:"",[M]:"stream-subscribed",[O]:"mute-video",[P]:"unmute-video",[L]:"mute-audio",[x]:"unmute-audio",[N]:"peer-join",[$]:"peer-leave",[U]:"client-banned",[D]:"error"},0:{[w]:"stream-added",[A]:"stream-removed",[k]:"",[C]:"",[M]:"",[O]:"",[P]:"",[L]:"",[x]:"",[D]:"error",[N]:"peer-joined",[$]:"peer-leaved",[U]:"peer-rejoined",[B]:"evicted",[V]:"token-will-expire",[F]:"token-expire",[j]:"room-closed",[W]:"sync-room-completed"}},Bt={0:{[w]:function(e){let t=new Dt(q(e.getUserId(),this.useStringUserId),this.webrtcType,e,e.getStreamId());return t.setLogger(this.logger),this.addRemoteStream(t),this.logger.info(`${w}, userId: ${this.userId}, streamUserId: ${t.getUserId()}, streamId: ${t.getStreamId()}`,"client"),{stream:t}},[A]:function(e){let t=this.removeRemoteStream(e.getUserId(),e.getStreamId());return t||(t=new Dt(q(e.getUserId(),this.useStringUserId),this.webrtcType,e,e.getStreamId()),t.setLogger(this.logger)),t.setUnpublish(),this.logger.info(`${A}, userId: ${this.userId}, streamUserId: ${t.getUserId()}, streamId: ${t.getStreamId()}`,"client"),{stream:t}},[D]:function(e){var t;let r=4002;"error-room"===e&&(r=4001);const i=this.getActiveProxy();return this.reportAction("signalChannelDisconnect",r,0,0,{proxy:{url:i?i.activeUrl||i.url||i.dcurl:"",location:i&&null!==(t=i.location)&&void 0!==t?t:""}}),this.logger.error(`${D}, userId: ${this.userId}, error: ${dt(r)}`,"client"),new R(r)},[N]:function(e){const t=q(e,this.useStringUserId);return this.logger.info(`${N}, userId: ${this.userId}, peerId: ${t}`,"client"),{userId:t}},[$]:function(e){let t=this.removeRemoteStream(e);t&&t.setUnpublish();const r=q(e,this.useStringUserId);return this.logger.info(`${$}, userId: ${this.userId}, peerId: ${r}`,"client"),{userId:r}},[U]:function(e){return Nt(this,void 0,void 0,(function*(){this.logger.error(`${U}, userId: ${this.userId}`,"client");try{yield this.leave("rejoined")}catch(e){}return(null==e?void 0:e.userId)&&(e.userId=tt(e.userId)),e}))},[B]:function(e){return Nt(this,void 0,void 0,(function*(){try{yield this.leave("evicted")}catch(e){}return this.logger.error(`${B}, userId: ${this.userId}`,"client"),new R(4009)}))},[V]:function(e){return this.logger.warn(`${V}, userId: ${this.userId}`,"client"),{seconds:e.seconds}},[F]:function(e){return Nt(this,void 0,void 0,(function*(){try{yield this.leave("token_expire")}catch(e){}return this.logger.error(`${F}, userId: ${this.userId}`,"client"),new R(5002)}))},[j]:function(e){return Nt(this,void 0,void 0,(function*(){try{yield this.leave("room_close")}catch(e){}return this.logger.error(`${j}, userId: ${this.userId}`,"client"),new R(5003)}))}},1:{[w]:function(e){let t=new Dt(q(e.stream.getUserId(),this.useStringUserId),this.webrtcType,e.stream,e.stream.getId());return t.setLogger(this.logger),this.addRemoteStream(t),this.logger.info(`${w}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),this.isJoinning?(t._brtcAddEventPadding_=!0,!1):{stream:t}},[A]:function(e){let t=this.removeRemoteStream(e.stream.getUserId(),e.stream.getId());return t||(t=new Dt(q(e.stream.getUserId(),this.useStringUserId),this.webrtcType,e.stream),t.setLogger(this.logger)),t.setUnpublish(),this.logger.info(`${A}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t}},[k]:function(e){let t=this.getRemoteStream(e.stream.getUserId(),e.stream.getId());return!!t&&(t.setStream(this.webrtcType,e.stream),this.logger.info(`${k}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[M]:function(e){let t=this.getRemoteStream(e.stream.getUserId(),e.stream.getId());return t.setStream(this.webrtcType,e.stream),this.logger.info(`${M}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t}},[O]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${O}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[P]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${P}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[L]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${L}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[x]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${x}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[D]:function(e){let t=9e3;return/DTLS Transport connection timeout/i.test(e)&&(t=4002),this.reportAction("signalChannelDisconnect",t),this.logger.error(`${D}, userId: ${this.userId}, error: ${dt(t)}`,"client"),new R(t,null,e)},[N]:function(e){const t=q(e.userId,this.useStringUserId);return this.logger.info(`${N}, userId: ${this.userId}, peerId: ${t}`,"client"),{userId:t}},[$]:function(e){let t=this.removeRemoteStream(e.userId);t&&t.setUnpublish();const r=q(e.userId,this.useStringUserId);return this.logger.info(`${$}, userId: ${this.userId}, peerId: ${r}`,"client"),{userId:r}},[U]:function(e){return Nt(this,void 0,void 0,(function*(){let t=(e.message||"").indexOf("account admin")>-1?"evicted":"rejoined";try{yield this.leave(t)}catch(e){}return this.logger.error(`${U}, userId: ${this.userId}, reason: ${t}`,"client"),"rejoined"===t?new R(4005):[B,new R(4009)]}))}}};class Vt{constructor(e=0){this.code=65535&e}enableAuth(){return!!(1&this.code)}canPushAudio(){return!!(2&this.code)}canPushVideo(){return!!(4&this.code)}canUseWhiteboard(){return!!(8&this.code)}}const Ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function jt(e){let t,r,i,n,s,o,a,c="",u=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");e.length%4;)e+="=";for(;u<e.length;)n=Ft.indexOf(e.charAt(u++)),s=Ft.indexOf(e.charAt(u++)),o=Ft.indexOf(e.charAt(u++)),a=Ft.indexOf(e.charAt(u++)),t=n<<2|s>>4,r=(15&s)<<4|o>>2,i=(3&o)<<6|a,c+=String.fromCharCode(t),64!==o&&(c+=String.fromCharCode(r)),64!==a&&(c+=String.fromCharCode(i));return function(e){let t="",r=0,i=0,n=0,s=0;for(;r<e.length;)i=e.charCodeAt(r),i<128?(t+=String.fromCharCode(i),r++):i>191&&i<224?(n=e.charCodeAt(r+1),t+=String.fromCharCode((31&i)<<6|63&n),r+=2):(n=e.charCodeAt(r+1),s=e.charCodeAt(r+2),t+=String.fromCharCode((15&i)<<12|(63&n)<<6|63&s),r+=3);return t}(c)}const Wt={"120p":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:200},"240p":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1e3},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4680},"4k":{width:3840,height:2160,frameRate:30,bitrate:9e3}},qt={1:{standard:{sampleRate:48e3,channelCount:1,bitrate:40},high:{sampleRate:48e3,channelCount:1,bitrate:192},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},0:{standard:{sampleRate:48e3,channelCount:1,bitrate:40},high:{sampleRate:48e3,channelCount:1,bitrate:128},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}}},Gt={"480p":{width:640,height:480,frameRate:5,bitrate:500},"480p_2":{width:640,height:480,frameRate:30,bitrate:600},"720p":{width:1280,height:720,frameRate:5,bitrate:800},"720p_2":{width:1280,height:720,frameRate:30,bitrate:2e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1200},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:3e3}},Ht={19200:{max:300,min:30},76800:{max:500,min:50},307200:{max:1e3,min:100},921600:{max:3e3,min:300},2073600:{max:5e3,min:500},3686400:{max:8e3,min:1e3},8294400:{max:15e3,min:3e3}},zt={bitrate:70,height:120,width:160},Jt=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices):navigator&&navigator.getUserMedia?navigator.getUserMedia.bind(window.navigator):null;var Yt=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function Kt(e){return Yt(this,void 0,void 0,(function*(){if(!Jt)throw new Error("not support");!o.c(e.video)&&o.i(e.video.deviceId)&&(e.video.deviceId={exact:e.video.deviceId}),!o.c(e.audio)&&o.i(e.audio.deviceId)&&(e.audio.deviceId={exact:e.audio.deviceId});const t=yield Jt(e);return o.c(e.video)?t:o.h(e.video)?function(e,t,r,i){if(!o.f(t)||!o.f(r)||0===t||0===r)return e;const n=e.getVideoTracks()[0];if(!n||"function"!=typeof n.getCapabilities)return e;const s=n.getConstraints();return s.frameRate=i||s.frameRate,n.applyConstraints(s),e}(t,e.video.width,e.video.height,e.fps):t}))}const Qt=navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia?navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices):navigator&&navigator.getDisplayMedia?navigator.getDisplayMedia.bind(window.navigator):null;var Xt=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function Zt(e){return Xt(this,void 0,void 0,(function*(){if(!Qt)throw new Error("not support");const t={video:{frameRate:e.fps},audio:!!e.audio,selfBrowserSurface:"include"};return o.f(e.width)&&o.f(e.height)&&(t.video.width={ideal:e.width},t.video.height={ideal:e.height}),yield Qt(t)}))}var er=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const tr=[["iphone",/iphone os ([\d_.]+)/],["ipad",/ipad; cpu os ([\d_.]+)/],["itouch",/itouch; cpu os ([\d_.]+)/],["android",/android ([\d_.]+)/],["wp",/windows phone ([\d_.]+)/],["windows",/windows nt ([\d_.]+)/],["linux",/linux/],["mac",/mac os x ([\d_.]+)/]],rr={iphone:1,ipad:1,itouch:1},ir=function(e){let t,r;return ye(tr,(i=>{let n=i[1].exec(e);if(n)return t=i[0],r=n[1],r&&(r=r.replace(/_/g,".")),!1})),{name:t||"",version:r||""}}((navigator.userAgent||"").toLowerCase());ir.name&&(ir[ir.name]=!0,rr[ir.name]&&(ir.ios=!0));var nr=ir;function sr(){if(nr.android||nr.ios)return!1;if(ut.chrome){if(ut.checkVersion(ut.majorVersion,"72",!0))return!0;if(ut.checkVersion(ut.majorVersion,"55"))return!1}else{if(ut.safari&&ut.checkVersion(ut.majorVersion,"13",!0))return!0;if(ut.firefox&&ut.checkVersion(ut.majorVersion,"66",!0))return!0;if(ut.edge&&ut.checkVersion(ut.majorVersion,"11"))return!0;if(ut.newEdge)return!0}return Object(o.d)(Qt)}var or=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function ar(e){return or(this,void 0,void 0,(function*(){if(e.screen){if(ut.chrome){if(ut.checkVersion(ut.majorVersion,"72",!0))return yield Zt(e);if(ut.checkVersion(ut.majorVersion,"55"))return yield function(e){return er(this,void 0,void 0,(function*(){throw new Error("not support")}))}()}else if(ut.edge&&ut.checkVersion(ut.majorVersion,"11")||ut.newEdge||ut.safari&&ut.checkVersion(ut.majorVersion,"13",!0)||sr())return yield Zt(e);throw new Error("not support")}return yield Kt(e)}))}function cr(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){let r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))}class ur{constructor(e={}){this.TRACE=pe.TRACE,this.DEBUG=pe.DEBUG,this.INFO=pe.INFO,this.WARN=pe.WARN,this.ERROR=pe.ERROR,this.FATAL=pe.FATAL,this.options=Le({uploadLevel:pe.getUploadLevel()},e),this.canUpload=!0}enableUploadLog(){this.canUpload=!0}disableUploadLog(){this.canUpload=!1}setUploadLevel(e){this.options.uploadLevel=e}fatal(e,t,r=!1){(pe.FATAL>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&pe.canUploadLog()&&this.options.onUpload(e,pe.FATAL,t),pe.fatal(e,t)}error(e,t,r=!1){pe.error(e,t),(pe.ERROR>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&pe.canUploadLog()&&this.options.onUpload(e,pe.ERROR,t)}warn(e,t,r=!1){pe.warn(e,t),(pe.WARN>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&pe.canUploadLog()&&this.options.onUpload(e,pe.WARN,t)}info(e,t,r=!1){pe.info(e,t),(pe.INFO>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&pe.canUploadLog()&&this.options.onUpload(e,pe.INFO,t)}call(e,t,r=!1){pe.call(e,t),(pe.INFO>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&pe.canUploadLog()&&this.options.onUpload(e,pe.INFO,t)}debug(e,t,r=!1,i=!1){pe.debug(e,t),i||(pe.DEBUG>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&pe.canUploadLog()&&this.options.onUpload(e,pe.DEBUG,t)}trace(e,t,r=!1){pe.trace(e,t),pe.TRACE>=this.options.uploadLevel&&r&&this.canUpload&&this.options.onUpload&&pe.canUploadLog()&&this.options.onUpload(e,pe.TRACE,t)}log(e,t,r,i=!1){switch(t){case pe.TRACE:this.trace(e,r,i);break;case pe.DEBUG:this.debug(e,r,i);break;case pe.INFO:this.info(e,r,i);break;case pe.WARN:this.warn(e,r,i);break;case pe.ERROR:this.error(e,r,i);break;case pe.FATAL:this.fatal(e,r,i);break;default:this.debug(e,r,i)}}}const dr="notify";var lr=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const hr={maxRetry:0,requestTimeout:5e3,responseTimeout:5e3,duplicatesTimeout:5e3};function pr(...e){let t="";for(let r=0;r<e.length;r++)e[r]&&(t+=e[r]);return t}class mr extends $e{constructor(e,t,r={},i){super(!1),this.packer=e,this.options=Le({},hr,r),this.requestID=0,this.notifyId=0,this.reqMap=new Map,this.resMap=new Map,this.reqKeyMap=new Map,this.logger=i||new ur,this.onmessageHandler=e=>{this.onmessage(e)},t&&this.handlTransport(t)}handlTransport(e){this.transport&&(Object(o.d)(this.transport.removeListener)?this.transport.removeListener(this.onmessageHandler):Object(o.d)(this.transport.removeEventListener)?this.transport.removeEventListener(this.onmessageHandler):Object(o.d)(this.transport.onmessage)&&(this.transport.onmessage=null)),e&&(Object(o.d)(e.addListener)?e.addListener("onmessage",this.onmessageHandler):Object(o.d)(e.addEventListener)?e.addEventListener("onmessage",this.onmessageHandler):e.onmessage=this.onmessageHandler,this.transport=e)}send(e){Object(o.d)(this.transport.send)?this.transport.send(e):Object(o.d)(this.transport.write)?this.transport.write(e):Object(o.d)(this.transport.postMessage)&&this.transport.postMessage(e)}request(e,t={},r={}){return lr(this,void 0,void 0,(function*(){if(!this.transport)throw new Error(`request ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);return new Promise(((i,n)=>{var s,o;if(r.key&&this.reqKeyMap.has(r.key)){const i=this.reqKeyMap.get(r.key);clearTimeout(i.timer),this.logger.warn(`request ${e}, params: ${JSON.stringify(t)} canceled because there is call new request whoes key is same as before`),i.reject(new Error("request canceled because there is call new request which key is same as before")),this.reqMap.delete(pr(i.id)),this.reqKeyMap.delete(r.key)}const a=this.requestID++;r.dest&&(t.dest=r.dest),this.options.peerId&&(t.from=this.options.peerId);const c={resolve:i,reject:n,id:a,dest:r.dest,timer:null,retryCount:0,maxRetry:null!==(s=r.maxRetry)&&void 0!==s?s:this.options.maxRetry,errorRetry:null!==(o=r.errorRetry)&&void 0!==o&&o,method:e,params:t,message:this.packer.pack({method:e,params:t},a),timestamp:J(),key:r.key,timeout:r.timeout,timeoutFn:()=>{c.retryCount>=c.maxRetry?(this.reqMap.delete(pr(c.id)),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key),this.logger.error(`request ${e}, params: ${JSON.stringify(t)} timeout`),n(new Error("request timeout"))):(c.retryCount++,c.timer=setTimeout(c.timeoutFn,r.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${e}, params: ${JSON.stringify(t)}, count: ${c.retryCount}`),this.send(c.message))},needRetry:r.needRetry};c.timer=setTimeout(c.timeoutFn,r.timeout||this.options.requestTimeout*(c.retryCount+1)),this.reqMap.set(pr(c.id),c),c.key&&this.reqKeyMap.set(c.key,c),this.send(c.message)}))}))}reply(e,t,r){var i;this.options.peerId&&(t&&(t.from=this.options.peerId),r&&(r.from=this.options.peerId));const n=this.packer.pack({result:t,error:r},e.id),s={id:e.id,message:n,timer:null},o=pr(e.id,null===(i=e.params)||void 0===i?void 0:i.from);this.options.responseTimeout&&(s.timer=setTimeout((()=>{this.resMap.delete(o)}),this.options.responseTimeout),this.resMap.set(o,s)),this.send(s.message)}notify(e,t={},r){if(!this.transport)throw new Error(`notify ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);const i=this.notifyId++;r&&(t.dest=r),this.options.peerId&&(t.from=this.options.peerId),this.send(this.packer.pack({method:e,params:t,seq:i}))}onmessage(e){var t;if(this.transport)if(Ce(e))if(Object(o.i)(e)){let r;try{r=this.packer.unpack(e)}catch(t){return void this.logger.error(`unpack message error, message: ${e}, error: ${dt(t)}`,"RpcBuilder")}const i=r.id,n=r.method,s=null!==(t=r.params)&&void 0!==t?t:{},o=s.dest;if(s.dest,Ce(this.options.peerId)&&this.options.peerId===o)return void this.logger.warn("ignored the message which send from me, message: "+e);if(Ce(i))if(n){const t=this.resMap.get(pr(i,o));t?(this.logger.warn(`request: ${e} has replyed in ${this.options.responseTimeout}ms, send same again`),this.send(t.message)):this.fire("request",[r])}else{const t=r.error,o=r.result;if((null==t?void 0:t.dest)!==this.options.peerId||(null==o?void 0:o.dest)!==this.options.peerId)return void this.logger.warn("ignored the message which not sent for me, message: "+e);const a=pr(i),c=this.reqMap.get(a);if(c){if(clearTimeout(c.timer),t){if(this.logger.error(`[request error] request: ${c.message}, response: ${e}, consume: ${J()-c.timestamp}`),c.errorRetry&&c.retryCount<c.maxRetry&&(!c.needRetry||c.needRetry(t)))return c.retryCount++,c.timer=setTimeout(c.timeoutFn,c.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${c.method}, params: ${JSON.stringify(c.params)}, count: ${c.retryCount}`),c.id=this.requestID++,c.message=this.packer.pack({method:n,params:s},c.id),void this.send(c.message);c.reject(t)}else this.logger.debug(`[request success] method: ${c.method}, id: ${c.id}, consume: ${J()-c.timestamp}`),c.resolve(o);this.reqMap.delete(a),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key)}else this.logger.warn("no request for the response: "+e)}else this.fire(dr,[n,s,r.seq])}else this.fire("binary",[e]);else this.logger.warn("message is not defined","RpcBuilder")}destroy(){this.off(),this.handlTransport(),this.reqMap&&(this.reqMap.forEach((e=>{clearTimeout(e.timer),e.reject("transport closed")})),this.reqMap.clear(),this.reqMap=null),this.reqKeyMap&&(this.reqKeyMap.clear(),this.reqKeyMap=null),this.resMap&&(this.resMap.forEach((e=>{clearTimeout(e.timer)})),this.resMap.clear(),this.resMap=null),this.packer=null,this.transport=null}getPacker(){return this.packer}getTransport(){return this.transport}setTransport(e){this.handlTransport(e)}resetRequest(){this.reqMap&&this.reqMap.forEach((e=>{clearTimeout(e.timer),e.timer=setTimeout(e.timeoutFn,e.timeout||this.options.requestTimeout*(e.retryCount+1)),this.send(e.message)}))}}class fr extends class{constructor(){}}{constructor(){super()}pack(e,t){const r={jsonrpc:"2.0"};if(e.method)r.method=e.method,e.params&&(r.params=e.params),Ce(t)&&(r.id=t),e.seq&&(r.seq=e.seq);else if(Ce(t)){if(e.error){if(e.result)throw new TypeError("Both result and error are defined");r.error=e.error}else{if(!e.result)throw new TypeError("No result or error is defined");r.result=e.result}r.id=t}return JSON.stringify(r)}unpack(e){const t=JSON.parse(e);if("2.0"!==t.jsonrpc)throw new TypeError(`Invalid JsonRPC version ${t.jsonrpc}: ${e}`);if(!Ce(t.method)){if(!Ce(t.id))throw new TypeError("Invalid message: "+e);const r=Ce(t.error),i=Ce(t.result);if(i&&r)throw new TypeError("Both result and error are defined: "+e);if(!i&&!r)throw new TypeError("No result or error is defined: "+e)}return t}}const gr={videoAdaption:"stream-video-adaption",consumerBitrate:"consumer-bitrate-changed",changeVideoStatus:"video-layer-status-changed"},vr=new Map;function yr(e){return e&&o.i(e)}function _r(e){o.a(e)?ye(e,(e=>{yr(e)&&vr.set(e,J())})):yr(e)&&vr.set(e,J()),function(){const e=vr.keys();for(let t of e)J()-vr.get(t)>=6e5&&vr.delete(t)}()}function br(e){return vr.has(e)&&J()-vr.get(e)<6e5}function Sr(){vr.clear()}function Ir(){const e=vr.keys(),t=[];for(let r of e)J()-vr.get(r)<6e5?t.push(r):vr.delete(r);return t}function Er(e){vr.delete(e)}var Tr,Rr=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class wr extends $e{constructor(e,t){var r,i,n,s,o,a;super(!0),this.type=e.type,this.sourceType=e.sourceType,this.client=e.client,this.userId=e.userId,this.streamId=null!==(r=e.streamId)&&void 0!==r?r:cr(),this.videoOn=null!==(i=e.videoOn)&&void 0!==i&&i,this.audioOn=null!==(n=e.audioOn)&&void 0!==n&&n,this.videoEnable=null!==(s=e.videoEnable)&&void 0!==s&&s,this.audioEnable=null!==(o=e.audioEnable)&&void 0!==o&&o,this.msmsIPs=[],this.audioLevelInterval=null!==(a=e.audioLevelInterval)&&void 0!==a?a:1e3,this.iceconnectionstatechangeTimer=null,this.dtlsconnectionstatechangeTimer=null,this.dtlsConnectionTimeout=null,this.destroyed=!1,this.isMsSupportDatachannel=!0,null==this.type&&(/^screen-/.test(this.streamId)?this.type=Pt.SCREEN:this.type=Pt.CAMERA),null==this.sourceType&&(this.sourceType=Pt.CAMERA),this.logger=t||new ur,this.packer=new fr}getUserId(){return this.userId}getStreamId(){return this.streamId}hasVideo(){return this.videoOn}hasAudio(){return this.audioOn}getVideoEnable(){return this.videoEnable}getAudioEnable(){return this.audioEnable}getMsmsIP(){return this.msmsIPs.join(" ")||""}update(e){let t=!1;return this.audioOn&&e.audio_enable&&!this.audioEnable&&this.collector&&this.collector.restartAudioLevelTimer(),o.c(e.videoOn)&&this.videoOn!==e.videoOn&&(this.videoOn=e.videoOn,t=!0),o.c(e.audioOn)&&this.audioOn!==e.audioOn&&(this.audioOn=e.audioOn,t=!0),o.c(e.video_enable)&&this.videoEnable!==e.video_enable&&(this.videoEnable=e.video_enable,t=!0),o.c(e.audio_enable)&&this.audioEnable!==e.audio_enable&&(this.audioEnable=e.audio_enable,t=!0),t&&this.fire("stream-update"),t}getVideoTrack(){const e=this.getStream();if(e)return e.getVideoTracks()[0]}getAudioTrack(){const e=this.getStream();if(e)return e.getAudioTracks()[0]}getValueFromStats(e,t){if(this.stats)for(let r of this.stats.rtps)if(r.ssrc===e)return De(r,t)}getStats(){var e;if(this.collector){const t=this.collector.getStats();for(let r of t.rtps)"video"===r.kind&&(!this.stats&&"none"!==r.qualityLimitationReason||this.stats&&(null===(e=this.stats.rtps)||void 0===e?void 0:e.length)&&r.qualityLimitationReason!==this.getValueFromStats(r.ssrc,"qualityLimitationReason"))&&this.fire("video-adaptation-changed",[{rid:r.rid,reason:r.qualityLimitationReason}]);this.stats=t}return this.stats}startCollecting(){this.collector&&this.collector.start()}stopCollecting(){this.collector&&this.collector.stop()}getAudioLevel(){var e;return this.collector&&null!==(e=this.collector.getAudioLevel())&&void 0!==e?e:0}updateAudioLevelInterval(e){this.audioLevelInterval=e,this.collector&&this.collector.updateAudioLevelInterval(e)}handlerEvent(){if(this.iceconnectionstatechangeTimer&&(clearTimeout(this.iceconnectionstatechangeTimer),this.iceconnectionstatechangeTimer=null),this.dtlsconnectionstatechangeTimer&&(clearTimeout(this.dtlsconnectionstatechangeTimer),this.dtlsconnectionstatechangeTimer=null),this.peer.oniceconnectionstatechange=e=>{this.iceconnectionstatechangeTimer&&(clearTimeout(this.iceconnectionstatechangeTimer),this.iceconnectionstatechangeTimer=null),"disconnected"===e?(this.iceconnectionstatechangeTimer=setTimeout((()=>{this.logger.error(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice disconnected`),this.fire("stream-connection-error"),this.iceconnectionstatechangeTimer=null}),5e3),this.fire("stream-reconnecting")):"failed"===e?(this.logger.error(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice failed`),this.fire("stream-connection-error")):"connected"===e?(this.logger.info(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice connected`),this.fire("stream-connection-success")):this.logger.info(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice ${e}`)},this.peer.ondtlsstatechange=e=>{"closed"===e||"failed"===e?this.dtlsconnectionstatechangeTimer=setTimeout((()=>{this.logger.error(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} dtls ${e}`),this.fire("stream-connection-error")}),5e3):(this.logger.info(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} dtls ${e}`),"connected"===e&&(this.dtlsConnectionTimeout&&(clearTimeout(this.dtlsConnectionTimeout),this.dtlsConnectionTimeout=null),"udp"===this.getSelectedMsmsIPProtocol()&&Er(this.getSelectedMsmsIP())))},this.peer.onicecandidate=e=>{this.client&&this.client.syncIcecandidate(this,e)},this.isMsSupportDatachannel){this.rpc&&this.rpc.destroy();const e={send:e=>{this.peer.send(e)},onmessage:null};this.peer.onmessage=t=>{e.onmessage&&e.onmessage(t.data)},this.rpc=new mr(this.packer,e,{},this.logger),this.rpc.on("binary",(e=>{this.fire("binary",[e])})),this.rpc.on(dr,((e,t,r)=>{gr[e]?("videoAdaption"===e&&(t.video_enable=!t.video_enable),this.fire(gr[e],[t])):this.fire(dr,[{method:e,params:t}])})),this.rpc.on("request",(e=>{this.fire("request",[e])}))}}requestKeyFrame(){this.hasVideo()&&this.getVideoEnable()&&this.request("requestKeyFrame")}request(e,t={}){return Rr(this,void 0,void 0,(function*(){if(this.rpc)return this.rpc.request(e,t);this.logger.error(`no rpc channel to request, method: ${e}, params: ${JSON.stringify(t)}`)}))}reply(e,t,r){if(this.rpc)return this.rpc.reply(e,t,r);this.logger.error(`no rpc channel to reply, request: ${JSON.stringify(e)}, result: ${JSON.stringify(t)}, error: ${JSON.stringify(r)}`)}notify(e,t={}){if(this.rpc)return this.rpc.notify(e,t);this.logger.error(`no rpc channel to notify, method: ${e}, params: ${JSON.stringify(t)}`)}close(){this.rpc&&this.rpc.destroy(),this.peer&&(this.peer.destroy(),this.peer=null),this.collector&&(this.stopCollecting(),this.collector.destroy(),this.collector=null),this.iceconnectionstatechangeTimer&&(clearTimeout(this.iceconnectionstatechangeTimer),this.iceconnectionstatechangeTimer=null),this.dtlsconnectionstatechangeTimer&&(clearTimeout(this.dtlsconnectionstatechangeTimer),this.dtlsconnectionstatechangeTimer=null),this.dtlsConnectionTimeout&&(clearTimeout(this.dtlsConnectionTimeout),this.dtlsConnectionTimeout=null)}setLogger(e){this.logger=e}getType(){return this.type}isConnecting(){return!!this.peer}getSourceType(){return this.sourceType}isDestroyed(){return this.destroyed}setAudioEncodeDataPipe(e){this.onAudioEncodeDataPipe=e,this.encodedDataProcesser&&this.encodedDataProcesser.setAudioEncodeDataPipe(e)}setVideoEncodeDataPipe(e){this.onVideoEncodeDataPipe=e,this.encodedDataProcesser&&this.encodedDataProcesser.setVideoEncodeDataPipe(e)}hasEncodedDataProcesser(e={}){return(e.enableSEI&&"h264"===this.options.vcodec.toLocaleLowerCase()||this.onVideoEncodeDataPipe||this.onAudioEncodeDataPipe)&&(null===RTCRtpSender||void 0===RTCRtpSender?void 0:RTCRtpSender.prototype.createEncodedStreams)}getSelectedMsmsIP(){return this.peer?this.peer.getRemoteIP()||this.collector.getRemoteIP()||this.msmsIPs[0]:""}getSelectedMsmsIPProtocol(){return this.peer&&(this.peer.getPairProtocol()||this.collector.getCurrentPairProtocol())||"udp"}isConnected(){var e;return null===(e=this.peer)||void 0===e?void 0:e.isConnected()}startDtlsConnectionTimeout(){ut.firefox||(this.dtlsConnectionTimeout&&clearTimeout(this.dtlsConnectionTimeout),this.dtlsConnectionTimeout=setTimeout((()=>{this.peer&&"connected"===this.peer.iceConnectionState&&"connected"!==this.peer.dtlsConnectionState&&"udp"===this.getSelectedMsmsIPProtocol()&&(_r(this.getSelectedMsmsIP()),this.fire("stream-connection-error"))}),8e3))}}!function(e){e[e.RECEIVE_BANDWIDTH=0]="RECEIVE_BANDWIDTH",e[e.SEND_BANDWIDTH=1]="SEND_BANDWIDTH",e[e.REMOTE_ADDRESS=2]="REMOTE_ADDRESS",e[e.TRANSPORT_TYPE=3]="TRANSPORT_TYPE",e[e.LOCAL_ADDRESS=4]="LOCAL_ADDRESS",e[e.ACTIVE_CONNECTION=5]="ACTIVE_CONNECTION",e[e.SSRC=6]="SSRC",e[e.PACKETS_RECEIVED=7]="PACKETS_RECEIVED",e[e.PACKETS_SENT=8]="PACKETS_SENT",e[e.PACKETS_LOST=9]="PACKETS_LOST",e[e.BYTES_RECEIVED=10]="BYTES_RECEIVED",e[e.BYTES_SENT=11]="BYTES_SENT",e[e.FRAME_HEIGHT_RECEIVED=12]="FRAME_HEIGHT_RECEIVED",e[e.FRAME_WIDTH_RECEIVED=13]="FRAME_WIDTH_RECEIVED",e[e.FRAME_HEIGHT_SENT=14]="FRAME_HEIGHT_SENT",e[e.FRAME_WIDTH_SENT=15]="FRAME_WIDTH_SENT",e[e.FRAME_RATE_RECEIVED=16]="FRAME_RATE_RECEIVED",e[e.FRAME_RATE_SENT=17]="FRAME_RATE_SENT",e[e.AUDIO_INPUT_LEVEL=18]="AUDIO_INPUT_LEVEL",e[e.AUDIO_OUTPUT_LEVEL=19]="AUDIO_OUTPUT_LEVEL",e[e.AUDIO_LEVEL=20]="AUDIO_LEVEL",e[e.CURRENT_ROUND_TRIP_TIME=21]="CURRENT_ROUND_TRIP_TIME",e[e.REMOTE_CANDIDATE_TYPE=22]="REMOTE_CANDIDATE_TYPE",e[e.LOCAL_CANDIDATE_TYPE=23]="LOCAL_CANDIDATE_TYPE",e[e.IP=24]="IP",e[e.PORT=25]="PORT",e[e.PROTOCOL=26]="PROTOCOL",e[e.JITTER_BUFFER_DELAY=27]="JITTER_BUFFER_DELAY",e[e.JITTER_BUFFER_EMITTED_COUNT=28]="JITTER_BUFFER_EMITTED_COUNT",e[e.MEDIA_TYPE=29]="MEDIA_TYPE",e[e.JITTER_BUFFER_MS=30]="JITTER_BUFFER_MS",e[e.INTER_FRAME_DELAY_MAX=31]="INTER_FRAME_DELAY_MAX",e[e.CURRENT_DELAY_MS=32]="CURRENT_DELAY_MS",e[e.AVAILABLE_RECEIVE_BANDWIDTH=33]="AVAILABLE_RECEIVE_BANDWIDTH",e[e.AVAILABLE_SEND_BANDWIDTH=34]="AVAILABLE_SEND_BANDWIDTH",e[e.RETRANSMIT_BITRATE=35]="RETRANSMIT_BITRATE",e[e.TRANSMIT_BITRATE=36]="TRANSMIT_BITRATE",e[e.TARGET_ENC_BITRATE=37]="TARGET_ENC_BITRATE",e[e.FRAME_RATE_INPUT=38]="FRAME_RATE_INPUT",e[e.ENCODE_USAGE_PERCENT=39]="ENCODE_USAGE_PERCENT",e[e.RENDER_DELAY_MS=40]="RENDER_DELAY_MS",e[e.TARGET_DELAY_MS=41]="TARGET_DELAY_MS",e[e.FRAME_RATE_OUTPUT=42]="FRAME_RATE_OUTPUT",e[e.RID=43]="RID",e[e.FRAMERATE_MEAN=44]="FRAMERATE_MEAN",e[e.AVAILABLE_INCOMING_BITRATE=45]="AVAILABLE_INCOMING_BITRATE",e[e.AVAILABLE_OUTGOING_BITRATE=46]="AVAILABLE_OUTGOING_BITRATE",e[e.ROUND_TRIP_TIME=47]="ROUND_TRIP_TIME",e[e.JITTER=48]="JITTER",e[e.PLI_COUNT=49]="PLI_COUNT",e[e.FIR_COUNT=50]="FIR_COUNT",e[e.NACK_COUNT=51]="NACK_COUNT",e[e.TIMESTAMP=52]="TIMESTAMP",e[e.FRAME_DECODED=53]="FRAME_DECODED",e[e.FRAME_ENCODED=54]="FRAME_ENCODED",e[e.FRAME_PER_SECOND=55]="FRAME_PER_SECOND",e[e.FRAME_SENT=56]="FRAME_SENT",e[e.FRAME_RECEIVED=57]="FRAME_RECEIVED",e[e.FRAME_WIDTH=58]="FRAME_WIDTH",e[e.FRAME_HEIGHT=59]="FRAME_HEIGHT",e[e.HUGE_FRAMES_SENT=60]="HUGE_FRAMES_SENT",e[e.ACCELERATE_RATE=61]="ACCELERATE_RATE",e[e.DECODING_PLC=62]="DECODING_PLC",e[e.DECODING_PLCCNG=63]="DECODING_PLCCNG",e[e.CONCEALED_SAMPLES=64]="CONCEALED_SAMPLES",e[e.TOTAL_SAMPLES_RECEIVED=65]="TOTAL_SAMPLES_RECEIVED",e[e.CONCEALMENT_EVENTS=66]="CONCEALMENT_EVENTS",e[e.TOTAL_AUDIO_ENERGY=67]="TOTAL_AUDIO_ENERGY",e[e.TOTAL_SAMPLES_DURATION=68]="TOTAL_SAMPLES_DURATION",e[e.SILENT_CONCEALED_SAMPLES=69]="SILENT_CONCEALED_SAMPLES",e[e.INSERTED_SAMPLES_FOR_DECELERATION=70]="INSERTED_SAMPLES_FOR_DECELERATION",e[e.REMOVED_SAMPLES_FOR_ACCELERATION=71]="REMOVED_SAMPLES_FOR_ACCELERATION",e[e.QUALITY_LIMITATION_REASON=72]="QUALITY_LIMITATION_REASON",e[e.QUALITY_LIMITATION_DURATIONS=73]="QUALITY_LIMITATION_DURATIONS",e[e.REQUESTS_SENT=74]="REQUESTS_SENT",e[e.RESPONSES_RECEIVED=75]="RESPONSES_RECEIVED"}(Tr||(Tr={}));const Ar={[Tr.RECEIVE_BANDWIDTH]:"googAvailableReceiveBandwidth",[Tr.SEND_BANDWIDTH]:"googAvailableSendBandwidth",[Tr.REMOTE_ADDRESS]:"googRemoteAddress",[Tr.TRANSPORT_TYPE]:"googTransportType",[Tr.LOCAL_ADDRESS]:"googLocalAddress",[Tr.ACTIVE_CONNECTION]:"googActiveConnection",[Tr.SSRC]:"ssrc",[Tr.PACKETS_RECEIVED]:"packetsReceived",[Tr.PACKETS_SENT]:"packetsSent",[Tr.PACKETS_LOST]:"packetsLost",[Tr.BYTES_RECEIVED]:"bytesReceived",[Tr.BYTES_SENT]:"bytesSent",[Tr.FRAME_HEIGHT_RECEIVED]:"googFrameHeightReceived",[Tr.FRAME_WIDTH_RECEIVED]:"googFrameWidthReceived",[Tr.FRAME_HEIGHT_SENT]:"googFrameHeightSent",[Tr.FRAME_WIDTH_SENT]:"googFrameWidthSent",[Tr.FRAME_RATE_RECEIVED]:"googFrameRateReceived",[Tr.FRAME_RATE_SENT]:"googFrameRateSent",[Tr.AUDIO_INPUT_LEVEL]:"audioInputLevel",[Tr.AUDIO_OUTPUT_LEVEL]:"audioOutputLevel",[Tr.AUDIO_LEVEL]:"audioLevel",[Tr.CURRENT_ROUND_TRIP_TIME]:"currentRoundTripTime",[Tr.REMOTE_CANDIDATE_TYPE]:"googRemoteCandidateType",[Tr.LOCAL_CANDIDATE_TYPE]:"googLocalCandidateType",[Tr.IP]:["address","ip"],[Tr.PORT]:"port",[Tr.PROTOCOL]:"protocol",[Tr.JITTER_BUFFER_DELAY]:"jitterBufferDelay",[Tr.JITTER_BUFFER_EMITTED_COUNT]:"jitterBufferEmittedCount",[Tr.MEDIA_TYPE]:"mediaType",[Tr.JITTER_BUFFER_MS]:"googJitterBufferMs",[Tr.INTER_FRAME_DELAY_MAX]:"googInterframeDelayMax",[Tr.CURRENT_DELAY_MS]:"googCurrentDelayMs",[Tr.AVAILABLE_RECEIVE_BANDWIDTH]:"googAvailableReceiveBandwidth",[Tr.AVAILABLE_SEND_BANDWIDTH]:"googAvailableSendBandwidth",[Tr.RETRANSMIT_BITRATE]:"googRetransmitBitrate",[Tr.TRANSMIT_BITRATE]:"googTransmitBitrate",[Tr.TARGET_ENC_BITRATE]:"googTargetEncBitrate",[Tr.FRAME_RATE_INPUT]:"googFrameRateInput",[Tr.ENCODE_USAGE_PERCENT]:"googEncodeUsagePercent",[Tr.RENDER_DELAY_MS]:"googRenderDelayMs",[Tr.TARGET_DELAY_MS]:"googTargetDelayMs",[Tr.FRAME_RATE_OUTPUT]:"googFrameRateOutput",[Tr.RID]:"rid",[Tr.AVAILABLE_INCOMING_BITRATE]:"availableIncomingBitrate",[Tr.AVAILABLE_OUTGOING_BITRATE]:"availableOutgoingBitrate",[Tr.ROUND_TRIP_TIME]:"roundTripTime",[Tr.JITTER]:"jitter",[Tr.PLI_COUNT]:"pliCount",[Tr.FIR_COUNT]:"firCount",[Tr.NACK_COUNT]:["nackCount","googNacksReceived"],[Tr.TIMESTAMP]:"timestamp",[Tr.FRAME_DECODED]:"framesDecoded",[Tr.FRAME_ENCODED]:"framesEncoded",[Tr.FRAME_PER_SECOND]:"framesPerSecond",[Tr.FRAME_SENT]:"framesSent",[Tr.FRAME_RECEIVED]:"framesReceived",[Tr.FRAME_WIDTH]:"frameWidth",[Tr.FRAME_HEIGHT]:"frameHeight",[Tr.FRAMERATE_MEAN]:"framerateMean",[Tr.HUGE_FRAMES_SENT]:"hugeFramesSent",[Tr.ACCELERATE_RATE]:"googAccelerateRate",[Tr.DECODING_PLC]:"googDecodingPLC",[Tr.DECODING_PLCCNG]:"googDecodingPLCCNG",[Tr.CONCEALED_SAMPLES]:"concealedSamples",[Tr.TOTAL_SAMPLES_RECEIVED]:"totalSamplesReceived",[Tr.CONCEALMENT_EVENTS]:"concealmentEvents",[Tr.TOTAL_AUDIO_ENERGY]:"totalAudioEnergy",[Tr.TOTAL_SAMPLES_DURATION]:"totalSamplesDuration",[Tr.SILENT_CONCEALED_SAMPLES]:"silentConcealedSamples",[Tr.INSERTED_SAMPLES_FOR_DECELERATION]:"insertedSamplesForDeceleration",[Tr.REMOVED_SAMPLES_FOR_ACCELERATION]:"removedSamplesForAcceleration",[Tr.QUALITY_LIMITATION_REASON]:"qualityLimitationReason",[Tr.QUALITY_LIMITATION_DURATIONS]:"qualityLimitationDurations",[Tr.REQUESTS_SENT]:"requestsSent",[Tr.RESPONSES_RECEIVED]:"responsesReceived"},kr=Le(Ar,{[Tr.IP]:"address"}),Cr=Le(Ar,{[Tr.IP]:"address"}),Mr=Le(Ar,{[Tr.IP]:"address"}),Or=Le(Ar,{[Tr.IP]:"address"});var Pr={[it.FIREFOX]:kr,[it.CHROME]:Ar,[it.SAFARI]:Cr,[it.OPERA]:Mr,[it.WECHAT]:Or};const Lr=Pr[ut.name]||Pr[it.CHROME];function xr(e,t){return o.d(e.stat)?e.stat(t):e[t]}function Dr(e,t){if(e){const r=function(e){const t=Lr[e];if(t)return t;pe.warn(`The property '${e}' isn't supported!`)}(t);if(r){if(o.a(r)){for(let t=0;t<r.length;t++){const i=xr(e,r[t]);if(i)return i}return}return xr(e,r)}}return 0}function Nr(e,t){let r=Dr(e,t);return o.f(r)||(r=Number(r)),isNaN(r)?0:Math.max(0,r)}function $r(e,t,r,i=1e3){let n=Nr(e,r),s=Nr(t,r),o=Math.max(0,n-s),a=Nr(e,Tr.TIMESTAMP),c=Nr(t,Tr.TIMESTAMP);const u=Math.max(i,a-c)||i;return Math.round(8*o/u)}class Ur{constructor(e,t,r){this.id=e,this.kind=t,this.interval=r,this.stats={type:"",loss:{packetsTotal:0,packetsLost:0,packetsTotalLost:0},bitrate:{download:0,upload:0},resolution:{width:0,height:0},framerate:0,jitter:0,interruptionCount:0,interruptionDuration:0,bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,framesEncoded:0,framesSent:0,framesDecoded:0,interframeDelayMax:0,currentDelayMs:0,rtt:0,sentPacketRate:0,recvPacketRate:0,pliCount:0,firCount:0,nacksCount:0,frameRateInput:0,encodeUsagePercent:0,targetDelayMs:0,renderDelayMs:0,frameRateOutput:0,frameRateDecoded:0,frameRateEncoded:0,jitterReceived:0,rid:"",accelerateRate:0,decodingPLC:0,decodingPLCCNG:0,hugeFramesSent:0,concealedSamples:0,totalSamplesReceived:0,concealmentEvents:0,totalAudioEnergy:0,totalSamplesDuration:0,silentConcealedSamples:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0,qualityLimitationReason:"none",qualityLimitationDurations:{bandwidth:0,cpu:0,other:0,none:0}},this.supportExtra=!1,this.uploadPacketLostScale=1}getKind(){return this.kind}getId(){return this.id}processOutboundRTP(e,t){const r=Dr(e,Tr.RID);r&&(this.stats.rid=r);const i=Nr(e,Tr.PACKETS_SENT);this.stats.packetsSent=i,this.stats.packetsReceived=0;const n=Nr(t,Tr.PACKETS_SENT),s=Math.max(0,i-n);if(!this.supportExtra){const r=Nr(e,Tr.PACKETS_LOST),i=Nr(t,Tr.PACKETS_LOST),n=Math.max(0,r-i),o=Nr(e,Tr.NACK_COUNT),a=Nr(t,Tr.NACK_COUNT),c=Math.max(0,o-a);this.stats.loss={packetsTotal:Math.max(s-c,n,1),packetsLost:n,packetsTotalLost:r}}if(this.stats.sentPacketRate=s/this.interval*1e3,this.stats.pliCount=Nr(e,Tr.PLI_COUNT),this.stats.firCount=Nr(e,Tr.FIR_COUNT),this.stats.nacksCount=Nr(e,Tr.NACK_COUNT),this.stats.bytesSent=Nr(e,Tr.BYTES_SENT),this.stats.bytesReceived=0,this.stats.bitrate={download:0,upload:$r(e,t,Tr.BYTES_SENT,this.interval)},"video"===this.kind){const r=Nr(e,Tr.FRAME_ENCODED),i=Nr(t,Tr.FRAME_ENCODED);this.stats.framesEncoded=r;const n=Nr(e,Tr.FRAME_SENT);n&&(this.stats.framesSent=n),this.stats.frameRateEncoded=Math.round(Math.max(r-i,0)/this.interval*1e3),this.stats.hugeFramesSent=Nr(e,Tr.HUGE_FRAMES_SENT);const s={height:Nr(e,Tr.FRAME_HEIGHT),width:Nr(e,Tr.FRAME_WIDTH)};s.width&&s.height&&(this.stats.resolution=s);const o=Nr(e,Tr.FRAMERATE_MEAN);if(o)this.stats.framerate=Math.round(o);else{let r=Nr(e,Tr.FRAME_PER_SECOND);if(!r){let i=Nr(e,Tr.TIMESTAMP)-Nr(t,Tr.TIMESTAMP);if(i>0){const n=Nr(e,Tr.FRAME_SENT),s=Nr(e,Tr.FRAME_ENCODED);n?r=(n-Nr(t,Tr.FRAME_SENT))/i*1e3:s&&(r=(s-Nr(t,Tr.FRAME_ENCODED))/i*1e3)}}this.stats.framerate=Math.round(r||0)}this.stats.qualityLimitationReason=Dr(e,Tr.QUALITY_LIMITATION_REASON)||"none";const a=Dr(e,Tr.QUALITY_LIMITATION_DURATIONS);a&&(this.stats.qualityLimitationDurations=a)}}processInboundRTP(e,t){const r=Nr(e,Tr.PACKETS_RECEIVED);this.stats.packetsReceived=r,this.stats.packetsSent=0;const i=Nr(t,Tr.PACKETS_RECEIVED),n=Math.max(0,r-i),s=Nr(e,Tr.PACKETS_LOST),o=Nr(t,Tr.PACKETS_LOST),a=Math.max(0,s-o);if(this.stats.loss={packetsTotal:n+a,packetsLost:a,packetsTotalLost:s},this.stats.recvPacketRate=n/this.interval*1e3,this.stats.pliCount=Nr(e,Tr.PLI_COUNT),this.stats.firCount=Nr(e,Tr.FIR_COUNT),this.stats.nacksCount=Nr(e,Tr.NACK_COUNT),this.stats.bytesReceived=Nr(e,Tr.BYTES_RECEIVED),this.stats.bytesSent=0,this.stats.bitrate={upload:0,download:$r(e,t,Tr.BYTES_RECEIVED,this.interval)},"video"===this.kind){const r=Nr(e,Tr.FRAME_DECODED),i=Nr(t,Tr.FRAME_DECODED);this.stats.framesDecoded=r,this.stats.frameRateDecoded=Math.round(Math.max(r-i,0)/this.interval*1e3);const n={height:Nr(e,Tr.FRAME_HEIGHT),width:Nr(e,Tr.FRAME_WIDTH)};n.width&&n.height&&(this.stats.resolution=n);const s=Nr(e,Tr.FRAMERATE_MEAN);if(s)this.stats.framerate=Math.round(s);else{let r=Nr(e,Tr.FRAME_PER_SECOND);if(!r){let i=Nr(e,Tr.TIMESTAMP)-Nr(t,Tr.TIMESTAMP);if(i>0){const n=Nr(e,Tr.FRAME_RECEIVED),s=Nr(e,Tr.FRAME_DECODED);n?r=(n-Nr(t,Tr.FRAME_RECEIVED))/i*1e3:s&&(r=(s-Nr(t,Tr.FRAME_DECODED))/i*1e3)}}this.stats.framerate=Math.round(r||0)}}}processRemoteInboundRTP(e){this.stats.rtt=Math.floor(1e3*Nr(e,Tr.ROUND_TRIP_TIME)),"audio"===this.kind&&(this.stats.jitterReceived=Nr(e,Tr.JITTER))}processTrack(e,t){const r=Nr(e,Tr.JITTER_BUFFER_DELAY);if(r&&t){const i=-Nr(t,Tr.JITTER_BUFFER_DELAY)+r,n=-Nr(t,Tr.JITTER_BUFFER_EMITTED_COUNT)+Nr(e,Tr.JITTER_BUFFER_EMITTED_COUNT);n>0&&(this.stats.jitter=Math.round(1e3*i/n))}if("video"===this.kind){const t={height:Nr(e,Tr.FRAME_HEIGHT),width:Nr(e,Tr.FRAME_WIDTH)};t.width&&t.height&&(this.stats.resolution=t);const r=Nr(e,Tr.FRAME_SENT);r&&(this.stats.framesSent=r)}else"audio"===this.kind&&(this.stats.concealedSamples=Nr(e,Tr.CONCEALED_SAMPLES),this.stats.totalSamplesReceived=Nr(e,Tr.TOTAL_SAMPLES_RECEIVED),this.stats.concealmentEvents=Nr(e,Tr.CONCEALMENT_EVENTS),this.stats.totalAudioEnergy=Nr(e,Tr.TOTAL_AUDIO_ENERGY),this.stats.totalSamplesDuration=Nr(e,Tr.TOTAL_SAMPLES_DURATION),this.stats.silentConcealedSamples=Nr(e,Tr.SILENT_CONCEALED_SAMPLES),this.stats.insertedSamplesForDeceleration=Nr(e,Tr.INSERTED_SAMPLES_FOR_DECELERATION),this.stats.removedSamplesForAcceleration=Nr(e,Tr.REMOVED_SAMPLES_FOR_ACCELERATION))}processMediaSource(e,t){"audio"===this.kind&&(this.stats.totalAudioEnergy=Nr(e,Tr.TOTAL_AUDIO_ENERGY),this.stats.totalSamplesDuration=Nr(e,Tr.TOTAL_SAMPLES_DURATION))}processExtraOutboundRTP(e,t){const r=Nr(e,Tr.PACKETS_SENT),i=Nr(t,Tr.PACKETS_SENT),n=Math.max(0,r-i),s=Nr(e,Tr.PACKETS_LOST),o=Nr(t,Tr.PACKETS_LOST),a=Math.max(0,s-o),c=Nr(e,Tr.NACK_COUNT),u=Nr(t,Tr.NACK_COUNT),d=Math.max(0,c-u);this.stats.loss={packetsTotal:Math.max(n-d,a,1),packetsLost:a,packetsTotalLost:s},"video"===this.kind&&(this.stats.frameRateInput=Nr(e,Tr.FRAME_RATE_INPUT),this.stats.encodeUsagePercent=Nr(e,Tr.ENCODE_USAGE_PERCENT)),this.supportExtra=!0}processExtraInboundRTP(e,t){"video"===this.kind?(this.stats.interframeDelayMax=Nr(e,Tr.INTER_FRAME_DELAY_MAX),this.stats.renderDelayMs=Nr(e,Tr.RENDER_DELAY_MS),this.stats.targetDelayMs=Nr(e,Tr.TARGET_DELAY_MS),this.stats.frameRateOutput=Nr(e,Tr.FRAME_RATE_OUTPUT)):(this.stats.currentDelayMs=Nr(e,Tr.CURRENT_DELAY_MS),this.stats.accelerateRate=Nr(e,Tr.ACCELERATE_RATE),this.stats.decodingPLC=Nr(e,Tr.DECODING_PLC),this.stats.decodingPLCCNG=Nr(e,Tr.DECODING_PLCCNG)),this.supportExtra=!0}getStats(e){const t={packetsSent:this.stats.packetsSent,packetsReceived:this.stats.packetsReceived,bytesSent:this.stats.bytesSent,bytesReceived:this.stats.bytesReceived,packetsLost:this.stats.loss.packetsTotalLost,recvPacketRate:this.stats.recvPacketRate,sentPacketRate:this.stats.sentPacketRate,googRtt:this.stats.rtt};e?("video"===this.kind?(t.googEncodeUsagePercent=this.stats.encodeUsagePercent,t.googFrameRateInput=this.stats.frameRateInput,t.googNacksReceived=this.stats.nacksCount,t.googPlisReceived=this.stats.pliCount,t.googFirsReceived=this.stats.firCount,t.framesEncoded=this.stats.framesEncoded,t.framesSent=this.stats.framesSent,t.hugeFramesSent=this.stats.hugeFramesSent):(t.googJitterReceived=this.stats.jitterReceived,t.totalAudioEnergy=this.stats.totalAudioEnergy,t.totalSamplesDuration=this.stats.totalSamplesDuration,t.googNacksReceived=this.stats.nacksCount),this.stats.loss.packetsLost=Math.floor(this.stats.loss.packetsLost*this.uploadPacketLostScale),this.stats.loss.packetsTotalLost=Math.floor(this.stats.loss.packetsTotalLost*this.uploadPacketLostScale),t.packetsLost=this.stats.loss.packetsTotalLost):"video"===this.kind?(t.googInterframeDelayMax=this.stats.interframeDelayMax,t.googPlisSent=this.stats.pliCount,t.googFirsSent=this.stats.firCount,t.googFrameRateDecoded=this.stats.frameRateDecoded,t.googFrameRateOutput=this.stats.frameRateOutput,t.googNacksSent=this.stats.nacksCount,t.googJitterBufferMs=this.stats.jitter,t.googRenderDelayMs=this.stats.renderDelayMs,t.googTargetDelayMs=this.stats.targetDelayMs,t.framesDecoded=this.stats.framesDecoded):(t.googJitterBufferMs=this.stats.jitter,t.googAccelerateRate=this.stats.accelerateRate,t.googDecodingPLC=this.stats.decodingPLC,t.googDecodingPLCCNG=this.stats.decodingPLCCNG,t.googNacksSent=this.stats.nacksCount,t.concealedSamples=this.stats.concealedSamples,t.concealmentEvents=this.stats.concealmentEvents,t.totalSamplesReceived=this.stats.totalSamplesReceived,t.totalAudioEnergy=this.stats.totalAudioEnergy,t.totalSamplesDuration=this.stats.totalSamplesDuration,t.silentConcealedSamples=this.stats.silentConcealedSamples,t.insertedSamplesForDeceleration=this.stats.insertedSamplesForDeceleration,t.removedSamplesForAcceleration=this.stats.removedSamplesForAcceleration);const r={ssrc:this.id,rid:this.stats.rid,kind:this.kind,loss:this.stats.loss,statistics:t,bitrate:this.stats.bitrate,qa:{jitter:this.stats.jitter,interruptionCount:0,interruptionDuration:0,frameDelay:"video"===this.kind?this.stats.interframeDelayMax:this.stats.currentDelayMs}};return"video"===this.kind&&(r.framerate=this.stats.framerate,r.resolution=this.stats.resolution,r.qualityLimitationReason=this.stats.qualityLimitationReason,r.qualityLimitationDurations=this.stats.qualityLimitationDurations),r}setUploadPacketLostScale(e){this.uploadPacketLostScale=e}}function Br(e,t){return!t||t<=0||!e||e<=0?0:Math.min(Math.round(e/t*100),100)}var Vr=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class Fr{constructor(e,t=1e3,r=!0,i=1e3){this.pc=e,this.interval=t,this.isPush=r,this.audioLevelInterval=i,this.uploadPacketLostScale=1,this.rtpsMap=new Map,this.conferenceStats={bandwidth:{download:0,upload:0},transport:[],bitrate:{download:0,upload:0,audio:{download:0,upload:0},video:{download:0,upload:0}},packetLoss:{audio:{total:0,download:0,upload:0},video:{total:0,download:0,upload:0}}},this.bweforvideo={availableReceiveBandwidth:0,availableSendBandwidth:0,targetEncBitrate:0,transmitBitrate:0,retransmitBitrate:0},this.iceStats={packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0},this.iceDownloadBitrate=0,this.iceUploadBitrate=0,this.previousReport=null,this.audioLevel=0,this.statsTimer=new lt((()=>{this.collectStats()}),0,this.interval),this.extraTimer=new lt((()=>{this.collectExtraStats()}),this.interval,this.interval),this.audioLevelTimer=new lt((()=>{this.collectAudioLevel()}),this.interval,this.audioLevelInterval)}getKind(e){return e.kind||e.mediaType}processCandidate(e,t){let r=Nr(t,Tr.AVAILABLE_INCOMING_BITRATE),i=Nr(t,Tr.AVAILABLE_OUTGOING_BITRATE);if((r||i)&&(this.conferenceStats.bandwidth={upload:Math.max(i,0),download:Math.max(r,0)}),o.d(e.get)){let r=e.get(t.remoteCandidateId),i=e.get(t.localCandidateId);if(r&&i){let e=Dr(r,Tr.IP),n=`${e}:${Dr(r,Tr.PORT)}`,s=Dr(i,Tr.IP),o=`${s}:${Dr(i,Tr.PORT)}`,a=Dr(r,Tr.PROTOCOL);e&&(this.remoteIP=e),s&&(this.localIP=s),a&&(this.pairProtocol=a);let c=this.conferenceStats.transport.find((e=>e.ip===n&&e.type===a&&e.localIp===o));c?(c.localCandidateType=i.candidateType,c.remoteCandidateType=r.candidateType,c.networkType=i.networkType,c.rtt=Math.round(1e3*Nr(t,Tr.CURRENT_ROUND_TRIP_TIME))):this.conferenceStats.transport.push({ip:n,type:a,localIp:o,localCandidateType:i.candidateType,remoteCandidateType:r.candidateType,networkType:i.networkType,rtt:Math.round(1e3*Nr(t,Tr.CURRENT_ROUND_TRIP_TIME))})}}this.iceStats.bytesSent=Nr(t,Tr.BYTES_SENT),this.iceStats.bytesReceived=Nr(t,Tr.BYTES_RECEIVED),this.iceStats.packetsSent=Nr(t,Tr.PACKETS_SENT),this.iceStats.packetsReceived=Nr(t,Tr.PACKETS_RECEIVED),this.iceStats.requestsSent=Nr(t,Tr.REQUESTS_SENT),this.iceStats.responsesReceived=Nr(t,Tr.RESPONSES_RECEIVED),this.previousCandidateStats&&(this.iceDownloadBitrate=$r(t,this.previousCandidateStats,Tr.BYTES_RECEIVED,this.interval),this.iceUploadBitrate=$r(t,this.previousCandidateStats,Tr.BYTES_SENT,this.interval)),this.previousCandidateStats=t}processReport(e){e.forEach((t=>{if("candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state)this.processCandidate(e,t);else if(this.isPush&&"outbound-rtp"===t.type){const e=this.previousReport.get(t.id),r=Nr(t,Tr.SSRC);if(r){let i=this.rtpsMap.get(r);i||(i=new Ur(r,this.getKind(t),this.interval),this.rtpsMap.set(r,i),i.setUploadPacketLostScale(this.uploadPacketLostScale)),i.processOutboundRTP(t,e)}}else if(this.isPush||"inbound-rtp"!==t.type){if("track"===t.type){const e=this.previousReport.get(t.id);if(this.rtpsMap.forEach((r=>{r.getKind()===this.getKind(t)&&r.processTrack(t,e)})),"audio"===this.getKind(t)){const e=Dr(t,Tr.AUDIO_LEVEL);Ce(e)&&(this.audioLevel=tt(e))}}else if("remote-inbound-rtp"===t.type){const e=Nr(t,Tr.SSRC);if(e){let r=this.rtpsMap.get(e);r||(r=new Ur(e,this.getKind(t),this.interval),this.rtpsMap.set(e,r),r.setUploadPacketLostScale(this.uploadPacketLostScale)),r.processRemoteInboundRTP(t)}}else if("media-source"===t.type){if("audio"===this.getKind(t)){const e=Dr(t,Tr.AUDIO_LEVEL);Ce(e)&&(this.audioLevel=tt(e))}if(this.isPush){const e=this.previousReport.get(t.id);this.rtpsMap.forEach((r=>{r.getKind()===this.getKind(t)&&r.processMediaSource(t,e)}))}}}else{const e=this.previousReport.get(t.id),r=Nr(t,Tr.SSRC);if(r){let i=this.rtpsMap.get(r);i||(i=new Ur(r,this.getKind(t),this.interval),this.rtpsMap.set(r,i),i.setUploadPacketLostScale(this.uploadPacketLostScale)),i.processInboundRTP(t,e)}if("audio"===this.getKind(t)){const e=Dr(t,Tr.AUDIO_LEVEL);Ce(e)&&(this.audioLevel=tt(e))}}}))}processExtraStats(e){for(let t in e){if(!e.hasOwnProperty(t))continue;const r=e[t];if(!r)continue;if("VideoBwe"===r.type&&(this.bweforvideo.availableReceiveBandwidth=Nr(r,Tr.AVAILABLE_RECEIVE_BANDWIDTH),this.bweforvideo.availableSendBandwidth=Nr(r,Tr.AVAILABLE_SEND_BANDWIDTH),this.bweforvideo.retransmitBitrate=Nr(r,Tr.RETRANSMIT_BITRATE),this.bweforvideo.targetEncBitrate=Nr(r,Tr.TARGET_ENC_BITRATE),this.bweforvideo.transmitBitrate=Nr(r,Tr.TRANSMIT_BITRATE)),"ssrc"!==r.type&&"outboundrtp"!==r.type&&"inboundrtp"!==r.type&&"track"!==r.type)continue;if(r.isRemote||r.remoteSource)continue;const i=this.previousExtraReport[t];let n=Nr(r,Tr.SSRC);if("track"===r.type&&Array.isArray(r.ssrcIds)&&(n=Number(r.ssrcIds[0])),n){const e=this.rtpsMap.get(n);e&&(this.isPush?e.processExtraOutboundRTP(r,i):e.processExtraInboundRTP(r,i))}}}collectStats(){return Vr(this,void 0,void 0,(function*(){let e=yield this.pc.getStats();e&&(o.d(e.result)&&(e=e.result()),this.previousReport&&this.processReport(e),this.previousReport=e)}))}collectExtraStats(){this.pc.getStats((e=>{if(e){if(o.d(e.result)&&(e=e.result()),o.d(e.forEach)){const t=[];e.forEach((e=>{t.push(e)})),e=t}this.previousExtraReport&&this.processExtraStats(e),this.previousExtraReport=e}}),(e=>{this.extraTimer.stop()}))}collectAudioLevel(){return Vr(this,void 0,void 0,(function*(){let e=yield this.pc.getStats();if(e){if(o.d(e.result)&&(e=e.result()),o.d(e.forEach)){const t=[];e.forEach((e=>{t.push(e)})),e=t}let t=!1;e.forEach((e=>{if("track"===e.type){if("audio"===this.getKind(e)){t=!0;const r=Dr(e,Tr.AUDIO_LEVEL);Ce(r)&&(this.audioLevel=tt(r))}}else if("inbound-rtp"===e.type){if("audio"===this.getKind(e)){t=!0;const r=Dr(e,Tr.AUDIO_LEVEL);Ce(r)&&(this.audioLevel=tt(r))}}else if("media-source"===e.type&&"audio"===this.getKind(e)){t=!0;const r=Dr(e,Tr.AUDIO_LEVEL);Ce(r)&&(this.audioLevel=tt(r))}})),this.onAudioLevel&&t?this.onAudioLevel(this.audioLevel):!t&&this.audioLevelTimer&&this.audioLevelTimer.stop()}}))}start(){this.statsTimer.isStarted()||this.statsTimer.start(),ut.chrome&&(this.extraTimer.isStarted()||this.extraTimer.start(),this.audioLevelTimer&&!this.audioLevelTimer.isStarted()&&this.audioLevelInterval<1e3&&this.audioLevelTimer.start())}restartAudioLevelTimer(){this.audioLevelTimer&&!this.audioLevelTimer.isStarted()&&this.audioLevelInterval<1e3&&this.audioLevelTimer.start()}stop(){this.statsTimer&&this.statsTimer.stop(),this.extraTimer&&this.extraTimer.stop(),this.audioLevelTimer&&this.audioLevelTimer.stop()}updateAudioLevelInterval(e){this.audioLevelInterval=e,this.audioLevelTimer&&(this.audioLevelTimer.updateInterval(e),!this.audioLevelTimer.isStarted()&&e<1e3?this.audioLevelTimer.start():e>=1e3&&this.audioLevelTimer.stop())}destroy(){this.stop(),this.statsTimer&&this.statsTimer.destroy(),this.extraTimer&&this.extraTimer.destroy(),this.audioLevelTimer&&this.audioLevelTimer.destroy(),this.statsTimer=null,this.extraTimer=null,this.audioLevelTimer=null,this.pc=null,this.previousReport=null,this.previousExtraReport=null,this.rtpsMap&&this.rtpsMap.clear(),this.conferenceStats={bandwidth:{download:0,upload:0},transport:[],bitrate:{download:0,upload:0,audio:{download:0,upload:0},video:{download:0,upload:0}},packetLoss:{audio:{total:0,download:0,upload:0},video:{total:0,download:0,upload:0}}},this.bweforvideo={availableReceiveBandwidth:0,availableSendBandwidth:0,targetEncBitrate:0,transmitBitrate:0,retransmitBitrate:0}}getAudioLevel(){return this.audioLevel}getStats(){let e=0,t=0,r=0,i=0,n=0,s=0,o={audio:{download:0,upload:0},video:{download:0,upload:0}},a={audio:{download:0,upload:0},video:{download:0,upload:0}};const c=[];this.rtpsMap.forEach((u=>{const d=u.getStats(this.isPush);e+=d.bitrate.download,t+=d.bitrate.upload,"video"===d.kind?(n+=d.bitrate.download,s+=d.bitrate.upload,this.isPush?(o.video.upload+=d.loss.packetsTotal,a.video.upload+=d.loss.packetsLost):(o.video.download+=d.loss.packetsTotal,a.video.download+=d.loss.packetsLost)):(r+=d.bitrate.download,i+=d.bitrate.upload,this.isPush?(o.audio.upload+=d.loss.packetsTotal,a.audio.upload+=d.loss.packetsLost):(o.audio.download+=d.loss.packetsTotal,a.audio.download+=d.loss.packetsLost)),c.push(d)}));let u={availableSendBandwidth:this.bweforvideo.availableSendBandwidth,availableReceiveBandwidth:this.bweforvideo.availableReceiveBandwidth,retransmitBitrate:this.bweforvideo.retransmitBitrate,transmitBitrate:this.bweforvideo.transmitBitrate,targetEncBitrate:this.bweforvideo.targetEncBitrate};const d=this.conferenceStats.transport;return{bandwidth:this.conferenceStats.bandwidth,bitrate:{upload:t,download:e,audio:{upload:i,download:r},video:{upload:s,download:n},ice:{upload:this.iceUploadBitrate,download:this.iceDownloadBitrate}},packetLoss:{audio:{total:Br(a.audio.download+a.audio.upload,o.audio.download+o.audio.upload),download:Br(a.audio.download,o.audio.download),upload:Br(a.audio.upload,o.audio.upload)},video:{total:Br(a.video.download+a.video.upload,o.video.download+o.video.upload),download:Br(a.video.download,o.video.download),upload:Br(a.video.upload,o.video.upload)}},transport:d,bweforvideo:u,ice:this.iceStats,rtps:c}}getLocalIP(){return this.localIP}getRemoteIP(){return this.remoteIP}getCurrentPairProtocol(){return this.pairProtocol}setUploadPacketLostScale(e){this.uploadPacketLostScale=e,this.rtpsMap.forEach((t=>{t.setUploadPacketLostScale(e)}))}}var jr=r(11),Wr=r.n(jr),qr=r(12);const Gr=new(r.n(qr).a.Interop);var Hr,zr,Jr,Yr;!function(e){e.SEND_ONLY="sendonly",e.RECV_ONLY="recvonly",e.SEND_RECV="sendrecv",e.INACTIVE="inactive"}(Hr||(Hr={})),function(e){e.VIDEO="video",e.AUDIO="audio",e.APPLICATION="application"}(zr||(zr={})),function(e){e[e.ADD=0]="ADD",e[e.REMOVE=1]="REMOVE"}(Jr||(Jr={})),function(e){e.VIDEO_INPUT="videoinput",e.AUDIO_INPUT="audioinput",e.AUDIO_OUTPUT="audiooutput"}(Yr||(Yr={}));var Kr,Qr=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};!function(e){e[e.PLAN_B=0]="PLAN_B",e[e.UNIFIED_PLAN=1]="UNIFIED_PLAN"}(Kr||(Kr={}));class Xr extends $e{constructor(e={},t=Kr.UNIFIED_PLAN){var r;super(!0);const i=null!==(r=e.iceServers)&&void 0!==r?r:[];this.options=Le({},{iceServers:i.concat(Wr()()),sdpSemantics:"unified-plan"},e),this.sdpType=t,this.candidategatheringdone=!1,this.localIcecandidatePadding=[],this.remoteIcecandidatePadding=[],this.uuid=cr(),this.direction=Hr.SEND_RECV,this.pc=new RTCPeerConnection(this.options),this.pc.onicecandidate=e=>{let t=e.candidate;t&&(this.sdpType===Kr.PLAN_B&&(t=Gr.candidateToUnifiedPlan(t)),this._onicecandidate&&this.candidategatheringdone?this._onicecandidate(t):this.localIcecandidatePadding.push(t))},this.pc.onsignalingstatechange=e=>{if("stable"===this.signalingState)for(;this.remoteIcecandidatePadding.length;)this.pc.addIceCandidate(this.remoteIcecandidatePadding.shift())},this.pc.onnegotiationneeded=e=>{this.onnegotiationneeded&&this.onnegotiationneeded()},this.pc.oniceconnectionstatechange=e=>{this.oniceconnectionstatechange&&this.oniceconnectionstatechange(this.iceConnectionState)}}createChannel(e={}){this.channel=this.pc.createDataChannel(this.uuid,e),this.channel.onmessage=e=>{this.onmessage&&H(this.onmessage,this,[e])}}getLocalSessionDescriptor(){return this.pc.localDescription}getRemoteSessionDescriptor(){return this.pc.remoteDescription}setOffer(e){return Qr(this,void 0,void 0,(function*(){let t=new RTCSessionDescription({type:"offer",sdp:e});yield this.pc.setLocalDescription(t)}))}setAnwser(e){return Qr(this,void 0,void 0,(function*(){let t=new RTCSessionDescription({type:"answer",sdp:e});this.sdpType===Kr.PLAN_B&&(t=Gr.toPlanB(t)),yield this.pc.setRemoteDescription(t),this.handleDtlsTransport()}))}resetAnswer(e){return Qr(this,void 0,void 0,(function*(){const t=this.getLocalSessionDescriptor();yield this.pc.createOffer(),yield this.pc.setLocalDescription(t),yield this.setAnwser(e)}))}addIceCandidate(e){"stable"===this.signalingState?this.pc.addIceCandidate(e):this.remoteIcecandidatePadding.push(e)}offer(e){return Qr(this,void 0,void 0,(function*(){let t=yield this.pc.createOffer(e);return this.sdpType===Kr.PLAN_B&&(t=Gr.toPlanB(t)),t.sdp}))}answer(e){return Qr(this,void 0,void 0,(function*(){let t=new RTCSessionDescription({type:"offer",sdp:e});this.sdpType===Kr.PLAN_B&&(t=Gr.toPlanB(t)),yield this.pc.setRemoteDescription(t);let r=yield this.pc.createAnswer();return this.sdpType===Kr.PLAN_B&&(t=Gr.toPlanB(t)),this.handleDtlsTransport(),r.sdp}))}getMediaStream(){return this.stream}getSenders(){return this.pc.getSenders()}getReceivers(){return this.pc.getReceivers()}getPeerConnection(){return this.pc}send(e){this.channel?this.channel.send(e):pe.error("can not send data because of no channel in DataChannel")}destroy(e=!1){this.pc&&(e&&this.stream&&this.stream.getTracks().forEach((e=>{e.stop()})),this.pc.onicecandidate=null,this.pc.onsignalingstatechange=null,this.pc.onnegotiationneeded=null,this.pc.oniceconnectionstatechange=null,this.dtlsTransport&&(this.dtlsTransport.onstatechange=null),this.pc.close(),this.pc=null,this.stream=null,this.dtlsTransport=null)}get onicecandidate(){return this._onicecandidate}set onicecandidate(e){if(this._onicecandidate=e,!this.candidategatheringdone)for(;this.localIcecandidatePadding.length;)this._onicecandidate(this.localIcecandidatePadding.shift());this.candidategatheringdone=!0}get signalingState(){var e;return null===(e=this.pc)||void 0===e?void 0:e.signalingState}get iceConnectionState(){var e;return null===(e=this.pc)||void 0===e?void 0:e.iceConnectionState}get dtlsConnectionState(){var e;return null===(e=this.dtlsTransport)||void 0===e?void 0:e.state}isConnected(){return"connected"===this.iceConnectionState&&"connected"===this.dtlsConnectionState}getLocalIP(){var e;const t=null===(e=this.dtlsTransport)||void 0===e?void 0:e.iceTransport;if(t&&o.d(t.getSelectedCandidatePair)){const e=t.getSelectedCandidatePair().local;if(e)return e.address}}getRemoteIP(){var e;const t=null===(e=this.dtlsTransport)||void 0===e?void 0:e.iceTransport;if(t&&o.d(t.getSelectedCandidatePair)){const e=t.getSelectedCandidatePair().remote;if(e)return e.address}}getPairProtocol(){var e;const t=null===(e=this.dtlsTransport)||void 0===e?void 0:e.iceTransport;if(t&&o.d(t.getSelectedCandidatePair)){const e=t.getSelectedCandidatePair().remote;if(e)return e.protocol}}handleDtlsTransport(){ye(this.getSenders(),(e=>{if(e.transport)return this.dtlsTransport=e.transport,!1})),this.dtlsTransport||ye(this.getReceivers(),(e=>{if(e.transport)return this.dtlsTransport=e.transport,!1})),this.dtlsTransport&&(this.dtlsTransport.onstatechange=e=>{this.ondtlsstatechange&&this.ondtlsstatechange(this.dtlsTransport.state)})}}var Zr=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class ei extends Xr{constructor(e={}){super(e),this.direction=Hr.SEND_ONLY}addStream(e,t,r=49152){var i;if(this.stream=e,!this.pc.addTransceiver||ut.chrome&&!ut.checkVersion(ut.majorVersion,"72",!0))if(this.pc.addTrack){const e=this.stream.getAudioTracks()[0],t=this.stream.getVideoTracks()[0];e&&this.pc.addTrack(e,this.stream),t&&this.pc.addTrack(t,this.stream)}else this.pc.addStream(this.stream);else{const e=this.stream.getAudioTracks()[0],n=this.stream.getVideoTracks()[0];if(e&&this.pc.addTransceiver(e,{streams:[this.stream],sendEncodings:[{active:!0,maxBitrate:r}]}),n){const e=[];if(o.a(t))for(let r=0;r<t.length;r++)e.push({active:!1!==t[r].active&&!1!==t[r].serverActive,scaleResolutionDownBy:t[r].scale,maxBitrate:t[r].bitrate,maxFramerate:t[r].fps||60,rid:null!==(i=t[r].rid)&&void 0!==i?i:"r"+r});this.pc.addTransceiver(n,{direction:Hr.SEND_ONLY,streams:[this.stream],sendEncodings:e})}}}setEncodings(e){const t=this.pc.getSenders();if(!t.length)return;const r=t.find((e=>e.track.kind===zr.VIDEO));if(!r)return;if(!r.track)return;const i=r.getParameters();if(!i)return;const n=i.encodings;n.length!==e.length&&pe.warn("encodings length not match to parameters");const s=Math.min(n.length,e.length);for(let t=0;t<s;t++)o.f(e[t].scale)&&(n[t].scaleResolutionDownBy=e[t].scale),o.f(e[t].bitrate)&&(n[t].maxBitrate=e[t].bitrate),o.f(e[t].fps)&&e[t].fps&&(n[t].maxFramerate=e[t].fps),o.c(e[t].active)&&(n[t].active=!1!==e[t].active&&!1!==e[t].serverActive);i.encodings=n,r.setParameters(i)}setScalabilityMode(e){const t=this.pc.getSenders();if(!t.length)return;const r=t.find((e=>e.track.kind===zr.VIDEO));if(!r)return;if(!r.track)return;const i=r.getParameters();if(!i)return;const n=i.encodings,s=n.length;for(let t=0;t<s;t++)n[t].scalabilityMode=e.replace(/^S/,"L").replace(/T[4-9]/,"T3");i.encodings=n,r.setParameters(i)}enableVideoLayer(e,t){const r=this.pc.getSenders();if(!r.length)return;const i=r.find((e=>e.track.kind===zr.VIDEO));if(!i)return;if(!i.track)return;const n=i.getParameters();if(!n)return;const s=n.encodings,o=s.length;let a=!1;for(let r=0;r<o;r++)if(r===t){a=!0,s[r].active=e;break}a&&(n.encodings=s,i.setParameters(n))}offer(){const e=Object.create(null,{offer:{get:()=>super.offer}});return Zr(this,void 0,void 0,(function*(){return e.offer.call(this,{offerToReceiveAudio:!1,offerToReceiveVideo:!1})}))}replaceTrack(e){return Zr(this,void 0,void 0,(function*(){const t=this.getSenders().find((t=>t.track.kind===e.kind));if(t&&(yield t.replaceTrack(e)),this.stream){const t="video"===e.kind?this.stream.getVideoTracks()[0]:this.stream.getAudioTracks()[0];this.stream.removeTrack(t),this.stream.addTrack(e)}}))}}function ti(e=[],t=!0){return function(r){return o.a(r.media)&&(ye(r.media,(r=>{o.a(r.candidates)&&ye(r.candidates,(r=>{we.d(r.ip,"172")||we.d(r.ip,"192")?t&&!Ee(e,r.ip)&&e.push(r.ip):Ee(e,r.ip)||e.push(r.ip)}))})),pe.debug(`[sdpOperator msmsIP] hold: ${JSON.stringify(e)}, hasLocal: ${t}`)),r}}function ri(e,t,r,i,n){return function(s){return o.a(s.media)&&ye(s.media,(s=>{if(s.type===r){let r;if("*"===n){const t=[],r=[];ye(s.rtcpFb,(n=>{if(!Ee(t,n.payload)){const s={payload:n.payload,type:e};i&&(s.subtype=i),r.push(s),t.push(n.payload)}})),s.rtcpFb=s.rtcpFb.concat(r).sort(((e,t)=>e.payload-t.payload))}else{const a=s.payloads.split(" ");if(!a.length)return!0;if(r=tt(a[0]),o.i(n)&&ye(s.rtp,(e=>{if(e.codec.toLocaleLowerCase()===n.toLocaleLowerCase())return r=e.payload,!1})),t===Jr.ADD){let t=!1;if(ye(s.rtcpFb,(n=>{if(n.payload===r&&n.type===e&&n.subtype==i)return t=!0,!1})),!t){const t={payload:r,type:e};i&&(t.subtype=i),s.rtcpFb?s.rtcpFb.push(t):s.rtcpFb=[t]}}else t===Jr.REMOVE&&o.a(s.rtcpFb)&&(s.rtcpFb=s.rtcpFb.filter((t=>!(t.payload===r&&t.type===e&&t.subtype==i))))}pe.debug(`[sdpOperator rtcpFB] payload: ${r}, attr: ${e}, operator: ${t}, mediaType: ${s.type}, subAttr: ${i}, codec: ${n}`)}})),s}}function ii(e,t){return function(r){return o.a(r.media)&&ye(r.media,(r=>{r.type===t&&(r.bandwidth=[{type:"AS",limit:e}],pe.debug(`[sdpOperator bandwidth] bandwidth: ${e}, mediaType: ${r.type}`))})),r}}function ni(e,t){return function(r){return r.direction&&(r.direction=e),o.a(r.media)&&ye(r.media,(r=>{if("application"===r.type)return!0;t&&r.type!==t||(r.direction=e,pe.debug(`[sdpOperator direction] direction: ${e}, mediaType: ${r.type}`))})),r}}function si(e,t,r){return function(i){return o.a(i.media)&&ye(i.media,(i=>{if("application"===i.type)return!0;if(!o.f(t)){const e=new Array(256);if(o.a(i.ext)){ye(i.ext,(t=>{e[t.value]=!0}));for(let r=1;r<e.length;r++)if(!e[r]){t=r;break}}else t=1}r&&r!==i.type||(o.a(i.ext)?i.ext.push({value:t,uri:e}):i.ext=[{value:t,uri:e}],pe.debug(`[sdpOperator addExtmap] id: ${t}, uri: ${e}, mediaType: ${i.type}`))})),i}}function oi(e,t="&"){const r={};if(o.i(e)&&e.indexOf("=")>=0){let i=e.charAt(0),n="?"===i||"#"===i?1:0;n>0&&(e=e.substr(n)),ye(function(e,t){const r=[];return o.f(e)&&(e+=""),e&&o.i(e)&&ye(e.split(t),((e,t)=>{(e=e.trim())&&r.push(e)})),r}(e,t),(e=>{var t;let i=e.split("=");if(2===i.length){let e=null===(t=i[0])||void 0===t?void 0:t.trim();e&&(r[e]=decodeURIComponent(i[1]))}}))}return r}function ai(e,t="&"){const r=[];return o.e(e)&&Oe(e,((e,t)=>{r.push(t+"="+encodeURIComponent(o.h(e)?JSON.stringify(e):e))})),r.join(t)}function ci(e,t,r,i,n,s){return function(a){return o.a(a.media)&&ye(a.media,(a=>{if(a.type!==e)return!0;if(!o.f(n)&&i){let e=!1;if(ye(a.rtp,(t=>{if(t.codec.toLocaleLowerCase()===i.toLocaleLowerCase())return e=!0,!1})),!e)return!0;n=tt(a.payloads.split(" ").shift())}if(!o.f(n))return!0;let c=null;if(ye(a.fmtp,(e=>{s&&s(e)?c=e:s||e.payload!==n||(c=e)})),c){const e=oi(c.config,";");e[t]=Object(je.a)(r),c.config=ai(e,";")}else a.fmtp?a.fmtp.push({payload:n,config:`${t}=${Object(je.a)(r)}`}):a.fmtp=[{payload:n,config:`${t}=${Object(je.a)(r)}`}];pe.debug(`[sdpOperator fmptConfig] key: ${t}, value: ${r}, codec: ${i}, payload: ${n}, mediaType: ${a.type}`)})),a}}const ui=/(.*)/,di={v:[{name:"version",reg:/^(\d*)$/,format:"%s"}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name",reg:ui,format:"%s"}],i:[{name:"description",reg:ui,format:"%s"}],u:[{name:"uri",reg:ui,format:"%s"}],e:[{name:"email",reg:ui,format:"%s"}],p:[{name:"phone",reg:ui,format:"%s"}],z:[{name:"timezones",reg:ui,format:"%s"}],r:[{name:"repeats",reg:ui,format:"%s"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/,format:"%s"},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/,format:"%s"},{name:"icelite",reg:/^(ice-lite)/,format:"%s"},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){let t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/,format:"%s"},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){let t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/,format:"%s"},{name:"rtcpRsize",reg:/^(rtcp-rsize)/,format:"%s"},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/,format:"%s"},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){let t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",reg:ui,names:["value"],format:"%s"}]};function li(e,t){if(o.a(di[e]))if("a"===e){const r=di[e].pop();di[e].push(...t),di[e].push(r)}else di[e].push(...t);else di[e]=t}const hi=["v","o","s","i","u","e","p","c","b","t","r","z","a"],pi=["i","c","b","a"],mi=e=>/^([a-z])=(.*)/.test(e);function fi(e){return String(Number(e))===e?Number(e):e}function gi(e,t,r){const i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});const n=e.push?{}:i?t[e.name]:t;!function(e,t,r,i){if(i&&!r)t[i]=fi(e[1]);else for(let i=0;i<r.length;i+=1)null!=e[i+1]&&(t[r[i]]=fi(e[i+1]))}(r.match(e.reg),n,e.names,e.name),e.push&&t[e.push].push(n)}const vi=/%[sdv%]/g;function yi(e){let t=1;const r=arguments,i=r.length;return e.replace(vi,(function(e){if(t>=i)return e;const n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n)+"";case"%v":return""}}))}function _i(e,t,r){const i=[e+"="+(o.d(t.format)?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(let e=0;e<t.names.length;e+=1){const n=t.names[e];t.name?i.push(r[t.name][n]):i.push(r[t.names[e]])}else i.push(r[t.name]);return yi.apply(null,i)}function bi(e){const t={},r=[];let i=t;return e.split(/(\r\n|\r|\n)/).filter(mi).forEach((e=>{const t=e[0],n=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),i=r[r.length-1]);for(let e=0;e<(di[t]||[]).length;e+=1){const r=di[t][e];if(r.reg.test(n))return gi(r,i,n)}})),t.media=r,t}function Si(e,t={outerOrder:hi,innerOrder:pi}){null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));const r=[];return t.outerOrder.forEach((t=>{di[t].forEach((i=>{i.name in e&&null!=e[i.name]?r.push(_i(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((e=>{r.push(_i(t,i,e))}))}))})),e.media.forEach((e=>{r.push(_i("m",di.m[0],e)),t.innerOrder.forEach((t=>{di[t].forEach((i=>{i.name in e&&null!=e[i.name]?r.push(_i(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(_i(t,i,e))}))}))}))})),r.join("\r\n")+"\r\n"}const Ii=/^([a-z])=(.*)/;function Ei(...e){let t=[],r=[];const i=function(i){if(t.length){let e=i.split(/(\r\n|\r|\n)/).filter((e=>Ii.test(e)));for(let r=0;r<t.length;r++)t[r]&&(e=t[r](e));i=e.join("\r\n")}if(e.length){let t=bi(i);for(let r=0;r<e.length;r++)e[r]&&(t=e[r](t));i=Si(t)}if(r.length){let e=i.split(/(\r\n|\r|\n)/).filter((e=>Ii.test(e)));for(let t=0;t<r.length;t++)r[t]&&(e=r[t](e));i=e.join("\r\n")+"\r\n"}return i};return i.before=(...e)=>(t=t.concat(e),i),i.after=(...e)=>(r=r.concat(e),i),i}function Ti(e,t,r){return function(i){return o.a(i.media)&&ye(i.media,(i=>{if(i.type===t){let t=[];if(ye(i.rtp,(r=>{r.codec.toLocaleLowerCase()===e.toLocaleLowerCase()&&t.push(r.payload)})),!t.length)return!0;let n=t[0];r&&ye(i.fmtp,(e=>{if(Ee(t,e.payload)&&we.b(e.config,r)>-1)return n=e.payload,!1}));const s=i.payloads.split(" ");Ie(s,Object(je.a)(n),!0),s.unshift(Object(je.a)(n)),i.payloads=s.join(" "),pe.debug(`[sdpOperator preferCodec] codec: ${e}, mediaType: ${i.type}, fmpt: ${r}`)}})),i}}function Ri(e,t,r){return function(i){return o.a(i.media)&&ye(i.media,(i=>{if("application"===i.type)return!0;t&&t!==i.type||!o.a(i.ext)||(i.ext=i.ext.filter((t=>!(o.f(r)&&t.value===r||we.b(t.uri,e)>-1))),pe.debug(`[sdpOperator removeExtmap] ext: ${e}, mediaType: ${i.type}, value: ${r}`))})),i}}function wi(e,t){return function(r){let i=!1;return o.a(r.media)&&ye(r.media,(t=>{if(t.type===e)return i=!0,!1})),t(i),r}}function Ai(e,...t){let r,i=0;for(r of t)i+=r.length;let n=new e(i),s=0;for(r of t)n.set(r,s),s+=r.length;return n}console.log.bind(console),console.log.bind(console);const ki="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function Ci(e,t,r){const i=(t>>>=0)+r;let n=t,s="";for(;e[n>>>0]&&!(n>=i);)++n;if(n-t>16&&e.subarray&&ki&&!("function"==typeof SharedArrayBuffer&&e.buffer instanceof SharedArrayBuffer))return ki.decode(e.subarray(t>>>0,n>>>0));for(;t<n;){let r=e[t++>>>0];if(!(128&r)){s+=String.fromCharCode(r);continue}let i=63&e[t++>>>0];if(192==(224&r)){s+=String.fromCharCode((31&r)<<6|i);continue}let n=63&e[t++>>>0];if(r=224==(240&r)?(15&r)<<12|i<<6|n:(7&r)<<18|i<<12|n<<6|63&e[t++>>>0],r<65536)s+=String.fromCharCode(r);else{let e=r-65536;s+=String.fromCharCode(55296|e>>10,56320|1023&e)}}return s}class Mi{constructor(e,t=!0){this.buffer=e,this.data=new DataView(e.buffer),this.pos=0,this.size=e.byteLength,this.littleEndian=!t}readUint8(){return this.data.getUint8(this.pos++)}readUint16(){const e=this.data.getUint16(this.pos,this.littleEndian);return this.pos+=2,e}readUint24(){return this.readUint16()<<8|this.readUint8()}readUint32(){const e=this.data.getUint32(this.pos,this.littleEndian);return this.pos+=4,e}readUint64(){const e=BigInt(this.readUint32()),t=BigInt(this.readUint32());return this.littleEndian?t<<BigInt(32)|e:e<<BigInt(32)|t}readInt8(){return this.data.getInt8(this.pos++)}readInt16(){const e=this.data.getInt16(this.pos,this.littleEndian);return this.pos+=2,e}readInt32(){const e=this.data.getInt32(this.pos,this.littleEndian);return this.pos+=4,e}readInt64(){const e=BigInt(this.readInt32()),t=BigInt(this.readInt32());return this.littleEndian?t<<BigInt(32)|e:e<<BigInt(32)|t}readFloat(){const e=this.data.getFloat32(this.pos,this.littleEndian);return this.pos+=4,e}readDouble(){const e=this.data.getFloat64(this.pos,this.littleEndian);return this.pos+=8,e}readHex(e=1){let t="";for(let r=0;r<e;r++){const e=this.readUint8().toString(16);t+=1===e.length?"0"+e:e}return t}readString(e=1){let t="";if(e){let r=this.pos;for(let t=0;t<e&&0===this.buffer[this.pos+t];t++)r++;t=Ci(this.buffer,r,e)}return this.pos+=e,t}getPos(){return this.pos}seek(e){e>this.size&&(this.pos=this.size),this.pos=e}skip(e){this.seek(this.pos+e)}remainingSize(){return this.size-this.pos}readBuffer(e){e=Math.min(e,this.remainingSize());const t=this.buffer.slice(this.pos,this.pos+e);return this.pos+=e,t}appendBuffer(e){this.buffer=Ai(Uint8Array,this.buffer,e),this.data=new DataView(this.buffer),this.size+=e.byteLength}}var Oi=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const Pi={send:!0,layers:1,payloadType:243,enableSVC:!1,enableSEI:!0};class Li{constructor(e={}){this.options=Le({},Pi,e),this.queue=[],this.next=0;for(let e=0;e<this.options.layers;e++)this.queue.push([]);this.encodeStreamMap=new Map,this.ssrcCaches=new Map}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,r=0;const i=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(i.getUint8(n)){case 0:r++;break;case 1:2!==r&&3!==r||t++,r=0;break;default:r=0}return t}pushNumber(e,t){const r=t/255|0,i=t%255;for(let t=0;t<r;t++)e.push(255);e.push(i)}readNumber(e){let t=0,r=e.readUint8();for(;255===r;)t+=255,r=e.readUint8();return t+=r,t}encodeSEINalu(e,t){const r=[0,0,0,1,6];this.pushNumber(r,t),this.pushNumber(r,e.byteLength);const i=new Uint8Array(r.length+e.byteLength);return i.set(r,0),i.set(new Uint8Array(e),r.length),i.buffer}decodeSEINalu(e){if(this.onmessage){const t=new Mi(e);0===t.readUint24()&&t.skip(1),t.skip(1);const r=this.readNumber(t),i=this.readNumber(t);this.onmessage(t.readBuffer(i),r)}}changeNRI(e,t){let r;t=3-(t=Math.min(t,3));let i={offset:0,startCode:0};for(;(r=this.getNextNaluStart(e,i.offset)).offset>-1&&(i=this.getNextNaluStart(e,r.offset+r.startCode),e[r.offset+r.startCode]=159&e[r.offset+r.startCode]|t<<5,-1!==i.offset););}encodeVideoFrame(e,t){return Oi(this,void 0,void 0,(function*(){if(this.options.onVideoEncodeDataPipe)try{const t=yield this.options.onVideoEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){pe.error("decodeVideoFrame fail, "+dt(e))}const r=e.getMetadata();let i=this.ssrcCaches.get(r.synchronizationSource);if(!i){if(i=this.queue[this.next++],!i)return void t.enqueue(e);this.ssrcCaches.set(r.synchronizationSource,i)}if(i.length&&!this.isEmptyFrame(e)){if(r.temporalIndex)return void t.enqueue(e);const n=9-this.getNaluCount(e.data);if(n<=0)return void t.enqueue(e);e.data=Ai(Uint8Array,...[new Uint8Array(e.data)].concat(i.splice(0,n))).buffer}t.enqueue(e)}))}encodeAudioFrame(e,t){return Oi(this,void 0,void 0,(function*(){if(!this.isEmptyFrame(e)&&this.options.onAudioEncodeDataPipe)try{const t=yield this.options.onAudioEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){pe.error("decodeVideoFrame fail, "+dt(e))}t.enqueue(e)}))}getNextSEIStart(e,t){let r=0;for(let i=t;i<e.length;i++)switch(e[i]){case 0:r++;break;case 1:if((2===r||3===r)&&6===e[i+1])return i-r;r=0;break;default:r=0}return-1}getNextNaluStart(e,t){let r=0;for(let i=t;i<e.length;i++)switch(e[i]){case 0:r++;break;case 1:if(2===r||3===r)return{offset:i-r,startCode:r+1};r=0;break;default:r=0}return{offset:-1,startCode:0}}decodeVideoFrame(e,t){return Oi(this,void 0,void 0,(function*(){if(!this.isEmptyFrame(e)){if(this.options.onVideoEncodeDataPipe)try{const t=yield this.options.onVideoEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){pe.error("decodeVideoFrame fail, "+dt(e))}const t=new Uint8Array(e.data);let r=0,i=-1;for(;(i=this.getNextSEIStart(t,r))>-1;){if(r=this.getNextNaluStart(t,i+3).offset,!(r>-1)){this.decodeSEINalu(t.slice(i));break}this.decodeSEINalu(t.slice(i,r))}}t.enqueue(e)}))}decodeAudioFrame(e,t){return Oi(this,void 0,void 0,(function*(){if(!this.isEmptyFrame(e)&&this.options.onAudioEncodeDataPipe)try{const t=yield this.options.onAudioEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){pe.error("decodeVideoFrame fail, "+dt(e))}t.enqueue(e)}))}start(e){this.abort=new AbortController,this.transports=e;let t=!1,r=!1;ye(e,(e=>{const i=e.createEncodedStreams();e.track.kind===zr.VIDEO?!this.options.enableSEI&&!this.options.onVideoEncodeDataPipe||t?i.readable.pipeTo(i.writable,{signal:this.abort.signal}):(t=!0,this.transformStreamVideo=new TransformStream({transform:this.options.send?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)}),i.readable.pipeThrough(this.transformStreamVideo).pipeTo(i.writable,{signal:this.abort.signal}).catch((e=>{}))):e.track.kind===zr.AUDIO&&this.options.onAudioEncodeDataPipe&&!r?(r=!0,this.transformStreamAudio=new TransformStream({transform:this.options.send?this.encodeAudioFrame.bind(this):this.decodeAudioFrame.bind(this)}),i.readable.pipeThrough(this.transformStreamAudio).pipeTo(i.writable,{signal:this.abort.signal}).catch((e=>{}))):i.readable.pipeTo(i.writable,{signal:this.abort.signal}),this.encodeStreamMap.set(e,i)}))}stop(){if(this.abort)try{this.abort.abort("none")}catch(e){}this.abort=null,this.transformStreamVideo=null,this.transformStreamAudio=null,this.encodeStreamMap&&this.encodeStreamMap.clear(),this.ssrcCaches&&this.ssrcCaches.clear(),this.next=0}restart(){this.stop(),this.start(this.transports)}isStarting(){return!!this.abort}push(e,t){if(!this.options.enableSEI)throw new Error("not support");const r=new Uint8Array(this.encodeSEINalu(e,t||this.options.payloadType));ye(this.queue,(e=>{e.push(r),e.length>100&&e.shift()}))}setAudioEncodeDataPipe(e){this.options.onAudioEncodeDataPipe=e}setVideoEncodeDataPipe(e){this.options.onVideoEncodeDataPipe=e}destroy(){this.stop(),this.queue=null,this.encodeStreamMap=null,this.ssrcCaches=null}}function xi(e){return function(t){if(o.a(t.media)){let r=!1;ye(t.media,(e=>{if(o.a(e.candidates)&&(r=e.candidates.some((e=>"tcp"===e.transport||"udp"===e.transport&&!br(e.ip))),r))return!1})),r&&ye(t.media,(e=>{o.a(e.candidates)&&(e.candidates=e.candidates.filter((e=>"tcp"===e.transport||"udp"===e.transport&&!br(e.ip))))}));let i=!1;ye(t.media,(e=>{if(o.a(e.candidates)&&(i=e.candidates.some((e=>"udp"===e.transport)),i))return!1})),e(i)}return t}}var Di=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};li("a",[{name:"rembFlags",reg:/^remb-flags:\s?(\d+)/,format:"remb-flags: %s"},{name:"packetlostScale",reg:/^packetlost-scale:\s?(\d+)/,format:"packetlost-scale: %s"},{name:"brtcVideoNego",reg:/^brtcvideonego:\s?(\d+)/,format:"brtcvideonego: %s"}]);const Ni={acodec:"opus",vcodec:"h264",audioBitrate:40960,simulcast:1,stereo:!1,encodings:[{scale:1,bitrate:512e3,fps:15}],usePlanBSimulcast:ut.chrome&&!ut.checkVersion(ut.majorVersion,"87",!0),redAudio:!1,profile:"42e01f"};let $i;function Ui(){let e=$i||(AudioContext?($i=new AudioContext,$i):void 0);return!!e&&e.createMediaStreamDestination().stream.getAudioTracks()[0]}const Bi=ut.edge&&ut.checkVersion(ut.majorVersion,"79",!0)||ut.firefox&&ut.checkVersion(ut.majorVersion,"34",!0)||ut.opera&&ut.checkVersion(ut.majorVersion,"52",!0)||ut.safari&&ut.checkVersion(ut.majorVersion,"11",!0);class Vi extends wr{constructor(e,t,r){if(super({client:t,type:e.type,sourceType:e.sourceType,userId:e.userId,streamId:e.streamId,videoOn:e.videoOn,audioOn:e.audioOn,videoEnable:e.videoEnable,audioEnable:e.audioEnable,audioLevelInterval:e.audioLevelInterval},r),this.options=Le({},Ni,e),this.published=!1,this.options.mediaStream){const e=this.getVideoTrack(),t=this.getAudioTrack();this.videoOn=!!e,this.videoOn?this.videoEnable=e.enabled:this.videoEnable=!1,this.audioOn=!!t,this.audioOn?this.audioEnable=t.enabled:this.audioEnable=!1}this.handlerStreamEvent()}addStream(e){const t=this.options.mediaStream;return this.options.mediaStream=e,t}getStream(){if(this.options)return this.options.mediaStream}setUserId(e){this.userId=e}isPublished(){return this.published}setEncodings(e){this.options.encodings=e,this.options.simulcast=e.length}getEncodings(){return this.options.encodings}getSimulcast(){return this.options.simulcast}processOffer(e,t={iceServers:[]}){var r;return Di(this,void 0,void 0,(function*(){if(!this.options.mediaStream)throw new Error("not has mediaStream to publish!");e&&(this.client=e),this.oldPeer&&(this.oldPeer.destroy(),this.oldPeer=null),this.oldPeer=this.peer,this.oldPeer&&(this.oldPeer.oniceconnectionstatechange=null,this.oldPeer.onicecandidate=null,this.oldPeer.ondtlsstatechange=null),this.collector&&this.collector.destroy(),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser=null),this.peer=new ei({iceServers:null!==(r=t.iceServers)&&void 0!==r?r:[],rtcpMuxPolicy:"require",encodedInsertableStreams:this.hasEncodedDataProcesser(t)}),this.isMsSupportDatachannel&&this.peer.createChannel(),this.handlerEvent(),this.peer.addStream(this.options.mediaStream,this.options.encodings,this.options.audioBitrate);let i=yield this.peer.offer(),n=0;for(let e=0;e<this.options.encodings.length;e++)n+=this.options.encodings[e].bitrate;return this.options.encodings.length>1&&(n=Math.ceil(1.2*n)),i=Ei(Ti(this.options.acodec,zr.AUDIO),Ti(this.options.vcodec,zr.VIDEO,this.options.profile),ii(Math.ceil(this.options.audioBitrate/1024),zr.AUDIO),ii(Math.ceil(n/1024),zr.VIDEO),ni(Hr.SEND_ONLY),this.options.stereo?ci(zr.AUDIO,"stereo",1,this.options.acodec):null,this.options.stereo?ci(zr.AUDIO,"sprop-stereo",1,this.options.acodec):null,this.options.redAudio?si("urn:boom:audio-stacked-rtp",null,zr.AUDIO):null,Ri("urn:ietf:params:rtp-hdrext:sdes:mid"),ri("nack",Jr.ADD,zr.AUDIO),this.options.simulcast>1&&this.options.usePlanBSimulcast?function(e=2){return function(t){return e<2||ye(t.media,(t=>{if(t.type===zr.VIDEO){const r=(t.ssrcs||[]).find((e=>"msid"===e.attribute));if(!r)return;const[i,n]=r.value.split(" "),s=tt(r.id);let o;ye(t.ssrcGroups||[],(e=>{if("FID"===e.semantics){const t=e.ssrcs.split(/\s+/);if(tt(t[0])===s)return o=tt(t[1]),!1}}));const a=t.ssrcs.find((e=>"cname"===e.attribute));if(!a)return;const c=a.value,u=[],d=[];for(let t=0;t<e;t++)u.push(s+t),o&&d.push(o+t);t.ssrcGroups=[],t.ssrcs=[],t.ssrcGroups.push({semantics:"SIM",ssrcs:u.join(" ")});for(let e=0;e<u.length;e++)t.ssrcs.push({id:u[e],attribute:"cname",value:c}),t.ssrcs.push({id:u[e],attribute:"msid",value:`${i} ${n}`}),t.ssrcs.push({id:u[e],attribute:"label",value:n}),t.ssrcs.push({id:u[e],attribute:"mslabel",value:i});for(let e=0;e<d.length;e++){const r=u[e],s=d[e];t.ssrcs.push({id:s,attribute:"cname",value:c}),t.ssrcs.push({id:s,attribute:"msid",value:`${i} ${n}`}),t.ssrcs.push({id:s,attribute:"label",value:n}),t.ssrcs.push({id:s,attribute:"mslabel",value:i}),t.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}pe.debug("[sdpOperator planBSimulcast] simulcast: "+e)}})),t}}():null,ut.firefox&&this.options.simulcast>1?function(e){return o.a(e.media)&&ye(e.media,(e=>{e.type===zr.VIDEO&&e.simulcast&&(delete e.ssrcs,delete e.ssrcGroups,pe.debug("[sdpOperator removeSSRC]"))})),e}:null,(ut.safari||ut.wechat&&nr.ios)&&"h264"===this.options.vcodec?function(e="640c1f",t="42e01f"){return function(r){return o.a(r.media)&&ye(r.media,(r=>{r.type===zr.VIDEO&&(ye(r.fmtp,(r=>{r.config&&r.config.indexOf("profile-level-id="+e)>-1&&(r.config=r.config.replace(e,t))})),pe.debug(`[sdpOperator profileReplace] profile: ${e}, replace: ${t}`))})),r}}("640c1f","42e01f"):null)(i),yield this.peer.setOffer(i),this.options.simulcast>1&&this.options.usePlanBSimulcast&&this.peer.setEncodings(this.options.encodings),this.collector=new Fr(this.peer.getPeerConnection(),1e3,!0,this.audioLevelInterval),this.collector.onAudioLevel=e=>{this.fire("stream-audio-level",[e])},this.logger.debug(`localstream streamId: ${this.getStreamId()}, offer: ${"\n"+i}`),i}))}processAnswer(e,t={enableSEI:!1,enableSVC:!1}){return Di(this,void 0,void 0,(function*(){let r=!1,i=!1,n={};const s=Ei(ti(this.msmsIPs,!1),this.isMsSupportDatachannel?wi(zr.APPLICATION,(e=>{r=e})):null,xi((e=>{i=e})),function(e,t){return function(r){return t[e]=r[e],r}}("packetlostScale",n));if(e=s(e),t.enableSVC){let t="";e=e.replace(/scalability-mode=([A-Z0-9_]{4,});?/g,(e=>(t=e.split("=")[1].replace(/^S/,"L").replace(/T[4-9]/,"T3"),"scalability-mode="+t))),t&&(";"===t[t.length-1]&&(t=t.slice(0,t.length-1)),this.peer.setScalabilityMode(t))}if(!r&&this.isMsSupportDatachannel)throw this.isMsSupportDatachannel=!1,this.logger.error(`msms ${this.getMsmsIP()} not support datachannel, should retry, localstream streamId: ${this.getStreamId()}`),new Error("msms not support datachannel, should retry");this.logger.debug(`localstream streamId: ${this.getStreamId()}, answer: ${"\n"+e}`),yield this.peer.setAnwser(e),this.oldPeer&&(this.oldPeer.destroy(),this.oldPeer=null),this.hasEncodedDataProcesser(t)&&(this.encodedDataProcesser=new Li({send:!0,layers:this.options.simulcast||1,enableSEI:t.enableSEI&&"h264"===this.options.vcodec.toLocaleLowerCase(),enableSVC:!1,onAudioEncodeDataPipe:this.onAudioEncodeDataPipe,onVideoEncodeDataPipe:this.onVideoEncodeDataPipe}),this.encodedDataProcesser.start(this.peer.getSenders())),i&&this.startDtlsConnectionTimeout(),n.packetlostScale&&this.collector&&this.collector.setUploadPacketLostScale(tt(n.packetlostScale,1))}))}muteVideo(){return Di(this,void 0,void 0,(function*(){this.hasVideo()&&this.getVideoEnable()&&(Bi?(this.emptyVideoTrack||(this.emptyVideoTrack=function(){let e=document.createElement("canvas");return!!e.captureStream&&e.captureStream().getTracks()[0]}()),this.emptyVideoTrack?(this.sourceVideoTrack=yield this.replaceTrack(this.emptyVideoTrack),this.sourceVideoTrack.enabled=!1,this.emptyVideoTrack.enabled=!1):this.getVideoTrack().enabled=!1):this.getVideoTrack().enabled=!1,this.videoEnable=!1,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{video_enable:!1},"videoEnableControl_"+this.streamId)),this.logger.info("localstream muteVideo"))}))}unmuteVideo(){return Di(this,void 0,void 0,(function*(){this.hasVideo()&&!this.getVideoEnable()&&(Bi&&this.sourceVideoTrack?(yield this.replaceTrack(this.sourceVideoTrack,!0),this.sourceVideoTrack.enabled=!0,this.emptyVideoTrack&&(this.emptyVideoTrack.enabled=!0),this.sourceVideoTrack=null):this.getVideoTrack().enabled=!0,this.videoEnable=!0,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{video_enable:!0},"videoEnableControl_"+this.streamId)),this.logger.info("localstream unmuteVideo"))}))}muteAudio(){return Di(this,void 0,void 0,(function*(){this.hasAudio()&&this.getAudioEnable()&&(Bi?(this.emptyAudioTrack||(this.emptyAudioTrack=Ui()),this.emptyAudioTrack?(this.sourceAudioTrack=yield this.replaceTrack(this.emptyAudioTrack),this.sourceAudioTrack.enabled=!1,this.emptyAudioTrack.enabled=!1):this.getAudioTrack().enabled=!1):this.getAudioTrack().enabled=!1,this.audioEnable=!1,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{audio_enable:!1},"audioEnableControl_"+this.streamId)),this.logger.info("localstream muteAudio"))}))}unmuteAudio(){return Di(this,void 0,void 0,(function*(){this.hasAudio()&&!this.getAudioEnable()&&(Bi&&this.sourceAudioTrack?(yield this.replaceTrack(this.sourceAudioTrack,!0),this.sourceAudioTrack.enabled=!0,this.emptyAudioTrack&&(this.emptyAudioTrack.enabled=!0),this.sourceAudioTrack=null):this.getAudioTrack().enabled=!0,this.audioEnable=!0,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{audio_enable:!0},"audioEnableControl_"+this.streamId)),this.logger.info("localstream unmuteAudio"))}))}getSourceVideoTrack(){return this.sourceVideoTrack}getSourceAudioTrack(){return this.sourceAudioTrack}addTrack(){return Di(this,void 0,void 0,(function*(){}))}removeTrack(){return Di(this,void 0,void 0,(function*(){}))}replaceTrack(e,t=!1){return Di(this,void 0,void 0,(function*(){const r="video"===e.kind;let i;const n=r?this.getVideoTrack():this.getAudioTrack();if(r&&!this.getVideoEnable()&&!t&&this.sourceVideoTrack)i=this.sourceVideoTrack,this.sourceVideoTrack=e,e.enabled=this.getVideoEnable();else if(r||this.getAudioEnable()||t||!this.sourceAudioTrack){if(i=n,this.peer)yield this.peer.replaceTrack(e);else{const t=this.getStream();t.removeTrack(n),t.addTrack(e)}e.enabled=i.enabled}else i=this.sourceAudioTrack,this.sourceAudioTrack=e,e.enabled=this.getAudioEnable();const s={};return"audio"===e.kind?s.audio=e:"video"===e.kind&&(s.video=e),this.fire("stream-replaced",[s]),this.logger.info(`LocalStream replaceTrack, streamId: ${this.getStreamId()}, kind: ${e.kind}, label: ${e.label}, force: ${t}`),i}))}destroy(e=!0){if(this.logger.info(`localStream destroy, streamId: ${this.getStreamId()}, stopTrack: ${e}`),e){const e=this.getVideoTrack(),t=this.getAudioTrack();e&&e.stop(),t&&t.stop(),this.sourceVideoTrack&&this.sourceVideoTrack!==e&&this.sourceVideoTrack.stop(),this.emptyVideoTrack&&this.emptyVideoTrack!==e&&this.emptyVideoTrack.stop(),this.sourceAudioTrack&&this.sourceAudioTrack!==t&&this.sourceAudioTrack.stop(),this.emptyAudioTrack&&this.emptyAudioTrack!==t&&this.emptyAudioTrack.stop()}else this.emptyVideoTrack&&this.emptyVideoTrack.stop(),this.emptyAudioTrack&&this.emptyAudioTrack.stop();this.oldPeer&&(this.oldPeer.destroy(),this.oldPeer=null),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser.destroy()),this.close(),this.options=null,this.emptyVideoTrack=null,this.sourceVideoTrack=null,this.emptyAudioTrack=null,this.sourceAudioTrack=null,this.destroyed=!0,this.off()}getOptions(){return this.options}validStreamType(e){return e===Pt.CAMERA?Pt.CAMERA:e===Pt.SCREEN?Pt.SCREEN:e===Pt.FILE?Pt.FILE:Pt.CAMERA}setOptions(e){Le(this.options,e),e.type&&(this.type=this.validStreamType(e.type))}getVideoEnable(){const e=this.getVideoTrack();return!!e&&e.enabled}getAudioEnable(){const e=this.getAudioTrack();return!!e&&e.enabled}resetEncodings(e,t=!0){return Di(this,void 0,void 0,(function*(){if(e.length!==this.options.encodings.length)throw this.logger.error(`the length of encodings must be equals before, encodings: ${JSON.stringify(e)}, before: ${JSON.stringify(this.options.encodings)}`),new Error("the length of encodings must be equals before");for(let t=0;t<e.length;t++)Le(this.options.encodings[t],e[t]);if(this.peer){this.peer.setEncodings(this.options.encodings);let e=this.options.encodings.reduce(((e,t)=>e+Math.ceil(t.bitrate/1e3)),0);const r=bi(this.peer.getRemoteSessionDescriptor().sdp);if(ye(r.media,(t=>{var r;"video"===t.type&&((null===(r=t.bandwidth[0])||void 0===r?void 0:r.limit)&&(t.bandwidth[0].limit=e),ye(t.fmtp,(t=>{t.config.indexOf("x-google-max-bitrate")>-1&&(t.config=t.config.split(";").map((t=>t.indexOf("x-google-max-bitrate")>-1?"x-google-max-bitrate="+e:t.indexOf("x-google-start-bitrate")>-1?"x-google-start-bitrate="+e:t.indexOf("x-google-min-bitrate")>-1?"x-google-min-bitrate="+Math.floor(.8*e):t)).join(";"))})))})),yield this.peer.resetAnswer(Si(r)),this.peer&&this.published&&t){const t={videoAS:e};let r=-1,i=-1,n=-1;for(let e=0;e<this.options.encodings.length;e++)r<this.options.encodings[e].width&&(r=this.options.encodings[e].width,n=this.options.encodings[e].fps),i<this.options.encodings[e].height&&(i=this.options.encodings[e].height);this.hasAudio()&&o.f(this.options.audioBitrate)&&(e+=Math.ceil(this.options.audioBitrate/1e3),t.audioAS=Math.ceil(this.options.audioBitrate/1e3)),yield this.request("setrate",Object.assign(Object.assign({rate:e},t),{width:r,height:i,fps:n}))}}}))}sendSEIMessage(e,t){if(this.encodedDataProcesser)return this.encodedDataProcesser.push(e,t);throw new Error("not support")}handlerStreamEvent(){this.on("consumer-bitrate-changed",(e=>!1)).on("video-layer-status-changed",(e=>{if(this.peer)if(o.f(e.layer)){const t=e.layer,r=this.options.encodings[t];r&&(this.peer.enableVideoLayer(!!e.enable&&!1!==r.active,t),r.serverActive=!!e.enable,this.logger.info(`video layer status changed, enable: ${e.enable}, layer: ${t}`))}else for(let t=0;t<this.getLayerCount();t++){const r=this.options.encodings[t];r&&(this.peer.enableVideoLayer(!!e.enable&&!1!==r.active,t),r.serverActive=!!e.enable,this.logger.info(`video layer status changed, enable: ${e.enable}, layer: ${t}`))}}))}isAllVideoLayerDisabled(){const e=this.options.encodings;let t=!0;for(let r=0;r<e.length;r++)if(!1!==e[r].active&&!1!==e[r].serverActive){t=!1;break}return t}getLayerCount(){return this.options.encodings.length}}class Fi{constructor(e=5){this.count=e,this.audioBytesArray=[],this.videoBytesArray=[]}addData(e,t){this.audioBytesArray.push(e),this.audioBytesArray.length>this.count&&this.audioBytesArray.shift(),this.videoBytesArray.push(t),this.videoBytesArray.length>this.count&&this.videoBytesArray.shift()}judgeAudioMuted(){if(this.audioBytesArray.length===this.count){for(let e=0;e<this.count;e++)if(0!==this.audioBytesArray[e])return!1;return!0}return!1}judgeVideoMuted(){if(this.videoBytesArray.length===this.count){for(let e=0;e<this.count;e++)if(0!==this.videoBytesArray[e])return!1;return!0}return!1}resetVideo(){this.videoBytesArray=[]}resetAudio(){this.audioBytesArray=[]}destroy(){this.audioBytesArray=[],this.videoBytesArray=[]}}function ji(e,t,r,i){return function(n,s,a){let c=a.value;const u=[];return a.value=function(){const n=J(),a=Te(arguments),d=e(n,u,a);if(0==d)return u.push(t(n,a)),u.length>r&&u.shift(),H(c,this,a);throw o.i(d)&&(i=d),new R(1002,`${s} ${null!=i?i:"方法执行超出频率限制"}`)},a}}var Wi=function(e,t,r,i){var n,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},qi=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class Gi extends ft{constructor(e,t){super(ft.STREAM_TYPE_LOCAL,t),this.streamDeviceOption=e,this.videoProfile="480p",this.audioProfile="standard",this.screenProfile="1080p",e.screen?(this.streamCodecOption=xe(Gt["1080p"],!0),this.streamCodecOption.width=null,this.streamCodecOption.height=null):this.streamCodecOption=xe(Wt["480p"],!0),this.muteDetect=new Fi,this.muteDetectAudioMuted=!1,this.muteDetectVideoMuted=!1,this.log(`${this.sid} create LocalStream, userId: ${this.uid}, options: ${JSON.stringify(e)}`,pe.DEBUG,"stream")}constraintBitrate(){let e,t=this.streamCodecOption.width*this.streamCodecOption.height;t&&o.f(t)&&(Oe(Ht,((r,i)=>{if(t<=+i)return e=r,!1})),e&&(this.streamCodecOption.bitrate<e.min&&(this.streamCodecOption.bitrate=e.min),this.streamCodecOption.bitrate>e.max&&(this.streamCodecOption.bitrate=e.max)))}applyConstraint(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient(),r=this.getVideoTrack();if(r){const e=r.getConstraints();if(e.width=this.streamCodecOption.width,e.height=this.streamCodecOption.height,e.frameRate=this.streamCodecOption.frameRate,r.applyConstraints(e),t)if(a(this.webrtcType)){const e=this.client.getEncodings(this);this.stream.resetEncodings(e)}else c(this.webrtcType)&&t.setVideoProfile({bitrate:this.streamCodecOption.bitrate})}}setPrivileges(e){this.privileges=e}isScreenStream(){return!!this.streamDeviceOption.screen}setVideoProfile(e){this.videoProfile=e,Le(this.streamCodecOption,Wt[e]||{}),this.applyConstraint(),this.log(`${this.sid} LocalStream setVideoProfile, userId: ${this.uid}, profile: ${e}`,pe.INFO,"stream")}setScreenProfile(e){this.screenProfile=e,Le(this.streamCodecOption,Gt[e]||{}),this.log(`${this.sid} LocalStream setScreenProfile, userId: ${this.uid}, profile: ${e}`,pe.INFO,"stream")}setAudioProfile(e){this.audioProfile=e,this.log(`${this.sid} LocalStream setAudioProfile, userId: ${this.uid}, profile: ${e}`,pe.INFO,"stream")}setVideoEncoderConfiguration(e){if(Oe(e,((t,r)=>{if("profile"===r){if(!o.i(t))throw new R(1001,r+" 的值不是 string 类型")}else{if(!o.f(t))throw new R(1001,r+" 的值不是 number 类型");if(t<=0)throw new R(1001,r+" 的值非法,必须是大于 0 的整数");e[r]=Math.floor(t)}})),Le(this.streamCodecOption,e),this.streamCodecOption.width*this.streamCodecOption.height>8294400)throw this.streamCodecOption=xe(Wt["480p"],!0),new R(1001,"暂不支持4k以上分辨率");this.constraintBitrate(),this.applyConstraint(),this.log(`${this.sid} LocalStream setVideoEncoderConfiguration, userId: ${this.uid}, options: ${JSON.stringify(e)}`,pe.INFO,"stream")}getAudioBandwidth(){return qt[this.webrtcType||0][this.audioProfile].bitrate}init(){var e,t;return qi(this,void 0,void 0,(function*(){let r,i=b();o.f(i)||(i=0);let n=qt[i],s=new MediaStream;if(this.streamDeviceOption.audioSource||this.streamDeviceOption.videoSource)this.streamDeviceOption.audioSource?(s.addTrack(this.streamDeviceOption.audioSource),this.streamDeviceOption.audio=!0):this.streamDeviceOption.audio=!1,this.streamDeviceOption.videoSource?(s.addTrack(this.streamDeviceOption.videoSource),this.streamDeviceOption.video=!0):this.streamDeviceOption.video=!1;else{let e;this.streamDeviceOption.screen?e={screen:!0,audio:this.streamDeviceOption.audio,width:this.streamCodecOption.width,height:this.streamCodecOption.height,fps:this.streamCodecOption.frameRate}:(e={audio:!1,video:!1,fps:this.streamCodecOption.frameRate},this.streamDeviceOption.video&&(e.video={width:{ideal:this.streamCodecOption.width,max:this.streamCodecOption.width},height:{ideal:this.streamCodecOption.height,max:this.streamCodecOption.height},deviceId:this.streamDeviceOption.cameraId,frameRate:this.streamCodecOption.frameRate}),this.streamDeviceOption.audio&&(e.audio={deviceId:this.streamDeviceOption.microphoneId,echoCancellation:!0,channelCount:n[this.audioProfile].channelCount},o.c(this.streamDeviceOption.autoGainControl)&&(e.audio.autoGainControl=this.streamDeviceOption.autoGainControl),o.c(this.streamDeviceOption.echoCancellation)&&(e.audio.echoCancellation=this.streamDeviceOption.echoCancellation),o.c(this.streamDeviceOption.noiseSuppression)&&(e.audio.noiseSuppression=this.streamDeviceOption.noiseSuppression))),s=yield ar(e)}if(a(i))r=new Vi({type:this.streamDeviceOption.type,sourceType:null!==(e=this.streamDeviceOption.sourceType)&&void 0!==e?e:this.streamDeviceOption.screen?Pt.SCREEN:Pt.CAMERA,userId:Object(je.a)(this.uid),streamId:this.sid,mediaStream:s,audioOn:this.streamDeviceOption.audio,videoOn:this.streamDeviceOption.video,usePlanBSimulcast:!(ut.firefox||ut.chrome&&ut.checkVersion(ut.majorVersion,"86"))||y,profile:null!==(t=this.streamCodecOption.profile)&&void 0!==t?t:"42e01f",stereo:/stereo/.test(this.audioProfile)});else if(c(i)){let e={};(this.streamDeviceOption.video||this.streamDeviceOption.screen)&&(e.videoSource=s.getVideoTracks()[0]),this.streamDeviceOption.audio&&(e.audioSource=s.getAudioTracks()[0]),r=It.a.createStream(e),r.setAudioProfile(this.audioProfile),r.setVideoProfile(this.streamCodecOption),yield r.initialize()}this.log(`${this.sid} LocalStream init success, userId: ${this.uid}, streamDeviceOption: ${JSON.stringify(this.streamDeviceOption)}, streamCodecOption: ${JSON.stringify(this.streamCodecOption)}, audioProfile: ${this.audioProfile}`,pe.INFO,"stream"),this.setStream(i,r),this.soundMeter&&(yield this.soundMeter.ready()),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint),this.setVolumeMeter()}))}setVideoHint(e){this.streamDeviceOption.videoHint=e;const t=this.getVideoTrack();t&&(t.contentHint=this.streamDeviceOption.videoHint)}setAudioHint(e){this.streamDeviceOption.audioHint=e;const t=this.getAudioTrack();t&&(t.contentHint=this.streamDeviceOption.audioHint)}switchWebRTC(e){return qi(this,void 0,void 0,(function*(){if(this.webrtcType!==e&&c(e)){const t=qt[e],r=this.audioTrack,i=this.videoTrack;let n=null,s=null;a(this.webrtcType)&&(n=this.stream.getSourceAudioTrack(),s=this.stream.getSourceVideoTrack());let o={videoSource:s||i,audioSource:n||r},c=It.a.createStream(o);c.setAudioProfile(t[this.audioProfile]),c.setVideoProfile(this.streamCodecOption),yield c.initialize(),this.log(`${this.sid} LocalStream switch success, userId: ${this.uid}`,pe.DEBUG,"stream"),this.stream.destroy(!1),this.setStream(e,c),s&&s!==i&&this.fire(ne,{type:"video",track:s}),n&&n!==r&&this.fire(ne,{type:"audio",track:n})}}))}addTrack(e){return qi(this,void 0,void 0,(function*(){if(this.privileges&&this.privileges.enableAuth()){if(d(e)&&!this.privileges.canPushAudio())throw new R(1011,"没有音频推送权限");if(u(e)&&!this.privileges.canPushVideo())throw new R(1012,"没有视频推送权限")}if(!this.stream)throw new R(1002,"流未初始化");if(d(e)&&this.hasAudio())throw new R(1002,"当前已有一个 audioTrack");if(u(e)&&this.hasVideo())throw new R(1002,"当前已有一个 videoTrack");try{yield this.stream.addTrack(e),d(e)?(this.addAudioTrackEvents(),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint)):u(e)&&(this.addVideoTrackEvents(),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint)),this.log(`${this.sid} LocalStream addTrack, userId: ${this.uid}`,pe.DEBUG,"stream")}catch(e){throw new R(9e3,"addTrack 失败",e)}}))}removeTrack(e){return qi(this,void 0,void 0,(function*(){if(!this.stream)throw new R(1002,"流未初始化");if(d(e)&&!this.hasAudio())throw new R(1002,"当前没有 audioTrack 可以移除");if(u(e)&&!this.hasVideo())throw new R(1002,"当前没有 videoTrack 可以移除");d(e)?this.removeAudioTrackEvents():u(e)&&this.removeVideoTrackEvents();try{yield this.stream.removeTrack(e),this.log(`${this.sid} LocalStream removeTrack, userId: ${this.uid}`,pe.DEBUG,"stream")}catch(e){throw new R(9e3,"removeTrack 失败",e)}}))}replaceTrack(e,t=!1){return qi(this,void 0,void 0,(function*(){if(!(e instanceof MediaStreamTrack||t))throw new R(1002,"参数 track 不是 MediaStreamTrack 实例");if(!this.stream)throw new R(1002,"流未初始化");if(d(e)){if(!this.hasAudio())throw new R(1002,"流没有 audioTrack");this.removeAudioTrackEvents()}else if(u(e)){if(!this.hasVideo())throw new R(1002,"流没有 videoTrack");this.removeVideoTrackEvents()}(a(this.webrtcType)||c(this.webrtcType))&&(yield this.stream.replaceTrack(e)),d(e)?(this.addAudioTrackEvents(),this.setVolumeMeter(),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint),this.muteDetectAudioMuted=!1,this.muteDetect.resetAudio()):u(e)&&(this.addVideoTrackEvents(),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint),this.muteDetectVideoMuted=!1,this.muteDetect.resetVideo()),this.fire(ne,{type:e.kind,track:e}),this.log(`${this.sid} LocalStream replaceTrack, userId: ${this.uid}`,pe.DEBUG,"stream")}))}switchDevice(e,t){return qi(this,void 0,void 0,(function*(){if(!o.i(t))throw new R(1001,"deviceId 类型错误");if("audio"===e&&!this.streamDeviceOption.microphoneId)throw new R(1002,"当前的 audioTrack 不是来自于麦克风设备");if("video"===e&&!this.streamDeviceOption.cameraId)throw new R(1002,"当前的 videoTrack 不是来自于摄像头设备");if(!this.stream)throw new R(1002,"流未初始化");{let r,i;if("audio"===e){let e=b();o.f(e)||(e=0);const n={deviceId:t,echoCancellation:!0,channelCount:qt[e][this.audioProfile].channelCount};o.c(this.streamDeviceOption.autoGainControl)&&(n.autoGainControl=this.streamDeviceOption.autoGainControl),o.c(this.streamDeviceOption.echoCancellation)&&(n.echoCancellation=this.streamDeviceOption.echoCancellation),o.c(this.streamDeviceOption.noiseSuppression)&&(n.noiseSuppression=this.streamDeviceOption.noiseSuppression);const s=yield ar({audio:n,video:!1});this.streamDeviceOption.microphoneId=t,r=s.getAudioTracks()[0],i=this.getAudioTrack(),this.reportAction("deviceChange",0,null,null,{type:"microphone",device_id:t,stream:this.getActionStreamId()})}else if("video"===e){const e=yield ar({audio:!1,video:{width:this.streamCodecOption.width,height:this.streamCodecOption.height,deviceId:t},fps:this.streamCodecOption.frameRate});this.streamDeviceOption.cameraId=t,r=e.getVideoTracks()[0],i=this.getVideoTrack(),this.reportAction("deviceChange",0,null,null,{type:"camera",device_id:t,stream:this.getActionStreamId()})}"audio"===e?this.removeAudioTrackEvents():"video"===e&&this.removeVideoTrackEvents(),yield this.replaceTrack(r),i&&i.stop(),"audio"===e?(this.addAudioTrackEvents(),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint),this.muteDetectAudioMuted=!1,this.muteDetect.resetAudio()):"video"===e&&(this.addVideoTrackEvents(),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint),this.muteDetectVideoMuted=!1,this.muteDetect.resetVideo()),this.playing&&this.player&&("audio"===e?this.player.replay(this,!1,!0):"video"===e&&this.player.replay(this,!0,!1)),this.log(`${this.sid} LocalStream switchDevice, userId: ${this.uid}, type: ${e}, deviceId: ${t}`,pe.DEBUG,"stream")}}))}play(e,t={}){const r=Object.create(null,{play:{get:()=>super.play}});return qi(this,void 0,void 0,(function*(){t.muted=!0,yield r.play.call(this,e,t)}))}getStats(){var e;return qi(this,void 0,void 0,(function*(){const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(t){if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),r=this.getVideoRTPStats(e);return{videoBytesSent:De(r,"statistics.bytesSent",0),videoPacketsSent:De(r,"statistics.packetsSent",0),videoPacketsLost:De(r,"statistics.packetsLost",0),videoNacksCount:De(r,"statistics.googNacksReceived",0),audioBytesSent:De(t,"statistics.bytesSent",0),audioPacketsSent:De(t,"statistics.packetsSent",0),audioPacketsLost:De(t,"statistics.packetsLost",0),audioNacksCount:De(t,"statistics.googNacksReceived",0),width:De(r,"resolution.width",0),height:De(r,"resolution.height",0),rtt:De(e,"transport.0.rtt",0),framesEncoded:De(r,"statistics.framesEncoded",0),framesSent:De(r,"statistics.framesSent",0)}}if(c(this.webrtcType)){let e=yield t.getLocalVideoStats();if(!this.client)throw new R(1010,"已被取消推流");let r=yield t.getLocalAudioStats();if(!this.client)throw new R(1010,"已被取消推流");let i=yield t.getTransportStats(),n=e[this.uid],s=r[this.uid];return{videoBytesSent:De(n,"bytesSent",0),videoPacketsSent:De(n,"packetsSent",0),videoPacketsLost:De(n,"packetsLost",0),videoNacksCount:0,audioBytesSent:De(s,"bytesSent",0),audioPacketsSent:De(s,"packetsSent",0),audioPacketsLost:De(s,"packetsLost",0),audioNacksCount:0,width:De(n,"frameWidth",0),height:De(n,"frameHeight",0),rtt:De(i,"rtt",0),framesEncoded:De(n,"framesEncoded",0),framesSent:De(n,"framesSent",0)}}}return{}}))}getReportStats(e){var t;return qi(this,void 0,void 0,(function*(){this.stutter||(this.stutter=new bt(e,!0));let r={bandwidth:{upload:0,download:0},bitrate:{audio:{upload:0,download:0},video:{upload:0,download:0}},packetLoss:{audio:{upload:0,download:0},video:{upload:0,download:0}},resolution:{width:0,height:0},framerate:0,audioLevel:0,transport:[{ip:"",type:"",localIp:"",localCandidateType:"",remoteCandidateType:"",networkType:"",rtt:0}],quality:{audio:{jitter:0,interruptionCount:0,interruptionDuration:0},video:{jitter:0,interruptionCount:0,interruptionDuration:0}},statistics:{audio:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0},video:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0,framesEncoded:0,framesDecoded:0,framesSent:0},bweforvideo:{googAvailableReceiveBandwidth:0,googAvailableSendBandwidth:0,googRetransmitBitrate:0,googTransmitBitrate:0,googTargetEncBitrate:0},ice:{packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0}},cpu:{appCpu:0,systemCpu:0}};const i=null===(t=this.client)||void 0===t?void 0:t.getClient();if(i){if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),i=this.getVideoRTPStats(e);r.audioLevel=this.getAudioLevel(),e.bandwidth&&(r.bandwidth=e.bandwidth),e.bitrate&&(r.bitrate=e.bitrate),e.packetLoss&&(r.packetLoss=e.packetLoss),e.transport&&(r.transport=e.transport),e.bweforvideo&&(r.statistics.bweforvideo={googAvailableReceiveBandwidth:e.bweforvideo.availableReceiveBandwidth,googAvailableSendBandwidth:e.bweforvideo.availableSendBandwidth,googRetransmitBitrate:e.bweforvideo.retransmitBitrate,googTransmitBitrate:e.bweforvideo.transmitBitrate,googTargetEncBitrate:e.bweforvideo.targetEncBitrate}),e.ice&&(r.statistics.ice=e.ice),t&&(r.quality.audio=t.qa,r.statistics.audio=t.statistics),i&&(r.quality.video=i.qa,r.statistics.video=i.statistics,r.resolution=i.resolution,r.framerate=i.framerate),this.stutter.addFrameRate(De(r,"framerate",0)),this.stutter.addVideoLoss(De(r,"statistics.video.packetsSent",0),De(r,"statistics.video.packetsLost",0)),this.stutter.addAudioLoss(De(r,"statistics.audio.packetsSent",0),De(r,"statistics.audio.packetsLost",0)),this.muteDetect.addData(r.bitrate.audio.upload,r.bitrate.video.upload)}else{let e=yield i.getLocalVideoStats();if(!this.client)throw new R(1010,"已被取消推流");let t=yield i.getLocalAudioStats();if(!this.client)throw new R(1010,"已被取消推流");let n=yield i.getTransportStats(),s=e[this.uid],o=t[this.uid];this.reportCollector.addData(De(o,"bytesSent",0),De(s,"bytesSent",0),De(o,"packetsSent",0),0,De(s,"packetsSent",0),0,De(s,"framesEncoded",0)),r.bitrate.audio.upload=this.reportCollector.getAudioBitrate(),r.bitrate.video.upload=this.reportCollector.getVideoBitrate(),r.packetLoss.audio.upload=this.reportCollector.getAudioPacketLoss(),r.packetLoss.video.upload=this.reportCollector.getVideoPacketLoss(),r.audioLevel=this.getAudioLevel(),r.framerate=this.reportCollector.getFrameRate(),r.resolution.width=De(s,"frameWidth",0),r.resolution.height=De(s,"frameHeight",0),r.transport[0].rtt=De(n,"rtt",0),r.bandwidth.upload=this.reportCollector.getAudioBitrate()+this.reportCollector.getVideoBitrate(),r.statistics.audio.bytesSent=De(o,"bytesSent",0),r.statistics.audio.packetsSent=De(o,"packetsSent",0),r.statistics.video.bytesSent=De(s,"bytesSent",0),r.statistics.video.packetsSent=De(s,"packetsSent",0),r.statistics.video.framesSent=De(s,"framesSent",0),r.statistics.video.framesEncoded=De(s,"framesEncoded",0),this.stutter.addFrameRate(De(r,"framerate",0)),this.stutter.addVideoLoss(De(r,"statistics.video.packetsSent",0),De(r,"statistics.video.packetsLost",0)),this.stutter.addAudioLoss(De(r,"statistics.audio.packetsSent",0),De(r,"statistics.audio.packetsLost",0)),ut.newEdge&&ut.checkVersion(ut.majorVersion,"112",!0)||this.muteDetect.addData(r.bitrate.audio.upload,r.bitrate.video.upload)}if(this.hasAudio()&&this.getAudioOn()&&a(this.webrtcType)&&this.stream.isConnected()){const e=this.muteDetect.judgeAudioMuted();e&&!this.muteDetectAudioMuted?(this.muteDetectAudioMuted=!0,this.fire(te),this.log(`${this.sid} Stream audioTrack detect mute, userId: ${this.uid}`,pe.WARN,"stream")):!e&&this.muteDetectAudioMuted&&(this.muteDetectAudioMuted=!1,this.fire(ie),this.log(`${this.sid} Stream audioTrack detect unmute, userId: ${this.uid}`,pe.WARN,"stream"))}if(this.hasVideo()&&this.getVideoOn()&&a(this.webrtcType)&&this.stream.isConnected()&&!this.stream.isAllVideoLayerDisabled()){const e=this.muteDetect.judgeVideoMuted();e&&!this.muteDetectVideoMuted?(this.muteDetectVideoMuted=!0,this.fire(ee),this.log(`${this.sid} Stream videoTrack detect mute, userId: ${this.uid}`,pe.WARN,"stream")):!e&&this.muteDetectVideoMuted&&(this.muteDetectVideoMuted=!1,this.fire(re),this.log(`${this.sid} Stream videoTrack detect unmute, userId: ${this.uid}`,pe.WARN,"stream"))}}return r}))}unmuteVideo(){const e=Object.create(null,{unmuteVideo:{get:()=>super.unmuteVideo}});return qi(this,void 0,void 0,(function*(){return this.muteDetectVideoMuted=!1,Object(z.a)((()=>{const e=this.getVideoTrack();e&&e.muted&&this.fire(ee)})),e.unmuteVideo.call(this)}))}unmuteAudio(){const e=Object.create(null,{unmuteAudio:{get:()=>super.unmuteAudio}});return qi(this,void 0,void 0,(function*(){return this.muteDetectAudioMuted=!1,Object(z.a)((()=>{const e=this.getAudioTrack();e&&e.muted&&this.fire(te)})),e.unmuteAudio.call(this)}))}getExtraReport(){var e;if(this.stutter){const t=this.stutter.judgeAudioStutter(),r=this.stutter.judegVideoStutter();return{event:t||r?1:0,audio_stutter:this.getAudioOn()&&t?1:0,video_stutter:this.getVideoOn()&&r?1:0,blockOp:0,streamSource:null!==(e=this.streamDeviceOption.sourceType)&&void 0!==e?e:Pt.CAMERA}}}getStreamCodecOption(){return this.streamCodecOption}destroy(){this.stream&&(this.videoTrack&&this.videoTrack.stop(),this.audioTrack&&this.audioTrack.stop(),super.destroy()),this.muteDetect&&this.muteDetect.destroy()}getSourceVideoTrack(){return a(this.webrtcType)&&this.stream.getSourceVideoTrack()||this.getVideoTrack()}getSourceAudioTrack(){return a(this.webrtcType)&&this.stream.getSourceAudioTrack()||this.getAudioTrack()}sendSEIMessage(e,t={}){var r,i,n;if(a(this.webrtcType))this.stream.sendSEIMessage(e,null!==(r=t.payloadType)&&void 0!==r?r:243);else if(c(this.webrtcType)){const r=null===(i=this.client)||void 0===i?void 0:i.getClient();if(r)try{r.sendSEIMessage(e,{seiPayloadType:null!==(n=t.payloadType)&&void 0!==n?n:243})}catch(e){throw new R(1002,dt(e),e)}}}}Wi([ji(((e,t,r)=>{if(r[0].byteLength>1e3)return"单次最大发送 1000 Bytes";const i=t.length;if(!i)return!1;let n=Math.max(i-30,0);const s=t[n].now;if(30==i&&e-s<1e3)return"每秒最大调用次数 30 次";let o=r[0].byteLength;for(let r=i-1;r>=n;r--)if(o+=t[r].size,o>8e3)return e-t[r].now<1e3&&"每秒最多发送 8000 Bytes";return!1}),((e,t)=>({now:e,size:t[0].byteLength})),30,"单次最大发送 1000 Bytes, 每秒最大调用次数 30 次,每秒最多发送 8000 Bytes")],Gi.prototype,"sendSEIMessage",null);class Hi{constructor(e){this.timeout=e}then(e,t){this.resolve=e,this.reject=t,this.startTime=Date.now(),this.timer=setTimeout((()=>{this.resolve(Date.now()-this.startTime),this.timer=null}),1e3*this.timeout)}stop(e=!0){this.timer&&(clearTimeout(this.timer),this.timer=null,this.resolve&&e?this.resolve(Date.now()-this.startTime):this.reject&&!e&&this.reject(Date.now()-this.startTime))}reset(e){e&&(this.timeout=e),this.timer&&(clearTimeout(this.timer),this.timer=setTimeout((()=>{this.resolve(Date.now()-this.startTime),this.timer=null}),1e3*this.timeout))}}let zi,Ji;const Yi=navigator.userAgent||"";zi=Yi.match(/NetType\/\w+/)?Yi.match(/NetType\/\w+/)[0]:"NetType/other",zi=zi.toLowerCase().replace("nettype/","");const Ki={ethernet:"ethernet",wifi:"wifi","5g":"5g","4g":"4g","3g":"3g","3gnet":"3g","2g":"2g","slow-2g":"2g"};if(Ji=Ki[zi],!Ji){let e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;e&&(Ji=Ki[e.type],Ji||(Ji=Ki[e.effectiveType]))}Ji||(Ji="unknown");var Qi={name:Ji},Xi=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};let Zi="";function en(e=!1){return Zi||function(e,t=!1){let r=t?"https://brtc-open.baijiayun.com":"https://brtc-api.baijiayun.com";return"development"===l?r=t?"https://brtc-opentest.baijiayun.com":"https://brtc-apitest.baijiayun.com":"beta"===l&&(r=t?"https://brtc-openbeta.baijiayun.com":"https://brtc-apibeta.baijiayun.com"),r+"/vrm/api/auth/token/vt"}(0,e)}function tn(e){return ai(e)||""}function rn(e,t,r=[]){return Xi(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{let s=0;const a=[e].concat(r),c=a.length,u=3*c;let d=0;!function r(){return Xi(this,void 0,void 0,(function*(){s++;try{let r=null,n=null;AbortController&&(n=new AbortController,r=n.signal);let s=yield Promise.race([fetch(a[d%c],{body:JSON.stringify(t),cache:"no-cache",credentials:"same-origin",headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",mode:"cors",redirect:"follow",referrer:"no-referrer",signal:r}),new Hi(g())]).catch((e=>{throw e}));if(o.f(s))throw n&&n.abort(),new Error(`fetch ${e}, data: ${JSON.stringify(t)} timeout`);if(s.status>=400)throw new Error("response code: "+s.status);i(s.json())}catch(e){s<u?(yield new Hi(1),d++,r()):n(e)}}))}()}))}))}function nn(e,t,r=[]){return Xi(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{let s=0;const a=[e].concat(r),c=a.length,u=3*c;let d=0;!function r(){return Xi(this,void 0,void 0,(function*(){s++;try{let r=null,n=null;AbortController&&(n=new AbortController,r=n.signal);let s=yield Promise.race([fetch(`${a[d%c]}?${tn(t)}`,{cache:"no-cache",credentials:"same-origin",headers:{Accept:"application/json","Content-Type":"application/json"},method:"GET",mode:"cors",redirect:"follow",referrer:"no-referrer",signal:r}),new Hi(g())]).catch((e=>{throw e}));if(o.f(s))throw n&&n.abort(),new Error(`fetch ${e}, data: ${JSON.stringify(t)} timeout`);if(s.status>=400)throw new Error("response code: "+s.status);i(s.json())}catch(e){s<u?(yield new Hi(1),d++,r()):n(e)}}))}()}))}))}var sn,on=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class an extends Xr{constructor(e,t){if(super(),this.url=e,this.channelOptions=t,!o.d(null==t?void 0:t.processOffer))throw new Error("processOffer required");this.createChannel(this.channelOptions),this.channel.onopen=e=>{this.onopen&&H(this.onopen,this,[e])},this.channel.onclose=e=>{this.onclose&&H(this.onclose,this,[e])},this.channel.onerror=e=>{this.close(),this.onerror&&H(this.onerror,this,[e])},this.channel.onbufferedamountlow=e=>{this.channelOptions.onbufferedamountlow&&H(this.channelOptions.onbufferedamountlow,this,[e])},this.oniceconnectionstatechange=e=>{"disconnected"!==e&&"failed"!==e||this.onclose&&H(this.onclose,this,[new Event("ice "+e)])},this.connect()}connect(){return on(this,void 0,void 0,(function*(){try{const e=yield this.offer({offerToReceiveAudio:!1,offerToReceiveVideo:!1});yield this.setOffer(e);const t=yield this.channelOptions.processOffer(this.url,e);yield this.setAnwser(t)}catch(e){pe.error("DataChannel request answer failed"),this.close(),this.onerror&&this.onerror(e)}}))}send(e){this.channel?this.channel.send(o.i(e)||o.b(e)?e:JSON.stringify(e)):pe.error("can not send data because of no channel in DataChannel")}close(){this.channel&&(this.channel.onopen=null,this.channel.onclose=null,this.channel.onerror=null,this.channel.onbufferedamountlow=null,this.channel.close(),this.channel=null),this.destroy()}clear(){this.close()}}!function(e){e[e.NONE=0]="NONE",e[e.OPEN=1]="OPEN",e[e.ERROR=2]="ERROR",e[e.CLOSE=3]="CLOSE",e[e.CLOSING=4]="CLOSING",e[e.TIMEOUT=5]="TIMEOUT",e[e.CONNECTING=6]="CONNECTING"}(sn||(sn={}));const cn="open",un="close",dn="error",ln="send",hn="message",pn="timeout",mn="reconnecting";var fn=class extends $e{constructor(e,t){var r;super(!0),Le(this,e),this.native||(this.native=WebSocket),this.status=sn.NONE,this.queue=[],this.isReconnect=!1,e.retryCount>0&&(this.retryIndex=0),this.logger=t||new ur,this.logLevel=null!==(r=this.logLevel)&&void 0!==r?r:this.logger.TRACE,this.connectCount=0}isOpen(){return this.status===sn.OPEN}isConnecting(){return this.status===sn.CONNECTING}getStatus(){return this.status}connect(e,t){const r=this;if(this.server=e,this.proxys=t,this.connectCount=0,r.status===sn.OPEN||r.status===sn.CONNECTING||r.status===sn.CLOSING)return;let i=[e];t&&t.length&&(i=i.concat(t));let n=-1;const s=function(){r.nextStartTimer=null,r.status===sn.CONNECTING?function(e,t){r.connectCount++;let i=r.nativeOptions;r.native===WebSocket&&(i=r.nativeOptions.protocols),r.logger.debug(`${r.tag||"Transport"} connecting url: ${e.url}`);const n=J(),s=new r.native(e.url,i);let a,c=function(r){a&&clearTimeout(a),s.onopen=s.onerror=null,t(s,e,r)};s.onopen=function(e){var t;r.consume=null!==(t=null==e?void 0:e.consume)&&void 0!==t?t:J()-n,c(sn.OPEN)},s.onerror=function(){c(sn.ERROR)},r.timeout>0&&(a=setTimeout((function(){a=null,s.onerror=null,s.onopen=null,o.d(s.close)&&s.close(),c(sn.TIMEOUT)}),r.timeout))}(i[++n],(function(e,s,c){if(r.status===sn.CONNECTING)if(c===sn.OPEN){if(r.url=s.url,r.socket=e,r.status=sn.OPEN,e.onmessage=function(e){r.status===sn.OPEN&&(r.logger.log(`${r.tag||"Transport"} Received: ${o.i(e.data)?e.data:"binary"}`,r.logLevel),r.onReceive&&o.i(e.data)&&r.onReceive(JSON.parse(e.data)),r.onmessage&&r.onmessage(e.data),r.fire(hn,[e.data]))},e.onclose=function(i){if(r.status===sn.OPEN)if(r.connectOnClose&&r.retryCount>0){if(r.status=sn.NONE,r.onReconnecting&&(r.onReconnecting(),r.status===sn.CLOSING||r.status===sn.CLOSE))return;r.fire(mn),r.isReconnect=!0,r.logger.warn((r.tag||"Transport")+" reconnecting"),e.clear&&e.clear(),r.connect(s,t)}else r.onClose&&r.onClose(i),r.fire(un,[i])},r.retryCount>0&&(r.retryIndex=0),r.onOpen&&(r.logger.debug(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} success`),r.onOpen({server:s,reconnect:r.isReconnect})),r.fire(cn,[{server:s,reconnect:r.isReconnect}]),r.queue.length)for(;r.queue.length;){const t=r.queue.shift(),i=o.i(t)||o.b(t)?t:JSON.stringify(t);e.send(i),r.logger.log(`${r.tag||"Transport"} Sent: ${o.b(t)?"binary":i}`,r.logLevel),r.onSend&&r.onSend(i),r.fire(ln,[i])}}else if(n===i.length-1){if(r.retryCount>0&&r.retryIndex++<r.retryCount-1)return n=-1,void a();switch(r.status=c){case sn.ERROR:r.logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} error`),r.onError&&r.onError({server:s}),r.fire(dn,[{server:s}]);break;case sn.TIMEOUT:r.logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} timeout`),r.onTimeout&&r.onTimeout({server:s}),r.fire(pn,[{server:s}])}}else a();else if(r.status===sn.CLOSING){let t=!1;if(c===sn.OPEN&&r.refreshQueueOnClose&&r.queue.length){for(;r.queue.length;){const t=r.queue.shift(),i=o.i(t)||o.b(t)?t:JSON.stringify(t);e.send(i),r.logger.log(`${r.tag||"Transport"} Sent: ${o.b(t)?"binary":i}`,r.logLevel),r.onSend&&r.onSend(i),r.fire(ln,[i])}t=!0}t?setTimeout((()=>{e.close(),r.status=sn.CLOSE}),1e3):(e.close(),r.status=sn.CLOSE)}})):r.status===sn.CLOSING&&(r.status=sn.CLOSE)},a=function(){r.interval>0?r.nextStartTimer=setTimeout(s,r.interval):s()};r.status=sn.CONNECTING,s()}send(e){if(this.status!==sn.OPEN&&this.status!==sn.CLOSING)return this.queueMax>0&&this.queue.length===this.queueMax&&this.queue.shift(),void this.queue.push(e);const t=this.socket;if(t){const r=o.i(e)||o.b(e)?e:JSON.stringify(e);t.send(r),this.logger.log(`${this.tag||"Transport"} Sent: ${o.b(e)?"binary":r}`,this.logLevel),this.onSend&&this.onSend(r),this.fire(ln,[r])}}close(){const e=this.socket;if(this.socket=null,this.status=sn.CLOSING,e){let t=!1;if(this.refreshQueueOnClose&&this.queue.length){for(;this.queue.length;)this.send(this.queue.shift());t=!0}e.onmessage=e.onclose=null,t?setTimeout((()=>{e.close(),this.status=sn.CLOSE}),1e3):(e.close(),this.status=sn.CLOSE)}this.nextStartTimer&&(clearTimeout(this.nextStartTimer),this.nextStartTimer=null)}reconnect(){this.status!==sn.CONNECTING&&(this.close(),this.status===sn.CLOSING?setTimeout((()=>{this.status=sn.CLOSE,this.connect(this.server,this.proxys)}),1e3):this.connect(this.server,this.proxys))}getSocket(){return this.socket}getConsume(){return Math.max(this.consume||0,0)}getConnectCount(){return this.connectCount}},gn=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};let vn,yn,_n,bn,Sn=[],In=60,En=180,Tn=10,Rn=0,wn=0;const An={sniffer:function(e){const t=Q();return{result:{receiver:e,send:t,costTime:Math.max(t-e,0)}}}};function kn(){!vn||!Sn.length||Rn>=Tn||function(){return gn(this,void 0,void 0,(function*(){if(!Sn.length||Rn>=Tn)return;const e=Sn[wn++];wn>=Sn.length&&(wn=0,Rn++);let t=!1;pe.info("start run probe task, server: "+JSON.stringify(e));const r=new Hi(15);return Promise.race([r,new Promise(((i,n)=>{const s=new fn({tag:`Probe ${e.address} ${e.location}`,retryCount:0,connectOnClose:!1,onClose:()=>{s.close(),yn=null,!t&&bn&&bn(9002,"probe failed",e),i(0)},onError:r=>{s.close(),yn=null,!t&&bn&&bn(9002,"probe failed",e),n(r)},onOpen:()=>{t=!0,r.reset(In)},native:an,nativeOptions:{processOffer:function(e,t){return gn(this,void 0,void 0,(function*(){return rn(e,{style:1,platform:"Web",session:{type:"offer",sdp:t}}).then((e=>{if(0===(null==e?void 0:e.code)&&e.data)return e.data.sdp}))}))},ordered:!1},logLevel:pe.DEBUG});s.onmessage=e=>gn(this,void 0,void 0,(function*(){if(e&&o.i(e)){const t=Q();try{const r=JSON.parse(e);if(An[null==r?void 0:r.method]){let e=yield An[r.method](t);e=Le({id:r.id,version:"2.0"},e),s.send(JSON.stringify(e))}}catch(e){}}})),yn=s,s.connect({url:e.address})}))]).then((r=>(yn&&(yn.close(),yn=null),r&&!t&&bn&&bn(9002,"probe failed",e),pe.info("end run probe task success, server: "+JSON.stringify(e)),r))).catch((t=>{yn&&(yn.close(),yn=null),pe.info("end run probe task error, server: "+JSON.stringify(e))}))}))}().then((()=>gn(this,void 0,void 0,(function*(){yield new Hi(En),kn()}))))}function Cn(){_n&&_n().then((e=>{if(e.data){const t=e.data.urls;o.f(e.data.duration)&&(In=e.data.duration),o.f(e.data.intervalDataChannel)&&(En=e.data.intervalDataChannel),o.f(e.data.maxLoopNum)&&(Tn=e.data.maxLoopNum),o.a(t)&&(Sn=t,pe.info(`run probe task, duration: ${In}, intervalDataChannel: ${En}, maxLoopNum: ${Tn}`),kn())}})).catch((e=>{vn=!1,yn&&(yn.close(),yn=null),Rn=0,wn=0,Sn=[]}))}function Mn(){return!!(ut.chrome&&ut.checkVersion(ut.majorVersion,"69")||ut.firefox&&ut.checkVersion(ut.majorVersion,"46")||ut.newEdge&&ut.checkVersion(ut.majorVersion,"80"))||It.a.isSmallStreamSupported()}var On=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const Pn={heartbeat:15e3,requestTimeout:15e3,maxRetry:3,packer:fr,retryInterval:500,connectTimeout:1e4,connectOnClose:!0,requestMaxRetry:0};class Ln extends $e{constructor(e,t,r,i){var n,s;super(!0),this.server=e,this.proxys=r,this.options=Le({},Pn,t),this.logger=i||new ur,this.heartbeatTimer=new lt((()=>{this.heartbeat()}),this.options.heartbeat,this.options.heartbeat),this.packer=new this.options.packer,this.transport=new fn({native:null!==(n=this.options.transport)&&void 0!==n?n:WebSocket,onSend:e=>{this.fire("onsend",[e])},onReceive:e=>{this.fire("onreceive",[e])},onOpen:e=>{this.fire(e.reconnect?"reconnected":"connected"),this.heartbeatTimer&&this.heartbeatTimer.start()},onClose:()=>{this.fire("close"),this.heartbeatTimer&&this.heartbeatTimer.stop()},onError:()=>{this.fire("error"),this.heartbeatTimer&&this.heartbeatTimer.stop()},onTimeout:()=>{this.fire("timeout"),this.heartbeatTimer&&this.heartbeatTimer.stop()},onReconnecting:()=>{this.fire("reconnecting"),this.heartbeatTimer&&this.heartbeatTimer.stop()},connectOnClose:this.options.connectOnClose,retryCount:this.options.maxRetry,nativeOptions:null!==(s=this.options.transportOptions)&&void 0!==s?s:{},tag:this.options.tag,interval:this.options.retryInterval,timeout:this.options.connectTimeout,logLevel:this.options.logLevel},this.logger),this.rpc=new mr(this.packer,this.transport,{requestTimeout:this.options.requestTimeout,responseTimeout:this.options.requestTimeout,peerId:this.options.peerId,maxRetry:this.options.requestMaxRetry},this.logger),this.rpc.on("binary",(e=>{this.fire("binary",[e])})),this.rpc.on(dr,((e,t,r)=>{this.fire(dr,[e,t,r])})),this.rpc.on("request",(e=>{this.fire("request",[e])})),Object(z.a)((()=>{this.transport&&this.transport.connect(this.server,this.proxys)}))}request(e,t={},r){return On(this,void 0,void 0,(function*(){return this.rpc.request(e,t,r)}))}reply(e,t,r){return this.rpc.reply(e,t,r)}notify(e,t={}){return this.rpc.notify(e,t)}sendBinary(e){const t=this.transport.getSocket();t&&t.send(e)}getConsume(){return this.transport?this.transport.getConsume():0}getTransportConnectCount(){return this.transport?this.transport.getConnectCount():0}getTransportStatus(){return this.transport?this.transport.getStatus():sn.NONE}destroy(){this.off(),this.rpc&&this.rpc.destroy(),this.transport&&this.transport.close(),this.transport=null,this.rpc=null,this.packer=null,this.heartbeatTimer&&this.heartbeatTimer.destroy(),this.heartbeatTimer=null}resetRequest(){this.rpc&&this.rpc.resetRequest()}changeTransport(e){var t;this.transport&&(this.transport.onSend=this.transport.onReceive=this.transport.onOpen=this.transport.onClose=this.transport.onError=this.transport.onTimeout=this.transport.onReconnecting=null,this.transport.close(),e.onSend=e=>{this.fire("onsend",[e])},e.onReceive=e=>{this.fire("onreceive",[e])},e.onOpen=e=>{this.fire(e.reconnect?"reconnected":"connected"),this.heartbeatTimer&&this.heartbeatTimer.start()},e.onClose=()=>{this.fire("close"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.onError=()=>{this.fire("error"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.onTimeout=()=>{this.fire("timeout"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.onReconnecting=()=>{this.fire("reconnecting"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.connectOnClose=this.options.connectOnClose,e.retryCount=this.options.maxRetry,e.nativeOptions=null!==(t=this.options.transportOptions)&&void 0!==t?t:{},e.tag=this.options.tag,e.interval=this.options.retryInterval,e.timeout=this.options.connectTimeout,e.logLevel=this.options.logLevel,this.transport=e,this.rpc&&this.rpc.setTransport(e))}getLogger(){return this.logger}}var xn=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class Dn extends Ln{constructor(e,t,r,i){super({url:e},t,null,i),this.notified=-1,this.seq=0,this.sessionId=null,this.syncRoomLock=!1,this.retryQueue=[],this.proxy=r}resetTimeout(){this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout((()=>{this.resetTimer=null,this.fire("timeout"),this.destroy()}),4*this.options.heartbeat)}syncNotify(){return xn(this,void 0,void 0,(function*(){this.fire("session-close")}))}request(e,t,r){const i=Object.create(null,{request:{get:()=>super.request}});return xn(this,void 0,void 0,(function*(){const n=this.seq++;return this.syncRoomLock&&"syncRoom"!==e?(this.logger.warn(`session closed, waiting for sync room, method: ${e}, params: ${JSON.stringify(t)}`),new Promise(((r,i)=>{this.retryQueue.push({method:e,params:t,resolve:r,reject:i,id:n})}))):(this.syncRoomLock||"syncRoom"!==e||(this.syncRoomLock=!0),i.request.call(this,e,t,r).then((t=>(this.resetTimeout(),!this.sessionId&&t.sessionId&&(this.sessionId=t.sessionId),"syncRoom"===e&&(this.syncRoomLock=!1,this.retryQueue.length&&(this.retryQueue=this.retryQueue.filter((e=>"recover"!==e.method)),this.retryQueue.sort(((e,t)=>e.id-t.id)),ye(this.retryQueue,(e=>{e.params.sessionId=this.sessionId,this.logger.info(`retry the retryQueue request, ${e.method}, params: ${JSON.stringify(e.params)}`),this.request(e.method,e.params).then((t=>{e.resolve(t)})).catch((t=>{e.reject(t)}))})),this.retryQueue=[])),t))).catch((r=>{if("request timeout"!==dt(r)&&this.resetTimeout(),99===(null==r?void 0:r.code))return this.sessionId&&this.sessionId!==t.sessionId?(this.logger.warn(`the request session has closed but the seesion is update after sync room, retry request again, ${e}, params: ${JSON.stringify(t)}`),t.sessionId=this.sessionId,this.request(e,t)):(this.syncRoomLock||(this.sessionId=null,this.syncRoomLock=!0,this.fire("session-close")),this.logger.warn(`the session has closed, push the request into retry queue, ${e}, params: ${JSON.stringify(t)}`),new Promise(((r,i)=>{this.retryQueue.push({method:e,params:t,resolve:r,reject:i,id:n})})));throw r})))}))}heartbeat(){this.request("ping",{sessionId:this.sessionId}).then((e=>{this.resetTimeout()})).catch((e=>{this.logger.error("channel heartbeat error: "+JSON.stringify(e))}))}destroy(){this.seq=null,this.notified=null,this.sessionId=null,this.retryQueue=null,this.syncRoomLock=null,this.resetTimer&&(clearTimeout(this.resetTimer),this.resetTimer=null),super.destroy()}getProxy(){return this.proxy}updateProxy(e){this.proxy=e}}var Nn=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function $n(e){return Ne(e)||""}function Un(e,t){return"application/x-www-form-urlencoded"===e?$n(t):"multipart/form-data"===e?function(e){const t=new FormData;return e&&Oe(e,((e,r)=>{t.append(encodeURIComponent(r),encodeURIComponent(e))})),t}(t):JSON.stringify(t)}function Bn(e,t,r,i={}){return Nn(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{let a=0;!function c(){return Nn(this,void 0,void 0,(function*(){a++;try{const s={Accept:"application/json","Content-Type":r||"application/json"};Oe(i,((e,t)=>{s[t]=e}));let a=null,c=null;AbortController&&(c=new AbortController,a=c.signal);const u=yield Promise.race([fetch(e,{body:Un(r,t),cache:"no-cache",credentials:"same-origin",headers:s,method:"POST",mode:"cors",redirect:"follow",referrer:"no-referrer",signal:a}),new Hi(8)]);if(o.f(u))throw c&&c.abort(),new Error(`fetch ${e}, data: ${JSON.stringify(t)} timeout`);n(u.json())}catch(e){a<3?(yield new Hi(1),c()):s(e)}}))}()}))}))}const Vn={joinUser:"peer-joined",leaveUser:"peer-leaved",roomClosed:"room-closed",roomError:"error",updateStats:"update-stats",updateUser:"peer-update",publishStream:"stream-added",unpublishStream:"stream-removed",onIceCandidate:"ice-candidate",streamUpdate:"stream-update",streamError:"stream-error",streamDisconnected:"stream-disconnected",evicted:"evicted",userRejoined:"peer-rejoined",tokenWillExpire:"token-will-expire",tokenExpire:"token-expire",changeSignalNode:"server-proxy-change",rebuildMediaRelation:"media-server-changed"};class Fn{constructor(e,t){this.data=new t(e),this.valid=0,this.tail=0,this.length=0,this.pos=0,this.size=e,this.constructorFunction=t}write(e){const t=e.length;if(!(t>this.size)){if(this.tail+t>this.size){const r=this.size-this.tail,i=t-r;this.data.set(e.subarray(0,r),this.tail),this.data.set(e.subarray(r),0),this.tail=i}else this.data.set(e,this.tail),this.tail+=t;if(this.length+t>this.size){const e=this.length+t-this.size;if(this.valid+e>this.size){const t=e-(this.size-this.valid);this.valid=t}else this.valid+=e;this.length=this.size}else this.length+=t}}read(e){if(0===this.length)return;e>this.length&&(e=this.length);const t=new this.constructorFunction(e);if(this.valid+e>this.size){const r=this.size-this.valid,i=e-r;t.set(this.data.subarray(this.valid,this.valid+r),0),t.set(this.data.subarray(0,i),r),this.valid=i}else t.set(this.data.subarray(this.valid,this.valid+e),0),this.valid+=e;return this.length-=e,this.pos+=e,t}readByRange(e,t){if(e<=t){const r=new this.constructorFunction(t-e);return r.set(this.data.subarray(e,t),0),r}{const r=new this.constructorFunction(this.size-e+t);return r.set(this.data.subarray(e),0),r.set(this.data.subarray(0,t),this.size-e),r}}getCurrentPointer(){return this.valid}readByte(){if(this.length>0){let e;return this.valid>=this.size?(this.valid=1,e=this.data[0]):e=this.data[this.valid++],this.length-=1,this.pos+=1,e}}getByteByIndex(e){if(this.length>e){let t;if(this.valid+e>=this.size){const r=e-(this.size-this.valid);t=this.data[r]}else t=this.data[this.valid+e];return t}}getSize(){return this.size}getLength(){return this.length}getPos(){return this.pos}getRemainingSize(){return this.size-this.length}back(e){e>this.size-this.length?(this.pos-=this.size-this.length,this.valid=this.tail,this.length=this.size):(this.valid<e?this.valid=this.size-(e-this.valid):this.valid-=e,this.length+=e,this.pos-=e)}skip(e){this.length<e?(this.valid=this.tail=0,this.pos+=this.length,this.length=0):(this.valid+e>this.size?this.valid=e-(this.size-this.valid):this.valid+=e,this.length-=e,this.pos+=e)}clear(){this.valid=this.tail=this.length=this.pos=0}}var jn;!function(e){e[e.COLON=58]="COLON",e.COLON_CHAR=":",e[e.COMMA=44]="COMMA",e.COMMA_CHAR=",",e[e.SPACE=32]="SPACE",e.SPACE_CHAR=" "}(jn||(jn={}));class Wn{constructor(e){this.options=e,this.ringBuffer=new Fn(e.bufferSize,Uint8Array)}isDigit(e){return e>=48&&e<=57}static encode(e,t){const r=o.f(t)&&t>=0?`${e.length+`${t}${jn.SPACE_CHAR}`.length}${jn.COLON_CHAR}${t}${jn.SPACE_CHAR}`:`${e.length}${jn.COLON_CHAR}`,i=new Uint8Array(r.length+e.length+1);let n;for(n=0;n<r.length;n++)i[n]=r.charCodeAt(n);return i.set(e,n),i[n+e.length]=jn.COMMA,i}decode(e){e&&this.ringBuffer.write(e);let t=0,r=0,i=this.ringBuffer.getCurrentPointer();if(this.ringBuffer.getLength()>=3){if(48===this.ringBuffer.getByteByIndex(0)&&this.isDigit(this.ringBuffer.getByteByIndex(1)))throw new Error("find leading zeros!");if(!this.isDigit(this.ringBuffer.getByteByIndex(0)))throw new Error("the netstring must start with a number");for(;this.ringBuffer.getLength()&&this.isDigit(this.ringBuffer.getByteByIndex(0));){if(r>9)throw new Error("length is more than 9 digits");t=10*t+(this.ringBuffer.readByte()-48),r++}if(!this.ringBuffer.getLength())return void this.ringBuffer.back(r);if(this.ringBuffer.readByte()!==jn.COLON)throw new Error("miss the colon");if(r++,t+1<=this.ringBuffer.getLength()){let e=0,r=t;if(this.options.enableCommand){for(;this.ringBuffer.getLength()&&this.isDigit(this.ringBuffer.getByteByIndex(0));)e=10*e+(this.ringBuffer.readByte()-48),r--;if(this.ringBuffer.readByte()!==jn.SPACE)throw new Error("miss the space");r--}if(this.ringBuffer.getByteByIndex(r)!==jn.COMMA)throw new Error("miss the comma");const n=this.ringBuffer.read(r);this.ringBuffer.skip(1);const s=this.ringBuffer.readByRange(i,this.ringBuffer.getCurrentPointer());this.options.onDecodeText&&this.options.onDecodeText(this,{payload:n,serialized:s,cmd:this.options.enableCommand?e:void 0}),this.decode()}else this.ringBuffer.back(r)}}destroy(){this.ringBuffer=null,this.options=null}}const qn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Gn(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");let t,r,i,n,s,o,a,c=0,u=0;for(;e.length%4;)e+="=";const d=new Uint8Array(.75*e.length);for(;c<e.length;)t=qn.indexOf(e.charAt(c++)),r=qn.indexOf(e.charAt(c++)),i=qn.indexOf(e.charAt(c++)),n=qn.indexOf(e.charAt(c++)),s=t<<2|r>>4,o=(15&r)<<4|i>>2,a=(3&i)<<6|n,d[u++]=s,64!==i&&(d[u++]=o),64!==n&&(d[u++]=a);return d}const Hn={};ye(["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"],((e,t)=>{Hn[e]=t}));class zn{constructor(e){this.count=e,this.queue=[]}push(e){this.queue.push(e),this.queue.length>this.count&&this.queue.shift()}clear(){this.queue.length=0}isFull(){return this.queue.length===this.count}getValue(){if(!this.queue.length)return 0;let e=0;for(let t=0;t<this.queue.length;t++)e+=this.queue[t];return e/this.queue.length}}function Jn(e,t,r){return e<t?e=t:e>r&&(e=r),e}var Yn=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const Kn={mode:"text",enableCommand:!1,binaryCommand:19,pingCommand:1,pingAckCommand:2,streamCount:1,textCommandStart:20,textCommandEnd:Math.pow(2,31)-1,commandTimeout:3e4,bufferSize:1048576,enablePing:!1,pingInterval:5e3};class Qn{constructor(e,t={}){this.url=e,this.options=Le({},Kn,t),t.textDecoder?this.textDecoder=t.textDecoder:o.d(TextDecoder)?this.textDecoder=new TextDecoder:"text"===this.options.mode&&pe.warn("has not textDecoder to use, support binary only"),t.textEncoder?this.textEncoder=t.textEncoder:o.d(TextEncoder)&&"text"===this.options.mode?this.textEncoder=new TextEncoder:"text"===this.options.mode&&pe.warn("has not textEncoder to use, support binary only"),this.textCommandPointer=this.options.textCommandStart,this.commandMap=new Map,this.pingStartTimestamp=new Map,this.commandQueue=[],this.streams=[],this.readers=[],this.writers=[],this.streamReaderMap=new Map,this.streamWriterMap=new Map,this.netStrings=[],this.currentWriteStreams=1,this.rtt=new zn(5),"stream"===this.options.mode&&(this.options.streamCount=1),this.options.streamCount>1&&(this.options.enableCommand=!0),this.options.enablePing&&(this.pingTimer=new lt((()=>{this.ping()}),1e3,this.options.pingInterval)),this.connect().catch((e=>{pe.error(`WebTransportWS connect error because of error: ${e}, url: ${this.url}`),this.onerror&&H(this.onerror,this,[e]),this.pingTimer&&this.pingTimer.stop()}))}read(e,t){return Yn(this,void 0,void 0,(function*(){"text"===this.options.mode&&(this.netStrings[t]=new Wn({bufferSize:this.options.bufferSize,onDecodeText:this.onDecodeMessage.bind(this),enableCommand:this.options.enableCommand,index:t}));let r=!1;for(;;)try{const{value:i,done:n}=yield e.read();if(n){r=n;break}if("text"===this.options.mode)try{this.netStrings[t].decode(i)}catch(e){pe.error("decode message error, "+e),this.onclose&&H(this.onclose,this,[new Error("decode message error")]);break}else this.onmessage&&H(this.onmessage,this,[{data:i.buffer}])}catch(e){r||pe.error("read data error, "+e);break}Ie(this.readers,e),this.readers.length||this.onclose&&H(this.onclose,this,[new Error("readableStream closed")])}))}handleRead(){ye(this.readers,((e,t)=>{this.read(e,t)}))}readDatagram(){return Yn(this,void 0,void 0,(function*(){let e=!1;for(;;)try{const{value:t,done:r}=yield this.datagramReader.read();if(r){e=!0;break}try{this.onDatagramMessage(t)}catch(e){pe.error("parse datagram data error, "+e)}}catch(t){e||pe.error("read datagram data error, "+t);break}}))}connect(){return Yn(this,void 0,void 0,(function*(){const e={};o.c(this.options.allowPooling)&&(e.allowPooling=this.options.allowPooling),o.a(this.options.serverCertificateHashes)&&(e.serverCertificateHashes=[],ye(this.options.serverCertificateHashes,(t=>{o.i(t.value)?e.serverCertificateHashes.push({algorithm:t.algorithm,value:Gn(t.value)}):e.serverCertificateHashes.push({algorithm:t.algorithm,value:t.value})}))),this.transport=new WebTransport(this.url.replace(/^webtransport:/,"https:"),e),this.transport.closed.then((()=>{pe.info("WebTransportWS closed gracefully, url: "+this.url),this.onclose&&H(this.onclose,this,[{}]),this.pingTimer&&this.pingTimer.stop()})).catch((e=>{pe.error(`WebTransportWS closed because of error: ${e}, url: ${this.url}`),this.onerror&&H(this.onerror,this,[e]),this.onclose&&H(this.onclose,this,[e]),this.pingTimer&&this.pingTimer.stop()}));const t=J();yield this.transport.ready;const r=J()-t;this.datagramReader=this.transport.datagrams.readable.getReader(),this.datagramWriter=this.transport.datagrams.writable.getWriter();const i=yield this.transport.createBidirectionalStream(),n=i.readable.getReader(),s=i.writable.getWriter();this.streams.push(i),this.readers.push(n),this.writers.push(s),this.streamReaderMap.set(i,n),this.streamWriterMap.set(i,s),yield Promise.all(this.writers.map((e=>e.ready))),this.handleRead(),this.options.enablePing&&this.readDatagram(),this.onopen&&H(this.onopen,this,[{consume:r}]),this.pingTimer&&this.pingTimer.start()}))}getTextCommand(){if(this.options.enableCommand){const e=this.textCommandPointer++;return this.textCommandPointer>this.options.textCommandEnd&&(this.textCommandPointer=this.options.textCommandStart),e}return-1}createPacket(e,t){const r=new Uint8Array(1+t.length);return r[0]=e,r.set(t,1),r}ping(){if(this.datagramWriter){const e=J(),t=new Float64Array(1);t[0]=e,this.pingStartTimestamp.set(e,setTimeout((()=>{this.pingStartTimestamp.delete(e);const t=J()-e;this.rtt.push(t),o.d(this.options.onPing)&&this.options.onPing(this,t)}),5e3));try{this.datagramWriter.write(this.createPacket(this.options.pingCommand,new Uint8Array(t.buffer)))}catch(e){pe.error("send ping error, "+e),this.pingTimer&&this.pingTimer.stop()}}}onDatagramMessage(e){if(!e.length)return;const t=e[0],r=e.slice(1);if(t===this.options.pingAckCommand){const e=new Float64Array(r.buffer);if(this.pingStartTimestamp.has(e[0])){clearTimeout(this.pingStartTimestamp.get(e[0]));const t=J()-e[0];this.rtt.push(t),this.pingStartTimestamp.delete(e[0]),o.d(this.options.onPing)&&this.options.onPing(this,t)}}else t===this.options.pingCommand?(e[0]=this.options.pingAckCommand,this.datagramWriter.write(e)):this.onmessage&&this.onmessage&&H(this.onmessage,this,[{data:r}])}onDecodeMessage(e,t){if(t.cmd>=this.options.textCommandStart&&t.cmd<=this.options.textCommandEnd||t.cmd===this.options.binaryCommand)if(this.options.streamCount>1){if(this.commandMap.get(t.cmd))return;for(this.onmessage&&H(this.onmessage,this,[{data:t.cmd!==this.options.binaryCommand&&this.textDecoder?this.textDecoder.decode(t.payload):t.payload.buffer}]),this.commandMap.set(t.cmd,!0),this.commandQueue.push({cmd:t.cmd,timestamp:J()});this.commandQueue.length&&J()-this.commandQueue[0].timestamp>this.options.commandTimeout;)this.commandMap.delete(this.commandQueue[0].cmd),this.commandQueue.shift()}else this.onmessage&&H(this.onmessage,this,[{data:t.cmd!==this.options.binaryCommand&&this.textDecoder?this.textDecoder.decode(t.payload):t.payload.buffer}]);else Ce(t.cmd)||this.onmessage&&H(this.onmessage,this,[{data:this.textDecoder?this.textDecoder.decode(t.payload):t.payload.buffer}])}send(e){if(o.b(e))return void this.sendBinary(e);if(!this.writers.length)return void pe.error("can not send data because of no writer in WebTransportWS");const t=o.i(e)?e:JSON.stringify(e);try{const e=Wn.encode(this.textEncoder.encode(t),this.getTextCommand());ye(this.writers,(t=>{t.write(e)}))}catch(e){pe.error("send data error, "+e),this.onclose&&H(this.onclose,this,[e]),this.pingTimer&&this.pingTimer.stop()}}sendBinary(e){const t=new Uint8Array(e);try{ye(this.writers,(e=>{e.write("text"===this.options.mode?Wn.encode(t,this.options.binaryCommand):t)}))}catch(e){pe.error("send binary data error, "+e),this.onclose&&H(this.onclose,this,[e]),this.pingTimer&&this.pingTimer.stop()}}getCurrentWriteStreams(){return this.currentWriteStreams}setCurrentWriteStreams(e){return Yn(this,void 0,void 0,(function*(){if(!(this.options.streamCount<2))if(this.currentWriteStreams=Jn(e,1,this.options.streamCount),this.currentWriteStreams<this.streams.length){for(let e=this.currentWriteStreams;e<this.streams.length;e++){const t=this.streams[e],r=this.streamReaderMap.get(t),i=this.streamWriterMap.get(t);r&&(yield r.cancel(),Ie(this.readers,r),this.streamReaderMap.delete(t)),i&&(yield i.close(),Ie(this.writers,i),this.streamWriterMap.delete(t))}this.netStrings=this.netStrings.slice(0,this.currentWriteStreams),this.streams=this.streams.slice(0,this.currentWriteStreams)}else if(this.currentWriteStreams>this.streams.length)for(let e=this.streams.length;e<this.currentWriteStreams;e++){const t=yield this.transport.createBidirectionalStream(),r=t.readable.getReader(),i=t.writable.getWriter();this.read(r,e),yield i.ready,this.streams.push(t),this.readers.push(r),this.writers.push(i),this.streamReaderMap.set(t,r),this.streamWriterMap.set(t,i)}}))}getRTT(){return this.rtt.getValue()}close(){this.readers.forEach((e=>{e.cancel()})),this.datagramReader&&this.datagramReader.cancel(),this.transport&&(this.transport.close(),this.transport=null),this.netStrings&&(ye(this.netStrings,(e=>{e.destroy()})),this.netStrings=[]),this.pingTimer&&(this.pingTimer.destroy(),this.pingTimer=null),this.textEncoder&&(this.textEncoder=null),this.textDecoder&&(this.textDecoder=null),this.pingStartTimestamp&&(this.pingStartTimestamp.forEach((e=>{clearTimeout(e)})),this.pingStartTimestamp.clear(),this.pingStartTimestamp=null),this.commandMap&&this.commandMap.clear(),this.streams=[],this.readers=[],this.writers=[],this.datagramReader=null,this.commandQueue=[],this.streamReaderMap.clear(),this.streamWriterMap.clear()}clear(){this.close()}}var Xn,Zn=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const es={enableRace:!0,forceWS:!1,forceDC:!1,forceWT:!1},ts="function"==typeof(null===(Xn=G.e)||void 0===Xn?void 0:Xn.WebTransport)&&ut.chrome&&ut.checkVersion(ut.majorVersion,"97",!0);let rs=[];class is extends $e{constructor(e,t,r={},i){super(!1),this.options=Le({},es,t),this.closed=!1,this.icefull=!1,this.isConnecting=!1,this.connectCount=0,this.isLeaving=!1,this.rpc=r,this.logger=i||new ur,this.proxies=this.preprocessProxy(e)}preprocessProxy(e){return e=e.map((e=>{if(e.wturl&&e.url){const t=xe(e,!0),r=xe(e,!0);return t.wturl="",r.url="",[r,t]}return[xe(e,!0)]})).reduce(((e,t)=>e.concat(t)),[]),ts||(e=e.filter((e=>!e.wturl))),e}isDataChannel(e){return 0!==e.indexOf("wss:")&&0!==e.indexOf("ws:")}isWebTransport(e){return 0===e.indexOf("webtransport:")}getTransport(e){return this.isWebTransport(e)?Qn:this.isDataChannel(e)?an:null}getTransportOptions(e){return this.isWebTransport(e)?{enableCommand:!0,textCommand:1,streamCount:2,autoStream:!0,enablePing:!0,onPing:(e,t)=>{t>160?e.setCurrentWriteStreams(2):e.setCurrentWriteStreams(e.getRTT()<60?1:2)}}:this.isDataChannel(e)?{processOffer:(e,t)=>Zn(this,void 0,void 0,(function*(){return Bn(e,{type:"offer",sdp:t}).then((e=>e.sdp))}))}:{}}getUrl(e){return e.activeUrl=e.url||e.dcurl||e.wturl,ts&&this.options.enableWT&&!this.options.forceWS&&e.wturl&&(e.activeUrl=e.wturl),o.h(e.suffix)?function(e,t,r){null==r&&(r=document.URL);let i=function(e){var t;const r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],i={},n=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e);let s=14;for(;s--;)i[r[s]]=null!==(t=n[s])&&void 0!==t?t:"";return{protocol:i.protocol,file:i.file,host:i.host,port:i.port,user:i.user,password:i.password,origin:`${i.protocol}://${i.authority}`,pathname:i.path,search:"?"+i.query,hash:i.anchor?"#"+i.anchor:""}}(r),n=oi(t?i.hash:i.search);return Le(n,e),n=Ne(n),r=i.origin+i.pathname,t?r+=i.search:n&&(r+="?"+n),t?n&&(r+="#"+n):r+=i.hash,r}(e.suffix,!1,e.activeUrl):e.activeUrl}raceConnect(){return Zn(this,void 0,void 0,(function*(){let e=rs.concat(this.proxies);if(this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}else if(this.options.forceDC){const t=e.filter((e=>!!e.dcurl));t.length&&(e=t)}else if(this.options.forceWT&&ts&&this.options.enableWT){const t=e.filter((e=>!!e.wturl));t.length&&(e=t)}if(!this.options.enableWT){const t=e.filter((e=>!e.wturl||!!e.url));t.length&&(e=t)}this.connectingTimers={};const t=".connecting"+Math.random();return new Promise(((r,i)=>{let n=!1;this.connectCount=0;const s=(e,s)=>{n?e.destroy():this.closed?(Oe(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.warn("signal open after call close function, reject"),i("signal has already closed")):(n=!0,Oe(this.connectingTimers,((e,t)=>{clearTimeout(e.timer),e.channel&&t!=s&&e.channel.destroy()})),this.connectingTimers={},e.off(t),this.connectCount=e.getTransportConnectCount(),r(e))};let o=0;const a=()=>{++o===e.length&&(Oe(this.connectingTimers,(e=>{e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.error("connect all proxies failed"),i("connect all proxies failed"))},c=(e,r)=>{const i=new Dn(e,{maxRetry:5,transport:this.getTransport(e),transportOptions:this.getTransportOptions(e),tag:"Signal",logLevel:pe.DEBUG},r,this.logger);i.one("connected"+t,(()=>{r.consume=i.getConsume(),this.connectCount=i.getTransportConnectCount(),s(i,e)})).one("reconnected"+t,(()=>{r.consume=i.getConsume(),this.connectCount=i.getTransportConnectCount(),s(i,e)})).one("error"+t,(()=>{this.connectCount=i.getTransportConnectCount(),a()})).one("timeout"+t,(()=>{this.connectCount=i.getTransportConnectCount(),a()})),this.connectingTimers[e].channel=i};ye(e,(e=>{const t=e.delay?tt(e.delay):0,r=this.getUrl(e);this.connectingTimers[r]={timer:setTimeout((()=>{c(r,e)}),t)}}))}))}))}queueConnect(){return Zn(this,void 0,void 0,(function*(){let e=rs.concat(this.proxies);if(this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}else if(this.options.forceDC){const t=e.filter((e=>!!e.dcurl));t.length&&(e=t)}else if(this.options.forceWT&&ts&&this.options.enableWT){const t=e.filter((e=>!!e.wturl));t.length&&(e=t)}if(!this.options.enableWT){const t=e.filter((e=>!e.wturl||!!e.url));t.length&&(e=t)}const t=".connecting"+Math.random();return new Promise(((r,i)=>{let n=0;this.connectCount=0;const s=()=>{this.closed&&i("signal has closed");const o=e[n],a=this.getUrl(o),c=this.connectingChannel=new Dn(a,{maxRetry:3,transport:this.getTransport(a),transportOptions:this.getTransportOptions(a),tag:"Signal",logLevel:pe.DEBUG},o,this.logger);c.one("connected"+t,(()=>{c.off(t),this.connectingChannel=null,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),r(c)})).one("reconnected"+t,(()=>{c.off(t),this.connectingChannel=null,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),r(c)})).one("error"+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=null,this.logger.error(`queue connect proxy: ${n} ${a} error`),this.fire("state-notify",[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} error`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,i("connect all proxies failed")):setTimeout((()=>{s()}),1e3)})).one("timeout"+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=null,this.logger.error(`queue connect proxy: ${n} ${a} timeout`),this.fire("state-notify",[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} timeout`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,i("connect all proxies failed")):setTimeout((()=>{s()}),1e3)}))};s()}))}))}tryConnectOtherProxy(e){this.proxies.length>1?(Sr(),Ie(this.proxies,this.getProxy()),Se(this.proxies,this.getProxy()),this.logger.info("try to connect other proxies"),this.connect().then((()=>{this.fire("reconnected"),this.channel.syncNotify()})).catch((t=>{this.logger.error("connect other proxies failed"),this.fire(e)}))):this.fire(e)}tryChangeSelectedProxy(e){if(!e.length)return;if(rs=e=this.preprocessProxy(e),this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}else if(this.options.forceDC){const t=e.filter((e=>!!e.dcurl));t.length&&(e=t)}else if(this.options.forceWT&&ts&&this.options.enableWT){const t=e.filter((e=>!!e.wturl));t.length&&(e=t)}if(!this.options.enableWT){const t=e.filter((e=>!e.wturl||!!e.url));t.length&&(e=t)}let t,r=0;const i=(e,t)=>{this.closed?e.close():(this.logger.info(`change selected proxy success from proxy: ${JSON.stringify(this.channel.getProxy())} to proxy: ${JSON.stringify(t)}`),t.consume=e.getConsume(),this.channel.updateProxy(t),this.channel.changeTransport(e),this.channel.syncNotify(),this.fire("proxy-changed"))},n=i=>{this.logger.error("try change selected proxy error, proxy: "+JSON.stringify(i)),r++,r>=e.length||setTimeout((()=>{t()}),1e3)};t=()=>{if(this.closed)return;const s=e[r],o=this.getUrl(s);if(this.channel.getProxy().activeUrl===s.activeUrl)return this.logger.warn("try to change selected proxy to current, ignore, proxy "+JSON.stringify(s)),r++,r>=e.length?void 0:(r++,void t());const a=new fn({native:this.getTransport(o),nativeOptions:this.getTransportOptions(o),connectOnClose:!0,retryCount:3,interval:500,timeout:1e4,onOpen:()=>{i(a,s)},onReconnecting:()=>{i(a,s)},onClose:()=>{n(s)},onError:()=>{n(s)},onTimeout:()=>{n(s)}},this.channel.getLogger());a.connect({url:o})},t()}connect(){return Zn(this,void 0,void 0,(function*(){if(!this.proxies.length)return new Error("not has any proxy to connect");this.isConnecting=!0,this.options.enableRace?this.channel=yield this.raceConnect():this.channel=yield this.queueConnect(),this.channel.on("error",(()=>{this.logger.error("proxy connect error, proxy: "+JSON.stringify(this.getProxy())),this.fire("error")})).on("close",(()=>{this.logger.error("proxy connect close, proxy: "+JSON.stringify(this.getProxy())),this.fire("close")})).on("timeout",(()=>{this.logger.error("proxy connect timeout, proxy: "+JSON.stringify(this.getProxy())),this.fire("timeout")})).on("connected",(()=>{this.fire("connected")})).on("reconnecting",(()=>{this.fire("reconnecting")})).on("reconnected",(()=>{if(this.isLeaving)return;this.fire("reconnected"),this.channel.syncNotify();const e=this.channel.getProxy();e&&(e.consume=this.channel.getConsume())})).on(dr,((e,t,r)=>{r&&r<this.channel.notified?this.logger.warn(`skip notify: ${r}, now notified: ${this.channel.notified}, method: ${e}, params: ${JSON.stringify(t)}`):(r&&r===this.channel.notified?this.logger.warn(`repeated receive notify: ${r}, method: ${e}, params: ${JSON.stringify(t)}`):r&&this.channel.notified>-1&&r-this.channel.notified>1&&this.logger.warn(`skip to notify: ${r}, now notified: ${this.channel.notified}, method: ${e}, params: ${JSON.stringify(t)}`),this.channel.notified=r,this.channel.resetTimeout(),Vn[e]?this.fire(Vn[e],[t]):this.fire(dr,[{method:e,params:t}]))})).on("request",(e=>Zn(this,void 0,void 0,(function*(){if(this.rpc[e.method]){this.channel.resetTimeout();const{error:t,result:r}=yield this.rpc[e.method](e);this.channel.reply(e,r,t)}})))).on("session-close",(()=>{this.fire("session-close")})),this.isConnecting=!1,this.logger.info("connect proxy success, proxy: "+JSON.stringify(this.channel.getProxy()))}))}request(e,t){return Zn(this,void 0,void 0,(function*(){return this.channel.request(e,t)}))}join(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("joinRoom",e).then((e=>(this.channel.resetTimeout(),this.icefull=e.icefull,this.isLeaving=!1,e)))}))}leave(e){return Zn(this,void 0,void 0,(function*(){return this.isLeaving=!0,this.channel.request("leaveRoom",e,{timeout:3e3}).then((e=>(this.isLeaving=!1,e)))}))}evictUser(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("evictUser",e)}))}publish(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("publishStream",e)}))}unpublish(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("unpublishStream",e)}))}controlStream(e,t){return Zn(this,void 0,void 0,(function*(){return this.channel.request("controlStream",e,t)}))}subscribe(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("subscribeStream",e)}))}unsubscribe(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("unsubscribeStream",e)}))}addIceCandidate(e){return Zn(this,void 0,void 0,(function*(){return this.icefull?this.channel.request("addIceCandidate",e):Promise.resolve({})}))}syncRoom(e){return Zn(this,void 0,void 0,(function*(){return this.channel.sessionId=null,this.channel.request("syncRoom",e).then((e=>(this.icefull=e.icefull,this.channel.resetRequest(),e)))}))}setBitrate(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("setrate",e)}))}pullUsers(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("getUserList",e)}))}queryUser(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("queryUser",e)}))}getMediaServers(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("getServers",e)}))}setMediaRelation(e){return Zn(this,void 0,void 0,(function*(){return this.channel.request("setMediaRelation",e)}))}close(){this.connectingChannel&&this.connectingChannel.destroy(),Me(this.connectingTimers).length&&(Oe(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={}),this.channel&&this.channel.destroy(),this.closed=!0,this.off()}getSessionId(){var e;return null===(e=this.channel)||void 0===e?void 0:e.sessionId}getProxy(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getProxy()}getConnectCount(){return this.connectCount}getConnectedProxyConsume(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getConsume()}getConnectStatus(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getTransportStatus()}}class ns{constructor(e,t){this.userId=e,this.info=t,this.streams=new Map}getUserId(){return this.userId}getUserInfo(){return this.info}getStreams(){return this.streams}getStream(e){return this.streams.get(e)}addStream(e){this.streams.set(e.getStreamId(),e)}removeStream(e){if(!this.streams)return;const t=this.streams.get(e);return t?(this.streams.delete(e),t):void 0}updateInfo(e){this.info=e}destroy(){this.streams&&(this.streams.forEach((e=>{e.close()})),this.streams.clear()),this.streams=null,this.info=null,this.userId=null}}var ss=r(13);function os(e=[],t=[],r){return function(i){var n;e=e.map((e=>e.toLocaleUpperCase()));let s=!1;if(ye(i.media,(i=>{if(s&&(delete i.fingerprint,delete i.setup,delete i.icePwd,delete i.iceUfrag,delete i.iceOptions),i.fingerprint&&i.icePwd&&i.iceUfrag&&(s=!0),"application"===i.type)return!0;const n=[],o=[],a=[],c=tt(i.payloads.split(" ").shift());let u=[c];const d=i.rtp.filter((e=>e.payload===c));if((null==d?void 0:d.length)&&!Ee(e,d[0].codec.toLocaleUpperCase())&&e.push(d[0].codec.toLocaleUpperCase()),ye(i.rtp,(t=>{Ee(e,t.codec.toLocaleUpperCase())&&!Ee(u,t.payload)&&u.push(t.payload)})),r){const e=u.slice();let t=0,n=0;ye(i.fmtp,(e=>{const i=/profile-level-id/.test(e.config);if(/profile(-level)?-id/.test(e.config)&&Ee(u,e.payload)){let s=e.config.match(/profile(-level)?-id=([0-9a-f]+)/),o="";s&&(t++,o=s[2],i?ss.isSameProfile({"profile-level-id":o},{"profile-level-id":r})||(n++,Ie(u,e.payload)):o!==r&&(n++,Ie(u,e.payload)))}})),u.length&&t!==n||(u=e)}ye(i.fmtp,(e=>{if(/^apt=/.test(e.config)){const t=e.config.match(/^apt=(\d+)$/)[1];Ee(u,tt(t))||Ie(u,e.payload)}})),ye(i.rtp,(e=>{Ee(u,e.payload)&&n.push(e)})),ye(i.fmtp,(e=>{if(Ee(u,e.payload))o.push(e);else if(/^apt=/.test(e.config)){const t=e.config.match(/^apt=(\d+)$/)[1];Ee(u,tt(t))&&o.push(e)}})),ye(i.rtcpFb,(e=>{Ee(u,e.payload)&&a.push(e)})),i.payloads=u.join(" "),i.rtp=n,i.fmtp=o,i.rtcpFb=a;const l=t.filter((e=>e.kind===i.type)).map((e=>e.value));i.ext=i.ext.filter((e=>!Ee(l,e.uri)))})),(null===(n=i.media)||void 0===n?void 0:n.length)>1){let e=-1;for(let t=0;t<i.media.length;t++){const r=i.media[t];if(r.fingerprint&&r.icePwd&&r.iceUfrag){e=t;break}}e>0&&i.media.unshift(i.media.splice(e,1)[0])}return pe.debug(`[sdpOperator shrink]: holdCodec: ${JSON.stringify(e)}, removeHeaderExtensions: ${JSON.stringify(t)}, profile: ${r}`),i}}class as extends Xr{constructor(e={}){super(e),this.direction=Hr.RECV_ONLY,"ontrack"in this.pc?this.pc.ontrack=e=>{this.stream=e.streams[0],this.ontrack&&this.ontrack(e.track)}:"onaddstream"in this.pc&&(this.pc.onaddstream=e=>{this.stream=e.stream})}getMediaStream(){if(this.stream)return this.stream;if(this.pc)if(this.pc.getReceivers){this.stream=new MediaStream;const e=this.pc.getReceivers();let t=!1,r=!1;e.forEach((e=>{e.track&&"video"===e.track.kind&&!t&&(this.stream.addTrack(e.track),t=!0),e.track&&"audio"===e.track.kind&&!r&&(this.stream.addTrack(e.track),r=!0)}))}else this.stream=this.pc.getRemoteStreams()[0];return this.stream}}var cs=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const us={videoOn:!1,audioOn:!1,videoEnable:!1,audioEnable:!1,simulcast:1,redAudio:!1};class ds extends wr{constructor(e,t,r){super({client:t,type:e.type,sourceType:e.sourceType,userId:e.userId,streamId:e.streamId,videoOn:e.videoOn,audioOn:e.audioOn,videoEnable:e.videoEnable,audioEnable:e.audioEnable,audioLevelInterval:e.audioLevelInterval},r),this.options=Le({},us,e),this.videoAdaptionEnable=!1}getStream(){if(this.peer)return this.peer.getMediaStream()}getProfile(){return this.profile}setProfile(e){this.profile=e}processOffer(e=!0,t=!0,r={iceServers:[]}){var i;return cs(this,void 0,void 0,(function*(){if(!this.options.audioOn&&!this.options.videoOn)throw new Error("not has any media track when subscribing");if(this.peer&&(this.peer.oniceconnectionstatechange=null,this.peer.onicecandidate=null,this.peer.ondtlsstatechange=null,this.peer.destroy()),this.collector&&this.collector.destroy(),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser=null),this.peer=new as({iceServers:null!==(i=r.iceServers)&&void 0!==i?i:[],rtcpMuxPolicy:"require",encodedInsertableStreams:this.hasEncodedDataProcesser(r)}),this.isMsSupportDatachannel&&this.peer.createChannel(),this.handlerEvent(),this.hasAudioKind=this.options.audioOn&&e,this.hasVideoKind=this.options.videoOn&&t,!this.hasAudioKind&&!this.hasVideoKind)throw new Error("must has a media kind when subscribing");let n=yield this.peer.offer({offerToReceiveAudio:this.hasAudioKind,offerToReceiveVideo:this.hasVideoKind});return n=Ei(Ti(this.options.acodec,zr.AUDIO),Ti(this.options.vcodec,zr.VIDEO,this.options.profile),ni(Hr.RECV_ONLY),this.options.stereo?ci(zr.AUDIO,"stereo",1,this.options.acodec):null,this.options.stereo?ci(zr.AUDIO,"sprop-stereo",1,this.options.acodec):null,Ri("urn:ietf:params:rtp-hdrext:sdes:mid",zr.AUDIO),this.options.redAudio?si("urn:boom:audio-stacked-rtp",null,zr.AUDIO):null,ri("nack",Jr.ADD,zr.AUDIO))(n),yield this.peer.setOffer(n),this.collector=new Fr(this.peer.getPeerConnection(),1e3,!1,this.audioLevelInterval),this.collector.onAudioLevel=e=>{this.fire("stream-audio-level",[e])},this.logger.debug(`remotestream ${this.getUserId()} ${this.getStreamId()} offer: ${"\n"+n}`),n}))}processAnswer(e,t={enableSEI:!1}){return cs(this,void 0,void 0,(function*(){let r=!1,i=!1;const n=Ei(ti(this.msmsIPs,!1),this.isMsSupportDatachannel?wi(zr.APPLICATION,(e=>{r=e})):null,xi((e=>{i=e})));if(e=n(e),!r&&this.isMsSupportDatachannel)throw this.isMsSupportDatachannel=!1,this.logger.error(`msms ${this.getMsmsIP()} not support datachannel, should retry, remotestream userId: ${this.getUserId()}, streamId: ${this.getStreamId()}`),new Error("msms not support datachannel, should retry");this.logger.debug(`remotestream userId: ${this.getUserId()}, streamId: ${this.getStreamId()}, answer: ${"\n"+e}`),yield this.peer.setAnwser(e),this.videoAdaptionEnable=!1,this.hasEncodedDataProcesser(t)&&(this.encodedDataProcesser=new Li({send:!1,enableSEI:t.enableSEI&&"h264"===this.options.vcodec.toLocaleLowerCase(),onAudioEncodeDataPipe:this.onAudioEncodeDataPipe,onVideoEncodeDataPipe:this.onVideoEncodeDataPipe}),this.encodedDataProcesser.onmessage=(e,t)=>{this.fire("stream-sei-message",[{data:e,payload:t}])},this.encodedDataProcesser.start(this.peer.getReceivers())),i&&this.startDtlsConnectionTimeout()}))}setVideoSubscribed(e){this.videoSubscribed=e}setAudioSubscribed(e){this.audioSubscribed=e}getVideoSubscribed(){return this.videoSubscribed}getAudioSubscribed(){return this.audioSubscribed}getHasAudioKind(){return this.hasAudioKind}getHasVideoKind(){return this.hasVideoKind}muteAudio(){return cs(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasAudioKind&&this.audioSubscribed&&(yield this.client.updateStream(this,{audio_enable:!1},"audioEnableControl_"+this.streamId),this.audioSubscribed=!1)}))}unmuteAudio(){return cs(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasAudioKind&&!this.audioSubscribed&&(yield this.client.updateStream(this,{audio_enable:!0},"audioEnableControl_"+this.streamId),this.audioSubscribed=!0)}))}muteVideo(){return cs(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasVideoKind&&this.videoSubscribed&&(yield this.client.updateStream(this,{video_enable:!1},"videoEnableControl_"+this.streamId),this.videoSubscribed=!1)}))}unmuteVideo(){return cs(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasVideoKind&&!this.videoSubscribed&&(yield this.client.updateStream(this,{video_enable:!0},"videoEnableControl_"+this.streamId),this.videoSubscribed=!0)}))}destroy(){this.logger.info(`remotestream destroy userId: ${this.getUserId()}, streamId: ${this.getStreamId()}`),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser=null),this.close(),this.options=null,this.off(),this.destroyed=!0}getOptions(){return this.options}getSimulcast(){return this.options.simulcast}updateCodec(e){let t=!1;return o.i(e.acodec)&&this.options.acodec!==e.acodec&&(this.options.acodec=e.acodec,t=!0),o.i(e.vcodec)&&this.options.vcodec!==e.vcodec&&(this.options.vcodec=e.vcodec,t=!0),o.f(e.simulcast)&&this.options.simulcast!==e.simulcast&&(this.options.simulcast=e.simulcast),t}handlerEvent(){super.handlerEvent(),this.on("stream-video-adaption",(e=>{this.videoAdaptionEnable=e.video_enable,this.logger.info(`video adaption, enable: ${this.videoAdaptionEnable}, userId: ${this.getUserId()}, streamId: ${this.getStreamId()}`)}))}getVideoAdaptionEnable(){return this.videoAdaptionEnable}isSubscribed(){return!!this.peer&&(this.audioSubscribed||this.videoSubscribed)}}function ls(){const e=J();return function(){return J()-e}}function hs(e){return function(t){return(null==e?void 0:e.length)&&(t.udpBlacklist=e.join(" ")),t}}function ps(e,t){return function(r){return r[e]=t,r}}li("a",[{name:"udpBlacklist",reg:/^udp-blacklist:\s?(.*)/,format:"udp-blacklist: %s"}]);var ms=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const fs={forceWS:!1,enableRace:!1},gs=["red","ulpfec","rtx","flexfec-03","CN"],vs=[{kind:"audio",value:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{kind:"video",value:"urn:ietf:params:rtp-hdrext:toffset"},{kind:"video",value:"urn:3gpp:video-orientation"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"}];class ys extends $e{constructor(e,t){super(!0),this.udpIPBlackList=s,this.options=Le({},fs,e),this.joined=!1,this.hasMoreUser=!0,this.userMap=new Map,this.iceServers=[],this.pullUserIds=[],this.joinedUsersMap=new Map,this.logger=t||new ur}parseUser(e){const t=e.value,r=[],i=[];ye(t,(e=>{var t;this.pullUserIds.push(e.userId);const n=new ns(e.userId,e.info.userinfo);i.push(n),(null===(t=e.streams)||void 0===t?void 0:t.length)&&ye(e.streams,(t=>{var i,s,o,a,c;const u=new ds({type:null===(i=t.params.ext)||void 0===i?void 0:i.streamType,sourceType:null===(s=t.params.ext)||void 0===s?void 0:s.streamRole,stereo:null===(o=t.params.ext)||void 0===o?void 0:o.stereo,userId:e.userId,streamId:t.streamId,acodec:t.params.acodec,vcodec:t.params.vcodec,profile:null===(a=t.params.ext)||void 0===a?void 0:a.profile,videoOn:t.params.video,audioOn:t.params.audio,videoEnable:t.params.video_enable,audioEnable:t.params.audio_enable,simulcast:null!==(c=t.params.simulcast)&&void 0!==c?c:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);r.push(u),n.addStream(u)})),this.userMap.set(n.getUserId(),n)})),Object(z.a)((()=>{this.joined&&(ye(i,(e=>{this.fire("peer-joined",[e.getUserId()])})),ye(r,(e=>{const t=this.userMap.get(e.getUserId());t&&t.getStream(e.getStreamId())&&this.fire("stream-added",[e])})))}))}syncUser(e){var t;return ms(this,void 0,void 0,(function*(){if(null===(t=e.raw)||void 0===t?void 0:t.streams){const t=e.raw.streams||[];this.userMap.get(this.userId).getStreams().forEach((e=>{Ee(t,e.getStreamId())||this.unpublish(e).then((()=>{this.publish(e)}))}))}const r=e.value,i=[],n=[],s=[],o=[],a=[],c=[],u=new Map;if(this.userMap.forEach(((e,t)=>{t!==this.userId&&(n.push(t),e.getStreams().forEach((e=>{e.isConnecting()&&!Ee(c,t)&&c.push(t)})))})),ye(r,(e=>{var t,r,n;if(e.userId===this.userId)return!0;this.pullUserIds.push(e.userId),u.set(e.userId,!0),Ie(c,e.userId);let d=this.userMap.get(e.userId);if(d)if(d.updateInfo(e.info),null===(t=e.streams)||void 0===t?void 0:t.length){const t=[];d.getStreams().forEach(((e,r)=>{e instanceof ds&&t.push(e)})),ye(e.streams,(r=>{var i,n,a,c,u;let l=d.getStream(r.streamId);if(l)l.update(r.params)&&o.push(l),Ie(t,l);else{const t=new ds({type:null===(i=r.params.ext)||void 0===i?void 0:i.streamType,sourceType:null===(n=r.params.ext)||void 0===n?void 0:n.streamRole,stereo:null===(a=r.params.ext)||void 0===a?void 0:a.stereo,userId:e.userId,streamId:r.streamId,acodec:r.params.acodec,vcodec:r.params.vcodec,profile:null===(c=r.params.ext)||void 0===c?void 0:c.profile,videoOn:r.params.video,audioOn:r.params.audio,videoEnable:r.params.video_enable,audioEnable:r.params.audio_enable,simulcast:null!==(u=r.params.simulcast)&&void 0!==u?u:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);d.addStream(t),s.push(t)}})),a.push(...t)}else null===(r=d.getStreams())||void 0===r||r.forEach(((e,t)=>{e instanceof ds&&a.push(e)}));else d=new ns(e.userId,e.info.userinfo),i.push(e.userId),(null===(n=e.streams)||void 0===n?void 0:n.length)&&ye(e.streams,(t=>{var r,i,n,o,a;const c=new ds({type:null===(r=t.params.ext)||void 0===r?void 0:r.streamType,sourceType:null===(i=t.params.ext)||void 0===i?void 0:i.streamRole,stereo:null===(n=t.params.ext)||void 0===n?void 0:n.stereo,userId:e.userId,streamId:t.streamId,acodec:t.params.acodec,vcodec:t.params.vcodec,profile:null===(o=t.params.ext)||void 0===o?void 0:o.profile,videoOn:t.params.video,audioOn:t.params.audio,videoEnable:t.params.video_enable,audioEnable:t.params.audio_enable,simulcast:null!==(a=t.params.simulcast)&&void 0!==a?a:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);d.addStream(c),s.push(c)})),this.userMap.set(d.getUserId(),d)})),c.length&&this.hasMoreUser){const e=Math.ceil(c.length/100);for(let t=0;t<e;t++){if(this.signal.getConnectStatus()!==sn.OPEN)return;const{values:e}=yield this.signal.queryUser({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),queryId:c.slice(100*t,Math.max(100*t+100,c.length))});ye(e,(e=>{var t,r;let i=this.userMap.get(e.userId);if(!i)return!0;if(u.set(e.userId,!0),i.updateInfo(e.info),null===(t=e.streams)||void 0===t?void 0:t.length){const t=[];i.getStreams().forEach(((e,r)=>{e instanceof ds&&t.push(e)})),ye(e.streams,(r=>{var n,a,c;let u=i.getStream(r.streamId);if(u)u.update(r.params)&&o.push(u),Ie(t,u);else{const t=new ds({type:null===(n=r.params.ext)||void 0===n?void 0:n.streamType,userId:e.userId,streamId:r.streamId,acodec:r.params.acodec,vcodec:r.params.vcodec,profile:null===(a=r.params.ext)||void 0===a?void 0:a.profile,videoOn:r.params.video,audioOn:r.params.audio,videoEnable:r.params.video_enable,audioEnable:r.params.audio_enable,simulcast:null!==(c=r.params.simulcast)&&void 0!==c?c:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);i.addStream(t),s.push(t)}})),a.push(...t)}else null===(r=i.getStreams())||void 0===r||r.forEach(((e,t)=>{e instanceof ds&&a.push(e)}))}))}}ye(a,(e=>{this.fire("stream-removed",[e]),e.close();const t=this.userMap.get(e.getUserId());t&&t.removeStream(e.getStreamId())})),ye(n,(e=>{var t;if(u.get(e))return!0;const r=this.userMap.get(e);r&&(null===(t=r.getStreams())||void 0===t||t.forEach((e=>{this.fire("stream-removed",[e])})),this.fire("peer-leaved",[e]),r.destroy(),this.userMap.delete(e))})),ye(i,(e=>{this.fire("peer-joined",[e])})),ye(s,(e=>{this.fire("stream-added",[e])})),ye(o,(e=>{this.fire("stream-update",[e])}))}))}join(e,t,r,i=null,n=!1,s=!1){var a,c;return ms(this,void 0,void 0,(function*(){if(this.roomId=e,this.userId=t.id,this.silence=s,this.isBig=n,r&&(this.options.token=r),!(null===(a=this.options.proxies)||void 0===a?void 0:a.length))throw new Error("not has any proxy to connect");if(!this.options.token)throw new Error("not has token to connect");if(this.joined)throw new Error("has already connected");ye(this.options.proxies,(e=>{if(e.suffix={token:this.options.token},this.options.ip&&(e.suffix.ip=this.options.ip),this.options.location&&(e.suffix.location=this.options.location),o.h(this.options.canary)){let t="";Oe(this.options.canary,((e,r)=>{t+=`${r},${e},`})),e.suffix.canary=t.slice(0,t.length-1)}})),this.signal=new is(this.options.proxies,{forceWS:this.options.forceWS,enableRace:this.options.enableRace,forceDC:this.options.forceDC,forceWT:this.options.forceWT,enableWT:this.options.enableWT},this.getRpc(),this.logger),this.handleEvents();const u=ls();yield this.signal.connect();const d=u(),l=Le({},t.info);l.create=!0,l.network=Qi.name,l.platform="Web",Sr();try{const e=ls(),r=yield this.signal.join({roomId:this.roomId,userId:this.userId,isBig:n?1:0,silence:s,info:l,sessionId:i}),a=e();o.a(r.iceservers)&&ye(r.iceservers,(e=>{e.urls||(e.urls=e.url),this.iceServers.push(e)})),this.joined=!0,this.callId=(null===(c=r.raw)||void 0===c?void 0:c.callId)||"";const u=new ns(this.userId,t.info);return this.userMap.set(u.getUserId(),u),this.pullUserIds=[],this.joinedUsersMap.clear(),this.hasMoreUser=r.value.length<r.total,this.parseUser(r),this.hasMoreUser||(this.pullUserIds=[]),this.logger.info(`joined: sessionId: ${r.sessionId}, callId: ${r.raw.callId}`),{sessionId:r.sessionId,callId:r.raw.callId,connectConsume:d,joinConsume:a,usedProxyConsume:this.signal.getConnectedProxyConsume(),connectCount:this.signal.getConnectCount()}}catch(e){throw this.logger.error(`join room failed: ${dt(e)}, proxy: ${JSON.stringify(this.getActiveProxy())}`),this.signal.close(),e}}))}leave(){var e;return ms(this,void 0,void 0,(function*(){this.signal&&(this.logger.info("leaved: sessionId: "+((null===(e=this.signal)||void 0===e?void 0:e.getSessionId())||"")),yield this.signal.leave({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId()||""}),this.signal.close(),this.signal=null,this.joined=!1)}))}publish(e,t){var r;return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(e.isDestroyed())throw new Error("stream has already destroyed");e.setLogger(this.logger),e.setUserId(this.userId),e.updateAudioLevelInterval(this.options.audioLevelInterval),this.logger.info(`publish: ${this.userId} ${e.getStreamId()} options: ${JSON.stringify(t)}`),t&&e.setOptions(t),t=e.getOptions();let i=yield e.processOffer(this,{iceServers:this.iceServers,enableSEI:this.options.enableSEI,enableSVC:this.options.enableSVC});const n=Ei(os(gs.concat([e.getOptions().acodec,e.getOptions().vcodec]),vs,e.getOptions().profile),this.options.enableSVC&&"vp8"===t.vcodec.toLocaleLowerCase()&&o.i(t.encodings[0].scalabilityMode)?ci(zr.VIDEO,"scalability-mode",t.encodings[0].scalabilityMode,t.vcodec):null,hs(Ir()),this.options.enableAdaption?ps("rembFlags",Lt.PACKETS_LOST_SCALE):null,this.options.enableNego?ps("brtcVideoNego",1):null).after((this.options.enableTCC,null));e.published=!0;const s={};if(e.hasAudio()&&(s.audio={codec:t.acodec&&t.acodec.toLocaleUpperCase()||"OPUS",bitrate:Math.ceil(t.audioBitrate/1024)}),e.hasVideo()&&t.encodings.length){let e=0,i=-1,n=-1,o=-1;for(let s=0;s<t.encodings.length;s++)e+=null!==(r=t.encodings[s].bitrate)&&void 0!==r?r:0,i<t.encodings[s].width&&(i=t.encodings[s].width,o=t.encodings[s].fps),n<t.encodings[s].height&&(n=t.encodings[s].height);s.video={w:i,h:n,fps:o,codec:t.vcodec&&t.vcodec.toLocaleUpperCase()||"H264",bitrate:Math.ceil(e/1024)}}const{sdpAnswer:a}=yield this.signal.publish({roomId:this.roomId,userId:this.userId,streamId:e.getStreamId(),sessionId:this.signal.getSessionId(),options:{sdpOffer:n(i),audio:e.hasAudio(),video:e.hasVideo(),audio_enable:e.getAudioEnable(),video_enable:e.getVideoEnable(),attribute:s,simulcast:t.simulcast,ext:{streamType:e.getType(),streamRole:e.getSourceType(),stereo:e.hasAudio()&&t.stereo}}});yield e.processAnswer(a,{enableSEI:this.options.enableSEI,enableSVC:this.options.enableSVC}),this.userMap.get(this.userId).addStream(e),e.startCollecting()}))}unpublish(e){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(e.isDestroyed())throw new Error("stream has already destroyed");this.logger.info(`unpublish: ${e.getUserId()} ${e.getStreamId()}`),e.published=!1,e.close(),this.signal.unpublish({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId()}),this.userMap.get(this.userId).removeStream(e.getStreamId())}))}updateStream(e,t,r){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");this.logger.info(`updateStream: ${e.getUserId()} ${e.getStreamId()} options: ${JSON.stringify(t)}`),yield this.signal.controlStream({roomId:this.roomId,userId:this.userId,streamId:e.getStreamId(),sessionId:this.signal.getSessionId(),options:t},{key:r,maxRetry:3,errorRetry:!0,needRetry:e=>!!e&&(33===e.code||11===e.code||21===e.code||23===e.code||13===e.code)})}))}preferProfile(e,t){return ms(this,void 0,void 0,(function*(){if(!(e instanceof ds))throw new Error("stream not remotestream instance");if(e.isDestroyed())throw new Error("stream has already destroyed");if(!(t>=e.getSimulcast()))return this.updateStream(e,{profile:t},"preferProfile_"+e.getStreamId());this.logger.warn(`preferProfile: ${e.getUserId()} ${e.getStreamId()} not support, simulcast: ${e.getSimulcast()}, profile: ${t}`)}))}subscribe(e,t={audio:!0,video:!0,profile:0}){var r,i;return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(!(e instanceof ds))throw new Error("stream not remotestream instance");if(e.isDestroyed())throw new Error("stream has already destroyed");this.logger.info(`subscribe: ${e.getUserId()} ${e.getStreamId()} options: ${JSON.stringify(t)}`);const n=e.getOptions();let s=yield e.processOffer(t.audio,t.video,{iceServers:this.iceServers,enableSEI:this.options.enableSEI});const a={sdpOffer:Ei(os(gs.concat([e.getOptions().acodec,e.getOptions().vcodec]),vs,e.getOptions().profile),hs(Ir())).after(this.options.enableTCC?e=>{const t=e.findIndex((e=>we.d(e,"m=")));return t>-1?(e.splice(t,0,"a=adaption:1"),e.splice(t+1,0,"a=brtcversion:2.0")):(e.push("a=adaption:1"),e.push("a=brtcversion:2.0")),e}:null)(s),audio:e.hasAudio()&&t.audio,video:e.hasVideo()&&t.video,audio_enable:e.hasAudio()&&t.audio&&(null===(r=t.audioEnable)||void 0===r||r),video_enable:e.hasVideo()&&t.video&&(null===(i=t.videoEnable)||void 0===i||i)};n.simulcast>1&&(a.profile=o.f(t.profile)?t.profile:n.simulcast-1);const{sdpAnswer:c}=yield this.signal.subscribe({roomId:this.roomId,userId:this.userId,streamId:e.getStreamId(),sessionId:this.signal.getSessionId(),options:a});yield e.processAnswer(c,{enableSEI:this.options.enableSEI}),e.setAudioSubscribed(a.audio_enable),e.setVideoSubscribed(a.video_enable),e.subscribeOptions=t,e.startCollecting()}))}unsubscribe(e){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(e.isDestroyed())throw new Error("stream has already destroyed");this.logger.info(`unsubscribe: ${e.getUserId()} ${e.getStreamId()}`),e.close(),this.signal.unsubscribe({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId()})}))}setBitrate(e,t){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");e.isPublished()?yield this.signal.setBitrate({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId(),rate:t}):this.logger.warn(`can not setBitrate because of stream not publish, ${e.getUserId()} ${e.getStreamId()}`)}))}syncIcecandidate(e,t){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");yield this.signal.addIceCandidate({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId(),candidate:t})}))}syncRoom(){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");const e=this.userMap.get(this.userId);if(e){const t=Le({},e.getUserInfo());t.create=!0,t.network=Qi.name,t.platform="Web";try{const e=yield this.signal.syncRoom({roomId:this.roomId,userId:this.userId,isBig:this.isBig?1:0,silence:this.silence,sessionId:null,info:t});this.pullUserIds=[],this.joinedUsersMap.clear(),this.hasMoreUser=e.value.length<e.total,yield this.syncUser(e),this.hasMoreUser||(this.pullUserIds=[]),this.fire("sync-room-completed")}catch(e){this.fire("error"),this.destroy()}}}))}pullUsers(e=120){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(!this.hasMoreUser)throw new Error("no more user to request");e=Jn(e,1,120),this.logger.info("pullUsers, count: "+e);try{const t=yield this.signal.pullUsers({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),count:e,cursor:this.pullUserIds[this.pullUserIds.length-1]||""}),r=t.value;if(r.length){const e=[],i=[];ye(r,(t=>{var r;if(this.joinedUsersMap.has(t.userId))return this.hasMoreUser=!1,this.pullUserIds=[],!1;this.pullUserIds.push(t.userId);const n=new ns(t.userId,t.info.userinfo);i.push(n),(null===(r=t.streams)||void 0===r?void 0:r.length)&&ye(t.streams,(r=>{var i,s,o;const a=new ds({type:null===(i=r.params.ext)||void 0===i?void 0:i.streamType,userId:t.userId,streamId:r.streamId,acodec:r.params.acodec,vcodec:r.params.vcodec,profile:null===(s=r.params.ext)||void 0===s?void 0:s.profile,videoOn:r.params.video,audioOn:r.params.audio,videoEnable:r.params.video_enable,audioEnable:r.params.audio_enable,simulcast:null!==(o=r.params.simulcast)&&void 0!==o?o:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);e.push(a),n.addStream(a)})),this.userMap.set(n.getUserId(),n)})),this.hasMoreUser&&(this.hasMoreUser=t.total>this.userMap.size),ye(i,(e=>{this.fire("peer-joined",[e.getUserId()])})),ye(e,(e=>{const t=this.userMap.get(e.getUserId());t&&t.getStream(e.getStreamId())&&this.fire("stream-added",[e])}))}else this.hasMoreUser=!1,this.pullUserIds=[]}catch(t){if(10===(null==t?void 0:t.code))return this.pullUserIds.pop(),this.pullUsers(e);throw t}return{hasMoreUser:this.hasMoreUser}}))}queryUsers(e){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(!o.a(e))throw new Error("userId must be string value array");if(!e.length)throw new Error("userId must not be empty array");if(!this.silence||!this.isBig)throw new Error("not support because of not silence and big room mode");if(this.logger.info("queryUsers, userIds: "+JSON.stringify(e)),!(e=e.filter((e=>e!==this.userId))).length)throw new Error("userIds must not only has self userId");const{values:t}=yield this.signal.queryUser({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),queryId:e}),r=[];return ye(t,(e=>{var t;(null===(t=null==e?void 0:e.streams)||void 0===t?void 0:t.length)&&ye(e.streams,(t=>{var i,n,s,o;const a=new ds({type:null===(i=t.params.ext)||void 0===i?void 0:i.streamType,sourceType:null===(n=t.params.ext)||void 0===n?void 0:n.streamRole,userId:e.userId,streamId:t.streamId,acodec:t.params.acodec,vcodec:t.params.vcodec,profile:null===(s=t.params.ext)||void 0===s?void 0:s.profile,videoOn:t.params.video,audioOn:t.params.audio,videoEnable:t.params.video_enable,audioEnable:t.params.audio_enable,simulcast:null!==(o=t.params.simulcast)&&void 0!==o?o:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);r.push(a),this.logger.debug(`stream added: ${e.userId} ${t.streamId}`)}))})),r}))}getMediaServers(){var e;return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");const t=yield this.signal.getMediaServers({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId()}),r=[];return(null===(e=t.servers)||void 0===e?void 0:e.length)&&ye(t.servers,(e=>{var t;(null===(t=e.data)||void 0===t?void 0:t.length)&&ye(e.data,(t=>{r.push({addr:t.addr,location:e.location,score:t.score})}))})),r.sort(((e,t)=>e.score-t.score))}))}setMediaServer(e,t){return ms(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");t||(t=this.userId),yield this.signal.setMediaRelation({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),selectUserId:t,node:e})}))}request(e,t){return ms(this,void 0,void 0,(function*(){return this.signal.request(e,t)}))}getCallId(){return this.callId}destroy(){this.userMap&&(this.userMap.forEach((e=>{e.destroy()})),this.userMap.clear()),this.userMap=null,this.joinedUsersMap&&this.joinedUsersMap.clear(),this.joinedUsersMap=null,this.pullUserIds=[],this.signal&&(this.signal.close(),this.signal=null),this.joined=!1,this.off()}handleEvents(){this.signal.on("error",(()=>{this.logger.error("signal error"),this.fire("error")})).on("close",(()=>{this.logger.error("signal close"),this.fire("error")})).on("timeout",(()=>{this.logger.error("signal timeout"),this.fire("error")})).on("reconnected",(()=>{this.fire("reconnected")})).on("peer-joined",(e=>{let t=this.userMap.get(e.userId);t?t.updateInfo(e.info||{}):(t=new ns(e.userId,e.info),this.userMap.set(t.getUserId(),t)),this.logger.debug("peer joined: "+t.getUserId()),this.joinedUsersMap.set(e.userId,!0),this.fire("peer-joined",[t.getUserId()])})).on("peer-leaved",(e=>{if(e.userId===this.userId)return;const t=this.userMap.get(e.userId);this.joinedUsersMap.delete(e.userId),t&&(this.userMap.delete(t.getUserId()),t.getStreams().forEach((e=>{this.fire("stream-removed",[e])})),this.logger.debug("peer leaved: "+t.getUserId()),this.fire("peer-leaved",[t.getUserId()]),t.destroy(),this.pullUserIds.length&&Ie(this.pullUserIds,e.userId))})).on("room-closed",(()=>{this.logger.error("room closed"),this.fire("room-closed"),this.destroy()})).on("error",(()=>{this.logger.error("room error"),this.fire("error"),this.destroy()})).on("stream-added",(e=>{var t,r,i,n;if(e.userId===this.userId)return;let s=this.userMap.get(e.userId);s||(s=new ns(e.userId,e.info),this.userMap.set(s.getUserId(),s));const o=s.getStream(e.streamId);if(o)if(o instanceof ds){this.logger.warn(`stream added but has old stream, updated: ${s.getUserId()} ${e.streamId}`);let t=o.update(e.params);t&&this.fire("stream-update",[o]),t=o.updateCodec(e.params),t&&(this.logger.warn(`retry subscribe stream because of the stream's codec has updated, ${s.getUserId()} ${e.streamId}`),this.subscribe(o,{audio:o.getHasAudioKind(),video:o.getHasVideoKind(),audioEnable:o.getAudioSubscribed(),videoEnable:o.getVideoSubscribed()}).then((()=>{o.fire("stream-update",[{trackUpdate:!0}])})))}else this.logger.warn(`stream added but the streamId is same of localstream, ignored: ${s.getUserId()} ${e.streamId}`);else{this.logger.debug(`stream added: ${s.getUserId()} ${e.streamId}`);const o=new ds({type:null===(t=e.params.ext)||void 0===t?void 0:t.streamType,sourceType:null===(r=e.params.ext)||void 0===r?void 0:r.streamRole,stereo:null===(i=e.params.ext)||void 0===i?void 0:i.stereo,userId:s.getUserId(),streamId:e.streamId,acodec:e.params.acodec,vcodec:e.params.vcodec,profile:null===(n=e.params.ext)||void 0===n?void 0:n.profile,audioOn:e.params.audio,videoOn:e.params.video,audioEnable:e.params.audio_enable,videoEnable:e.params.video_enable,simulcast:e.params.simulcast,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);s.addStream(o),this.fire("stream-added",[o])}})).on("stream-removed",(e=>{if(e.userId===this.userId)return;let t=this.userMap.get(e.userId);if(t){const r=e.streams||[];e.streamId&&!Ee(r,e.streamId)&&r.push(e.streamId),this.logger.debug(`stream removed: ${t.getUserId()} ${JSON.stringify(r)}`),ye(r,(e=>{const r=t.removeStream(e);r&&(this.fire("stream-removed",[r]),r.close())}))}})).on("stream-update",(e=>{const t=this.userMap.get(e.userId);if(t){const r=t.getStream(e.streamId);if(r){const i=r.update(e.params);this.logger.debug(`stream updated: ${t.getUserId()} ${e.streamId} options: ${JSON.stringify(e.params)}, updated: ${i}`),i&&this.fire("stream-update",[r])}}})).on("stream-error",(e=>{this.logger.error("stream error "+JSON.stringify(e.error)),this.fire("media-error",[e.error])})).on("stream-disconnected",(e=>{if(e.userId!==this.userId)return;const t=this.userMap.get(e.userId),r=t.getStream(e.streamId);r&&(this.logger.error(`stream disconnection: ${t.getUserId()} ${e.streamId}`),r.fire("stream-disconnected"))})).on("evicted",(e=>{if(this.isBig&&this.silence)return void(e.userId===this.userId&&(this.fire("evicted"),this.logger.error("peer evicted: "+this.userId)));const t=this.userMap.get(e.userId);t&&(t.getUserId()===this.userId?(t.getStreams().forEach((e=>{e.close()})),this.fire("evicted")):(t.getStreams().forEach((e=>{this.fire("stream-removed",[e])})),this.logger.error("peer evicted: "+t.getUserId()),this.userMap.delete(t.getUserId()),this.fire("peer-leaved",[t.getUserId()]),t.destroy()))})).on("peer-rejoined",(e=>{this.fire("peer-rejoined",[{userId:e.userId,platform:e.info.platform,device:e.info.device,ip:e.info.ip}]),this.logger.warn("peer rejoied: "+e.userId)})).on("token-expire",(()=>{this.logger.error("token expire"),this.fire("token-expire")})).on("token-will-expire",(e=>{this.logger.warn("token will expire"),this.fire("token-will-expire",[e.seconds])})).on("session-close",(()=>{this.logger.error("session closed, retry syncRoom"),this.syncRoom()})).on(dr,(e=>{this.logger.debug("notify: "+JSON.stringify(e)),this.fire(dr,[e])})).on("state-notify",(e=>{this.fire("state-notify",[e])})).on("server-proxy-change",(e=>{o.a(e.nodes)&&(ye(e.nodes,(e=>{if(e.suffix={token:this.options.token},this.options.ip&&(e.suffix.ip=this.options.ip),this.options.location&&(e.suffix.location=this.options.location),o.h(this.options.canary)){let t="";Oe(this.options.canary,((e,r)=>{t+=`${r},${e},`})),e.suffix.canary=t.slice(0,t.length-1)}})),this.signal.tryChangeSelectedProxy(e.nodes))})).on("proxy-changed",(()=>{this.fire("proxy-changed")})).on("media-server-changed",(()=>{this.userMap.forEach((e=>{e.getStreams().forEach((e=>{e instanceof Vi&&e.isPublished()?this.unpublish(e).then((()=>{this.publish(e)})):e instanceof ds&&e.isSubscribed()&&this.subscribe(e,e.subscribeOptions).then((()=>{e.fire("stream-update",[{trackUpdate:!0}])}))}))}))}))}getRpc(){return{sessionClosed:()=>(Object(z.a)((()=>{this.syncRoom()})),{result:0})}}getActiveProxy(){return this.signal.getProxy()}}class _s{constructor(e=500,t=50){this.interval=e,this.threshold=t,this.lastTime=J(),this.cpu=[0],this.delay=0,this.timer=new lt((()=>{this.process()}),0,this.interval)}process(){let e=1,t=J();this.delay=Math.max(t-this.lastTime-this.interval,0);let r=this.threshold;this.delay>this.interval+500&&(r*=this.delay/this.interval);let i=1;for(;i<100;)t>this.lastTime+i*r&&e++,i++;this.cpu.push(e),this.cpu.length>20&&this.cpu.shift(),this.lastTime=t}getCPU(){return Math.max(...this.cpu)}getDelay(){return this.delay}start(){this.timer.start()}stop(){this.timer.stop(),this.cpu=[0]}destroy(){this.timer.destroy(),this.cpu=[0]}}var bs=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};const Ss={callId:"",diffNTP:0,comments:""};class Is{constructor(e){this.url=e.url,this.options=Le({},Ss,e),this.seq=0,this.transport=new fn({tag:"Collection",interval:3e3,connectOnClose:!0,native:an,nativeOptions:{processOffer:(e,t)=>bs(this,void 0,void 0,(function*(){const r={type:"offer",sdp:t,token:this.options.token,device_id:this.options.deviceId,trace_id:this.options.traceId,platform:"Web",appid:this.options.appId,room:this.options.roomId,user:this.options.userId,version:this.options.version,webrtcType:this.options.webrtcType,comments:this.options.comments};return this.options.clientIp&&(r.client_ip=this.options.clientIp),Bn(e,r).then((e=>e.sdp)).catch((e=>{var t;throw this.options.report&&this.options.report({code:1,msg:"Collection request answer failed, error: "+(null!==(t=null==e?void 0:e.message)&&void 0!==t?t:"")}),e}))}))},onReceive:e=>{this.resetTimeout()},onClose:()=>{this.options.report&&this.options.report({code:2,msg:"Collection channel closed"})},onError:()=>{this.options.report&&this.options.report({code:3,msg:"Collection channel error"})},onTimeout:()=>{this.options.report&&this.options.report({code:4,msg:"Collection channel timeout"})},onOpen:e=>{this.options.report&&this.options.report({code:0,msg:"Collection channel opened"})},retryCount:2e3,refreshQueueOnClose:!0,timeout:1e4,queueMax:1800}),this.cpuSimulator=new _s,this.cpuSimulator.start(),this.transport.connect({url:`${this.url}/${cr()}`})}resetTimeout(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}setTimeout(){this.timeout||(this.timeout=setTimeout((()=>{this.transport&&(this.transport.reconnect(),this.options.report&&this.options.report({code:5,msg:"Collection reconnect"})),this.timeout=null}),2e4))}setCallId(e){this.options.callId=e}heartbeat(){const e={type:"heart",callId:this.options.callId,ts:J()+this.options.diffNTP,seq:this.seq++};this.transport.send(JSON.stringify(e)),this.setTimeout()}action(e,t,r,i,n,s){if(!this.transport)return;const o=J(),a={type:"action",callId:this.options.callId,ts:o+this.options.diffNTP,action:e,sendTs:(r||o)+this.options.diffNTP,receiveTs:(i||o)+this.options.diffNTP,success:t>0?0:1,eid:cr(),seq:this.seq++};t>0&&(a.errorCode=t),null!=s&&(a.vErrorCode=s),n&&(a.options=n),this.transport.send(JSON.stringify(a)),this.setTimeout()}stats(e,t,r,i,n,s=0){if(!this.transport)return;t&&(t.cpu={systemCpu:this.cpuSimulator.getCPU(),systemDelay:this.cpuSimulator.getDelay()});const o={type:"stats",callId:this.options.callId,stream:e,flow:r?"push":"pull",ts:J()+this.options.diffNTP,seq:this.seq++,stats:t};r||(o.remote=i),n&&Oe(n,((e,t)=>{o[t]=e})),this.transport.send(JSON.stringify(o)),this.setTimeout()}log(e,t,r={}){const i={type:"sdklog",ts:J()+this.options.diffNTP,seq:this.seq++,level:t,log:e,extend:r};this.transport.send(JSON.stringify(i)),this.setTimeout()}destroy(){this.transport&&(this.transport.close(),this.transport=null),this.cpuSimulator&&(this.cpuSimulator.destroy(),this.cpuSimulator=null)}}function Es(e){return new Promise(((t,r)=>{navigator.mediaDevices.enumerateDevices().then((r=>{t(function(e,t){const r=[];let i=0;for(let n of t)if(n.kind==e||"all"==e){let e={label:"",groupId:n.groupId,deviceId:n.deviceId,kind:n.kind};""===n.label?(i++,"videoinput"==n.kind?e.label="Camera-"+i:"audioinput"==n.kind?e.label="Mic-"+i:"audiooutput"==n.kind?e.label="Speaker-"+i:(i--,e.label="unknown device")):e.label=n.label,e.deviceId&&r.push(e)}return r}(e,r))})).catch((e=>{r(e)}))}))}var Ts=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function Rs(){return Ts(this,void 0,void 0,(function*(){let e=yield Es(Yr.AUDIO_INPUT),t={};return e.filter((e=>("default"===e.deviceId&&(t=e),"default"!==e.deviceId&&"communications"!==e.deviceId))).map(((e,r)=>({name:e.label,deviceId:e.deviceId,groupId:e.groupId,index:r,kind:"audioinput",default:e.groupId===t.groupId&&t.label&&t.label.indexOf(e.label)>-1})))}))}var ws=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function As(){return ws(this,void 0,void 0,(function*(){const e=yield Es(Yr.VIDEO_INPUT);let t={};return e.filter((e=>("default"===e.deviceId&&(t=e),"default"!==e.deviceId&&"communications"!==e.deviceId))).map(((e,r)=>({name:e.label,deviceId:e.deviceId,groupId:e.groupId,index:r,kind:"videoinput",default:e.groupId===t.groupId&&t.label&&t.label.indexOf(e.label)>-1})))}))}var ks=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};function Cs(){return ks(this,void 0,void 0,(function*(){let e=yield Es(Yr.AUDIO_OUTPUT),t={};return e.filter((e=>("default"===e.deviceId&&(t=e),"default"!==e.deviceId&&"communications"!==e.deviceId))).map(((e,r)=>({name:e.label,deviceId:e.deviceId,groupId:e.groupId,index:r,kind:"audiooutput",default:e.groupId===t.groupId&&t.label&&t.label.indexOf(e.label)>-1})))}))}const Ms={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,b:11,c:12,d:13,e:14,f:15},Os=void 0!==window.localStorage;let Ps=G.b,Ls=G.b;G.b,Os&&(Ps=function(e,t){if(o.e(e))Oe(e,((e,t)=>{Ps(t,e)}));else try{localStorage[e]=t}catch(e){}},Ls=function(e){let t;try{t=localStorage[e]}catch(e){}return t});const xs=Ps,Ds=Ls;var Ns=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class $s{constructor(e){var t,r,i,n;if(this.mode="rtc",this.codec="h264",this.audioCodec="opus",this.comments="",!e||!o.i(e.appId))throw new R(1001,"appId 类型错误,请检查");this.options=e,e.comments&&(this.comments=e.comments.substring(0,64)),this.brtcAppId=e.appId,this.deviceId=Ds("brtc_device_id"),this.deviceId||(this.deviceId=K(),xs("brtc_device_id",this.deviceId)),this.codec=null!==(t=e.codec)&&void 0!==t?t:"h264",this.roomType=null!==(r=e.roomType)&&void 0!==r?r:"normal",this.webrtcType=0,this.emitter=new $e(!0),this.promiseHoldMap={},this.remoteStreamMap={},this.publishStream=null,this.sessionId=null,this.publishOnly=!!e.publishOnly,this.useStringUserId=!!e.useStringUserId,this.isJoinning=!1,this.role=null!==(i=e.role)&&void 0!==i?i:"anchor",this.diffNTP=0,this.options.audioLevelInterval=null!==(n=this.options.audioLevelInterval)&&void 0!==n?n:1e3,this.isEnableSmallStream=!1,this.smallStreamCodecOption=Le({},zt),this.destroyed=!1,this.publishNamespace=".client_publish_stream_close"+Math.random(),this.enableSVC=!1,this.logger=new ur({uploadLevel:pe.getUploadLevel(),onUpload:(e,t,r)=>{this.collection&&this.collection.log(e,t,{tag:r||"brtc"})}}),this.reportTimer=new lt(this.reportStats.bind(this),2e3,2e3),this.ondevicechangeHandler=Fe((e=>{this.reportDeviceList()}),200);try{navigator.mediaDevices.addEventListener("devicechange",this.ondevicechangeHandler)}catch(e){this.logger.error("bind devicechange event handler failed, userId: "+this.userId,"client")}this.logger.info(`create client, userId: ${this.userId}, mode: ${this.mode}, codec: ${this.codec}`,"client")}reportDeviceList(){return Ns(this,void 0,void 0,(function*(){if(this.collection){const[e,t,r]=yield Promise.all([Rs(),Cs(),As()]),i=r.concat(e).concat(t);this.reportAction("deviceEnumerate",0,null,null,{list:i.map((e=>({device_id:e.deviceId,group_id:e.groupId,name:e.name,kind:e.kind,default:e.default})))})}}))}getBRTCRoomId(){return`${this.roomId}@${this.brtcAppId}`}clearObject(){a(this.webrtcType)&&this.client?this.client.destroy():c(this.webrtcType)&&this.client&&this.client.off("*"),this.client=null,this.sessionId=null,this.publishStream=null,this.remoteStreamMap={},this.reportTimer&&this.reportTimer.stop(),this.collection&&(this.collection.destroy(),this.collection=null)}joinFailReport(e=0,t="",r){const i={appid:this.brtcAppId,rid:this.getBRTCRoomId(),uid:this.userId,sig:this.userSig,err_code:e,msg:t};r&&(i.ext=r),function(e){Xi(this,void 0,void 0,(function*(){const t=Le({os:nr.name,sdk_ver:h,os_ver:nr.version,network_type:Qi.name,device:`${nr.name}/${nr.version} ${ut.name}/${ut.version}`},e);return fetch(`${"production"===l?"https://qs.baijiayun.com/brtcsdkreport":"https://test-qs.baijiayun.com/brtcsdkreport"}?${tn(t)}`,{cache:"no-cache",credentials:"same-origin",headers:{Accept:"text/plain","Content-Type":"text/plain"},method:"GET",mode:"cors",redirect:"follow",referrer:"no-referrer"})}))}(i)}getVT(){return Ns(this,void 0,void 0,(function*(){let e=yield function(e){return Xi(this,void 0,void 0,(function*(){const t={app_id:e.appId,room_id:e.roomId,user_id:e.userId,sig:e.sign,ts:Math.floor((new Date).getTime()/1e3),platform:"Web",version:h,device_id:e.deviceId};return e.comments&&(t.comments=e.comments),e.clientIP&&(t.client_ip=e.clientIp),rn(en(),t,[en(!0)])}))}({appId:this.brtcAppId,sign:this.userSig,roomId:this.roomId,userId:this.userId,comments:this.comments,clientIP:this.clientIP,deviceId:this.deviceId}).catch((e=>{throw this.joinFailReport(5e3,"userSig 验证接口请求失败"),new R(5e3,"userSig 验证接口请求失败")}));if(200!==e.code)throw this.joinFailReport(5e3,"userSig 验证接口请求失败",{code:e.code,msg:e.msg}),new R(5e3,e.msg);return this.token=e.data.ut,this.traceId=e.data.trace,this.reportThreshold=e.data.report.rtc,this.masterResSettings=e.data.settings,this.masterResSettings.sdk_video_svc_mode&&(this.masterResSettings.sdk_video_svc_mode=this.masterResSettings.sdk_video_svc_mode.replace(/T[4-9]/,"T3")),this.reportTimer.updateInterval(1e3*this.reportThreshold.meet_call_quality_upload_rate_interval),this.logger&&o.f(this.reportThreshold.sdk_log_level)&&this.logger.setUploadLevel(this.reportThreshold.sdk_log_level),e}))}getUserId(){return this.userId}join(e,t,r,i={}){var n,s,u,d,l,m,g,v,y,b;return Ns(this,void 0,void 0,(function*(){if(this.destroyed)throw new R(1002,"client 已调用 destroy 方法");if(this.isJoinning)throw new R(1002,"正在 join,请勿重复调用");if(this.client)throw new R(1002,"重复 join,请先调用 leave");if(!o.i(e))throw this.joinFailReport(1001,"roomId 类型错误,请检查",{roomId:e}),new R(1001,"roomId 类型错误,请检查");if(this.useStringUserId){if(!o.i(t))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:t}),new R(1001,"userId 类型错误,请检查");if(!/^[0-9a-zA-Z-_]{1,64}$/.test(t))throw this.joinFailReport(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符",{userId:t}),new R(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符")}else{if(!o.f(t))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:t}),new R(1001,"userId 类型错误,请检查");if(t>Math.pow(2,31)-1||t<-Math.pow(2,31)||Math.floor(t)!==t)throw this.joinFailReport(1001,"userId 为 int32 整型",{userId:t}),new R(1001,"userId 为 int32 整型")}if(!o.i(r))throw new R(1001,"sig 类型错误,请检查");this.roomId=e,this.userId=t,this.userSig=r,this.joinConfig=i,this.isJoinning=!0;const I=ls(),E=ls();let T=yield this.getVT();const A=E();let k,C=0,M=0,O=0,P=0,L="WebSocket";this.joinConfig.role&&(this.role=this.joinConfig.role);const x=Q();try{let e=this.token.split(".");if(3!==e.length||!o.i(e[1])||!e[1])throw this.logger.error("client join fail, userId: "+this.userId,"client"),this.joinFailReport(5001,"ut 格式错误",{ut:this.token}),new R(5001,this.userSig);if(k=JSON.parse(jt(e[1])),!o.f(k.sub)&&!/^[0-9a-zA-Z-_]{1,64}$/.test(k.sub))throw this.joinFailReport(5001,"ut user_id 类型错误,请检查",{sub:k.sub}),new R(5001,"user_id 类型错误,请检查");if(this.userId!==q(k.sub,this.useStringUserId))throw this.joinFailReport(5001,"签名的 userId 与传入的 userId 不符",{userId:this.userId,sub:k.sub}),new R(5001,"签名的 userId 与传入的 userId 不符");if(this.brtcAppId!==k.u)throw this.joinFailReport(5001,"签名的 appId 与传入的 appId 不符",{appId:this.brtcAppId,u:k.u}),new R(5001,"签名的 appId 与传入的 appId 不符");if(this.roomId!==k.r)throw this.joinFailReport(5001,"签名的 roomId 与传入的 roomId 不符",{roomId:this.roomId,r:k.r}),new R(5001,"签名的 roomId 与传入的 roomId 不符");if(this.vloudProxy=k.s,this.webrtcAppId=k.c,this.webrtcType=k.m,this.sign=k.sig,a(this.webrtcType)&&(this.sign=this.token),o.h(k.canary)&&(this.canary=k.canary),c(this.webrtcType)&&o.i(this.webrtcAppId)&&!/^[0-9]+$/.test(this.webrtcAppId))throw this.joinFailReport(5001,"trtc appId 类型错误",{appId:this.webrtcAppId}),new R(5001,"trtc appId 类型错误,请检查");this.privileges=new Vt(o.f(k.p)?k.p:0),D=this.webrtcType,p=D}catch(e){if(this.isJoinning=!1,R.instanceOf(e))throw new R(e.code,e.message);throw this.joinFailReport(5001,"userSig 验证失败"),new R(5001,"userSig 验证请求失败")}var D,N,$;try{let e=T.data.services;if(!1===e.ip_accurate&&e.ip_url)try{const t=yield nn(e.ip_url,{});if(200!==t.code||!(null===(n=t.data)||void 0===n?void 0:n.ip))throw new R(5004,"ip 请求失败");{this.clientIP=t.data.ip;const r=yield this.getVT();e=r.data.services}}catch(t){this.joinFailReport(5004,"ip request failed, use before",{ip:e.ip}),this.logger.warn("ip request failed, use before","client")}else this.clientIP=e.ip;if(e.timestamp&&(this.diffNTP=e.timestamp-Q()),e.collection&&(this.collection=new Is({url:e.collection,appId:this.brtcAppId,roomId:this.getBRTCRoomId(),callId:null,userId:Object(je.a)(this.userId),diffNTP:this.diffNTP,webrtcType:this.webrtcType,version:h,comments:this.comments,clientIp:this.clientIP,traceId:this.traceId,deviceId:this.deviceId,token:this.token,report:e=>{this.joinFailReport(6e3+(o.f(e.code)?e.code:0),"collection 连接错误",e)}})),this.destroyed)throw new R(4013,"client 已调用 destroy 方法");if(a(this.webrtcType)){const t=_||[];this.enableSVC=(!!(null===(s=this.masterResSettings)||void 0===s?void 0:s.sdk_svc_enabled)||function(e,t){if(!e)return!1;const r=Math.floor(t/4);return!(r>=e.length)&&1==(Ms[e[e.length-1-r].toLocaleLowerCase()]>>t%4&1)}(null===(u=this.masterResSettings)||void 0===u?void 0:u.extend,4))&&(ut.chrome||ut.edge)&&ut.checkVersion(ut.majorVersion,"111",!0),this.client=new ys({proxies:t.concat(e.proxies),forceWS:1===S(),forceDC:2===S(),forceWT:3===S(),enableRace:!1,enableWT:!!(null===(d=this.masterResSettings)||void 0===d?void 0:d.sdk_quic_enabled),audioLevelInterval:this.options.audioLevelInterval,enableTCC:!!(null===(l=this.masterResSettings)||void 0===l?void 0:l.sdk_tcc_enabled),enableAdaption:!!(null===(m=this.masterResSettings)||void 0===m?void 0:m.sdk_video_adaption_enabled),enableSEI:!!this.options.enableSEI,enableSVC:this.enableSVC,canary:f||this.canary||null,enableNego:!!(null===(g=this.masterResSettings)||void 0===g?void 0:g.sdk_base_on_demand_enabled),ip:this.clientIP},this.logger),this.handleEvent();let r=yield this.client.join(this.getBRTCRoomId(),{id:Object(je.a)(this.userId),info:{version:h,device:`${nr.name}/${nr.version} ${ut.name}/${ut.version}`,ua:navigator.userAgent,role:this.role,comments:this.comments}},this.token,this.sessionId,"big"===this.roomType,!0===this.options.silence);this.sessionId=r.sessionId,C=r.connectConsume,O=r.joinConsume,P=r.connectCount,M=r.usedProxyConsume,this.collection&&this.collection.setCallId(r.callId);const i=this.client.getActiveProxy(),n=i.activeUrl||i.url||i.dcurl;/^webtransport:\/\//.test(n)?L="WebTransport":/^https?:\/\//.test(n)&&(L="DataChannel"),this.reportAction("signalChannelConnect",0,x,Q(),{proxy:{url:n,location:null!==(v=i.location)&&void 0!==v?v:"",consume:M}})}else c(this.webrtcType)&&(this.collection&&this.collection.setCallId(k.l),this.client=It.a.createClient({mode:this.mode,sdkAppId:+this.webrtcAppId,userId:Object(je.a)(this.userId),userSig:this.sign,useStringRoomId:!0,autoSubscribe:!1,enableAutoPlayDialog:!1,enableSEI:this.options.enableSEI}),O=Math.max(Q()-x,0),this.isEnableSmallStream?this.client.enableSmallStream():this.client.disableSmallStream(),this.handleEvent(),yield this.client.join({roomId:this.getBRTCRoomId()}),this.reportAction("signalChannelConnect",0,x,Q()));if(this.destroyed)throw new R(4013,"client 已调用 destroy 方法");this.reportTimer.isStarted()||this.reportTimer.start();const t={version:h,device:`${nr.name}/${nr.version} ${ut.name}/${ut.version}`,network:Qi.name,platform:"Web",role:this.role,ua:navigator.userAgent||"",vtConsume:A,usedProxyConsume:M,connectConsume:C,joinConsume:O,connectCount:P,totalConsume:I(),proxyType:L};this.reportAction("joinRoom",0,x,Q(),t),this.logger.info(`client join suceess, userId: ${this.userId}, userSig: ${this.userSig}, data: ${JSON.stringify(t)}`,"client"),this.isJoinning=!1,this.reportDeviceList(),c(this.webrtcType)&&Object(z.a)((()=>{Oe(this.remoteStreamMap,(e=>{ye(e,(e=>{e._brtcAddEventPadding_&&(delete e._addEventPadding_,this.fire(w,{stream:e}))}))}))}));try{N=()=>Ns(this,void 0,void 0,(function*(){return e.detectors?function(e,t,r,i){return Xi(this,void 0,void 0,(function*(){return nn(i,{sig:e,room_id:t,user_id:r})}))}(this.userSig,this.roomId,this.userId,e.detectors):Promise.reject("no url to post")})),$=this.joinFailReport.bind(this),vn||(_n=N,bn=$,vn=!0,Cn())}catch(e){}}catch(e){this.isJoinning=!1;let t=dt(e),r=function(e,t){return R.instanceOf(e)?e.getCode():t}(e,4e3);if("request timeout"===t?r=4011:"connect all proxies failed"===t&&(r=4012),a(this.webrtcType)){const e=null===(y=this.client)||void 0===y?void 0:y.getActiveProxy();e&&(t=`error: ${t}, url: ${e.url||e.dcurl}, location: ${null!==(b=e.location)&&void 0!==b?b:""}`)}throw this.reportAction("joinRoom",r,x,Q(),{version:h,device:`${nr.name}/${nr.version} ${ut.name}/${ut.version}`,network:Qi.name,platform:"Web",role:this.role,ua:navigator.userAgent||"",msg:t},pt(e)),this.clearObject(),this.joinFailReport(r,"client join failed, "+t,{vError:pt(e)}),this.logger.error(`client join fail, userId: ${this.userId}, error: ${dt(e)}`,"client"),new R(4e3,"client join 失败",e)}}))}leave(e="none"){return Ns(this,void 0,void 0,(function*(){if(!this.client)throw new R(1002,"没有 joined");let t=Q();try{if(this.publishStream&&("rejoined"!==e&&"evicted"!==e&&"room_close"!==e&&(yield this.unpublish(this.publishStream)),this.publishStream.close()),Me(this.remoteStreamMap).length)for(let e in this.remoteStreamMap)ye(this.remoteStreamMap[e],(e=>{e.destroy()}))}catch(e){}try{a(this.webrtcType)?"rejoined"!==e&&"evicted"!==e&&"room_close"!==e&&(yield this.client.leave()):c(this.webrtcType)&&(yield this.client.leave()),this.reportAction("leaveRoom",0,t,Q(),{reason:e}),this.logger.info("client leave success, userId: "+this.userId,"client"),this.clearObject()}catch(r){throw this.reportAction("leaveRoom",ht(r),t,Q(),{reason:e},pt(r)),this.logger.error(`client leave fail, userId: ${this.userId}, error: ${dt(r)}`,"client"),this.clearObject(),new R(ht(r),"client leave 失败",r)}}))}clear(){try{if(this.publishStream){if(a(this.webrtcType)){let e=this.publishStream.getStream();this.client.unpublish(e)}else c(this.webrtcType)&&this.client&&this.client.unpublish(this.publishStream.getStream());this.publishStream.setClient(null),this.publishStream.setCollection(null),this.publishStream.setPrivileges(null),this.publishStream=null}if(Me(this.remoteStreamMap).length)for(let e in this.remoteStreamMap)ye(this.remoteStreamMap[e],(e=>{e.destroy()}));a(this.webrtcType)?this.client&&this.client.leave():c(this.webrtcType)&&this.client&&this.client.leave()}catch(e){}this.clearObject()}_publish(e,t=0){var r,i;return Ns(this,void 0,void 0,(function*(){let n=e.getStream();try{yield this.client.publish(n,{acodec:this.audioCodec,vcodec:this.codec,simulcast:this.isEnableSmallStream?2:1,encodings:this.getEncodings(e),audioBitrate:1024*e.getAudioBandwidth()})}catch(n){if(t>=(null!==(r=this.reportThreshold.brtc_flow_retry_times)&&void 0!==r?r:3)-1)throw n;yield new Hi(null!==(i=this.reportThreshold.brtc_flow_retry_interval)&&void 0!==i?i:1),yield this._publish(e,++t)}}))}publish(e){return Ns(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("publish, client 未 join,请先执行 join"),new R(1002,"client 未 join,请先执行 join");if("audience"===this.role)throw this.logger.error("publish, audience(观众)不支持推流,请先执行 switchRole 切换角色为 anchor(主播)"),new R(1002,"audience(观众)不支持推流,请先执行 switchRole 切换角色为 anchor(主播)");if(!(e instanceof Gi))throw this.logger.error("publish, stream 参数错误"),new R(1001,"stream 参数错误");if(e.hasAudio()&&this.privileges.enableAuth()&&!this.privileges.canPushAudio())throw this.logger.error("publish, 没有音频推送权限"),new R(1011,"没有音频推送权限");if(e.hasVideo()&&this.privileges.enableAuth()&&!this.privileges.canPushVideo())throw this.logger.error("publish, 没有视频推送权限"),new R(1012,"没有视频推送权限");if(!e.getStream())throw this.logger.error("publish, LocalStream 未初始化"),new R(1002,"LocalStream 未初始化");if(!e.hasAudio()&&!e.hasVideo())throw this.logger.error("publish, LocalStream 至少需要一个媒体轨道"),new R(1002,"LocalStream 至少需要一个媒体轨道");if(this.publishStream&&this.publishStream!==e)throw this.logger.error("publish, 当前已在推流,请先执行 unpublish 取消之前的 localstream 推流再推新的 localstream"),new R(1002,"当前已在推流,请先执行 unpublish 取消之前的 localstream 推流再推新的 localstream");e.setUserId(this.userId),e.setLogger(this.logger),this.webrtcType!==e.getWebRTCType()&&(yield e.switchWebRTC(this.webrtcType));let t=Q();e.setICEStartTS(t),this.logger.info("user call publish, streamId: "+e.getStreamId());let r={};e.hasAudio()&&(r.audio={codec:this.audioCodec.toLocaleUpperCase(),bitrate:e.getAudioBandwidth()}),e.hasVideo()&&(r.video={w:e.streamCodecOption.width,h:e.streamCodecOption.height,fps:e.streamCodecOption.frameRate,bitrate:e.streamCodecOption.bitrate,codec:this.codec.toLocaleUpperCase()});try{if(e.getAudioOn()&&this.reportAction("audioEnable",0,null,null,{stream:e.getActionStreamId()}),e.getVideoOn()&&this.reportAction("videoEnable",0,null,null,{stream:e.getActionStreamId()}),a(this.webrtcType))yield this._publish(e),this.fire(C,{stream:e});else if(c(this.webrtcType)){if(this.isEnableSmallStream){const t=this.getEncodings(e);this.client.setSmallStreamProfile({width:t[0].width,height:t[0].height,framerate:e.getStreamCodecOption().frameRate,bitrate:this.smallStreamCodecOption.bitrate})}yield this.client.publish(e.getStream()),this.fire(C,{stream:e})}this.publishStream=e,e.setClient(this),e.setCollection(this.collection),e.setPrivileges(this.privileges),e.syncClientOptions(this.options),this.publishNamespace&&e.has(this.publishNamespace)&&e.off(this.publishNamespace),e.on(he+this.publishNamespace,(()=>{this.publishStream===e&&(this.publishStream=null)})),this.reportAction("publish",0,t,Q(),{cameraId:e.streamDeviceOption.cameraId||(e.streamDeviceOption.screen?"screen":"track"),microphoneId:e.streamDeviceOption.microphoneId||"track",stream:e.getActionStreamId(),audio:e.hasAudio(),video:e.hasVideo(),audio_enable:e.getAudioOn(),video_enable:e.getVideoOn(),attribute:r,msip:e.getMSIP()}),this.logger.info("client publish success, userId: "+this.userId,"client")}catch(i){throw this.reportAction("publish",ht(i),t,Q(),{cameraId:e.streamDeviceOption.cameraId||(e.streamDeviceOption.screen?"screen":"track"),microphoneId:e.streamDeviceOption.microphoneId,stream:e.getActionStreamId(),audio:e.hasAudio(),video:e.hasVideo(),audio_enable:e.getAudioOn(),video_enable:e.getVideoOn(),attribute:r,msip:e.getMSIP()},pt(i)),this.logger.error(`client publish fail, userId: ${this.userId}, error: ${dt(i)}`,"client"),new R(ht(i),"推流失败",i)}}))}unpublish(e){return Ns(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("unpublish, client 未 join,请先执行 join"),new R(1002,"client 未 join,请先执行 join");if(!(e instanceof Gi))throw this.logger.error("unpublish, stream 参数错误"),new R(1001,"stream 参数错误");if(!this.publishStream)throw this.logger.error("unpublish, stream 未发布"),new R(1002,"stream 未发布");let t=Q(),r=e.getActionStreamId();this.logger.info("user call unpublish, streamId: "+e.getStreamId());try{if(a(this.webrtcType)){let t=e.getStream();yield this.client.unpublish(t)}else c(this.webrtcType)&&(yield this.client.unpublish(e.getStream()));this.reportAction("unpublish",0,t,Q(),{stream:r}),e.setClient(null),e.setCollection(null),e.setPrivileges(null),this.publishStream=null,this.logger.info("client unpublish success, userId: "+this.userId,"client")}catch(e){throw this.publishStream=null,this.reportAction("unpublish",ht(e),t,Q(),{stream:r},pt(e)),this.logger.error(`client unpublish fail, userId: ${this.userId}, error: ${dt(e)}`,"client"),new R(ht(e),"取消推流失败",e)}}))}_subscribe(e,t,r=0){var i,n;return Ns(this,void 0,void 0,(function*(){let s=e.getStream();if(!s)throw new R(4010,"stream 已被销毁");try{yield Promise.race([yield this.client.subscribe(s,{audio:t.audio,video:t.video,audioEnable:!(!1===t.audioEnable),videoEnable:!(!1===t.videoEnable),profile:"small"===t.streamType?0:1}).then((()=>(e.onSubscribe(),0))),new Hi(10)]).then((t=>{if(t)throw new R(4007,`订阅流 ${e.getUserId()} 超时`)}))}catch(s){if(r>=(null!==(i=this.reportThreshold.brtc_flow_retry_times)&&void 0!==i?i:3)-1||s&&!1===s.retry)throw s;yield new Hi(null!==(n=this.reportThreshold.brtc_flow_retry_interval)&&void 0!==n?n:1),this.logger.warn(`client retry subscribe, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()}`),yield this._subscribe(e,t,++r)}}))}subscribe(e,t={audio:!0,video:!0}){return Ns(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("subscribe, client 未 join,请先执行 join"),new R(1002,"client 未 join,请先执行 join");if(!(e instanceof Dt))throw this.logger.error("subscribe, stream 参数错误"),new R(1001,"stream 参数错误");if(!e.getStream())throw this.logger.error("subscribe, stream 已被销毁"),new R(1002,"stream 已被销毁");if(this.publishOnly)throw this.logger.error("subscribe, 当前 client 已被设置为只能 publish 流"),new R(1002,"当前 client 已被设置为只能 publish 流");if(!t.audio&&!t.video)throw this.logger.error("subscribe, 音频和视频至少需要订阅一个"),new R(1002,"音频和视频至少需要订阅一个");if(e.isUnpublish())throw this.logger.error("subscribe, stream 已不存在,无法再次订阅"),new R(1002,"stream 已不存在,无法再次订阅");o.i(t.streamType)||(t.streamType="big");let r=Q();e.setICEStartTS(r),e.onUnsubscribe(),this.logger.info(`user call subscribe, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()}`);try{a(this.webrtcType)?(yield this._subscribe(e,t),e.subscribeOptions=t,this.fire(M,{stream:e}),this.reportAction("subscribe",0,r,Q(),{audio:t.audio,video:t.video,stream:e.getActionStreamId(),msip:e.getMSIP(),remote_id:Object(je.a)(e.getUserId())}),this.fire(k,{stream:e})):c(this.webrtcType)&&("small"===t.streamType&&(yield this.client.setRemoteVideoStreamType(e.getStream(),t.streamType)),yield Promise.race([new Promise(((r,i)=>{this.promiseHoldMap[e.getUserId()]={resolve:r,reject:i},this.client.subscribe(e.getStream(),t)})),new Hi(10)]).then((t=>{if(t)throw delete this.promiseHoldMap[e.getUserId()],new R(4007,`订阅流 ${e.getUserId()} 超时`)})),e.onSubscribe(),e.subscribeOptions=t,this.reportAction("subscribe",0,r,Q(),{audio:t.audio,video:t.video,stream:e.getActionStreamId(),msip:e.getMSIP(),remote_id:Object(je.a)(e.getUserId())})),this.logger.info(`client subscribe success, userId: ${this.userId}, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()} options: ${JSON.stringify(t)}`,"client")}catch(i){if(this.logger.error(`client subscribe fail, userId: ${this.userId}, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()} error: ${dt(i)}`,"client"),this.reportAction("subscribe",ht(i),r,Q(),{audio:t.audio,video:t.video,stream:e.getActionStreamId(),msip:e.getMSIP(),remote_id:Object(je.a)(e.getUserId())},pt(i)),R.instanceOf(i))throw new R(i.code,i.message);throw new R(ht(i),null,i)}}))}unsubscribe(e){return Ns(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("unsubscribe, client 未 join,请先执行 join"),new R(1002,"client 未 join,请先执行 join");if(!(e instanceof Dt))throw this.logger.error("unsubscribe, stream 参数错误"),new R(1001,"stream 参数错误");if(!e.getStream())throw this.logger.error("unsubscribe, stream 已被销毁"),new R(1002,"stream 已被销毁");if(this.publishOnly)throw this.logger.error("unsubscribe, 当前 client 已被设置为只能 publish 流"),new R(1002,"当前 client 已被设置为只能 publish 流");let t=Q(),r=e.getActionStreamId();this.logger.info(`user call unsubscribe, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()}`);try{if(a(this.webrtcType)){let t=e.getStream();yield this.client.unsubscribe(t)}else c(this.webrtcType)&&(yield this.client.unsubscribe(e.getStream()));e.onUnsubscribe(),e.subscribeOptions=null,this.reportAction("unsubscribe",0,t,Q(),{stream:r,remote_id:Object(je.a)(e.getUserId())}),this.logger.info(`client unsubscribe success, userId: ${this.userId}, streamUserId: ${e.getUserId()}`,"client")}catch(i){throw e.onUnsubscribe(),this.reportAction("unsubscribe",ht(i),t,Q(),{stream:r,remote_id:Object(je.a)(e.getUserId())},pt(i)),this.logger.error(`client unsubscribe fail, userId: ${this.userId}, streamUserId: ${e.getUserId()}, error: ${dt(i)}`,"client"),new R(ht(i),"unsubscribe",i)}}))}enableSmallStream(){return Ns(this,void 0,void 0,(function*(){if(!Mn())throw new R(1002,"不支持大小流");this.publishStream&&this.logger.warn("enableSmallStream 不支持在 publish 之后设置, userId: "+this.userId,"client"),this.isEnableSmallStream=!0,this.client&&c(this.webrtcType)&&this.client.enableSmallStream()}))}disableSmallStream(){return Ns(this,void 0,void 0,(function*(){if(this.publishStream)throw new R(1002,"不支持在 publish 之后设置");this.isEnableSmallStream=!1,this.client&&c(this.webrtcType)&&this.client.disableSmallStream()}))}setRemoteVideoStreamType(e,t){return Ns(this,void 0,void 0,(function*(){if(!e.isSubscribed())throw new R(1002,"只能在订阅之后设置");if(!e.getStream())throw new R(1002,"流已不存在");const r=Q();try{if(a(this.webrtcType)){let r=e.getStream();yield this.client.preferProfile(r,"big"===t?1:0)}else c(this.webrtcType)&&(yield this.client.setRemoteVideoStreamType(e.getStream(),t));this.reportAction("simulcastSwitch",0,r,Q(),{stream:e.getActionStreamId(),remote_id:Object(je.a)(e.getUserId()),type:0,layer:"big"===t?1:0})}catch(i){throw this.reportAction("simulcastSwitch",ht(i),r,Q(),{stream:e.getActionStreamId(),remote_id:Object(je.a)(e.getUserId()),type:0,layer:"big"===t?1:0},pt(i)),this.logger.error(`client setRemoteVideoStreamType fail, userId: ${this.userId}, streamUserId: ${e.getUserId()}, error: ${dt(i)}`,"client"),new R(9e3,"setRemoteVideoStreamType",i)}}))}setSmallStreamProfile(e){Le(this.smallStreamCodecOption,e)}switchRole(e){return Ns(this,void 0,void 0,(function*(){this.role=e}))}pullUsers(e=120){return Ns(this,void 0,void 0,(function*(){if(!this.client)throw new R(1002,"client 未 join,请先执行 join");if(!a(this.webrtcType))throw new R(1002,"not support");return this.client.pullUsers(e)}))}queryUsers(e){return Ns(this,void 0,void 0,(function*(){if(!a(this.webrtcType))throw new R(1002,"不支持的操作");if(!this.client)throw new R(1002,"client 未 join,请先执行 join");if(!o.a(e))throw new R(1001,"需要传入 userIds 参数");return this.useStringUserId?ye(e,(e=>{if(!o.i(e))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:e}),new R(1001,"userId 类型错误,请检查");if(!/^[0-9a-zA-Z-_]{1,64}$/.test(e))throw this.joinFailReport(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符",{userId:e}),new R(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符")})):ye(e,(e=>{if(!o.f(e))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:e}),new R(1001,"userId 类型错误,请检查");if(e>Math.pow(2,31)-1||e<-Math.pow(2,31)||Math.floor(e)!==e)throw this.joinFailReport(1001,"userId 为 int32 整型",{userId:e}),new R(1001,"userId 为 int32 整型")})),ye(e,(e=>{if(e===this.userId)throw new R(1002,"不能传自己的 userId")})),(yield this.client.queryUsers(e.map((e=>Object(je.a)(e))))).map((e=>{let t=new Dt(q(e.getUserId(),this.useStringUserId),this.webrtcType,e,e.getStreamId());const r=t.getUserId(),i=t.getStreamId();t.setLogger(this.logger),t.setClient(this),t.setCollection(this.collection),t.syncClientOptions(this.options);const n=this.remoteStreamMap[r]||[];if(n.length){let e=-1;if(ye(n,((t,r)=>{if(t.getStreamId()===i)return e=r,!1})),e>-1)return t.destroy(),n[e]}return n.push(t),this.remoteStreamMap[r]=n,t.on(he,(()=>{let e=this.remoteStreamMap[r];if(e&&e.length){let t=-1;ye(e,((e,r)=>{if(e.getStreamId()===i)return t=r,!1})),t>-1&&e.splice(t,1),0===e.length&&delete this.remoteStreamMap[r]}})),t}))}))}getMediaServers(){return Ns(this,void 0,void 0,(function*(){if(!this.client)throw new R(1002,"client 未 join,请先执行 join");return this.client.getMediaServers()}))}setMediaServer(e,t){return Ns(this,void 0,void 0,(function*(){if(!a(this.webrtcType))throw new R(1002,"不支持的操作");return this.client.setMediaServer(e,Object(je.a)(t))}))}handleEvent(){let e=this,t=Ut[e.webrtcType],r=Bt[e.webrtcType],i=this.publishOnly?[]:$t;function n(t,i){e.client.on(t,(function(){let t=H(r[i],e,Te(arguments));t&&o.d(t.then)?t.then((t=>{!1!==t&&(o.a(t)&&2===t.length?e.fire(t[0],t[1]):e.fire(i,t),e.logger.debug(`client event ${i}, userId: ${e.userId}`,"client"))})):!1!==t&&(o.a(t)&&2===t.length?e.fire(t[0],t[1]):e.fire(i,t),e.logger.debug(`client event ${i}, userId: ${e.userId}`,"client"))}))}ye(i,(e=>{t[e]&&(o.a(t[e])?ye(t[e],((t,r)=>{n(t,e)})):o.i(t[e])&&t[e]&&n(t[e],e))})),a(e.webrtcType)?e.client.on("media-error",(t=>{e.fire(D,new R(4008))})).on("reconnected",(()=>{var t;const r=e.client.getActiveProxy();e.reportAction("signalChannelConnect",0,0,0,{proxy:{url:r.url||r.dcurl,location:null!==(t=r.location)&&void 0!==t?t:""}})})).on("proxy-changed",(()=>{var t;const r=e.client.getActiveProxy();e.reportAction("changeSignalNode",0,0,0,{proxy:{url:r.url||r.dcurl,location:null!==(t=r.location)&&void 0!==t?t:""}})})).on("state-notify",(e=>{this.joinFailReport(8e3,"state notify, "+e.msg,e)})).on("stream-update",(t=>{const r=this.getRemoteStream(t.getUserId(),t.getStreamId());r?r.onMediaUpdate(this):e.logger.warn(`stream update but not found the remotestream, userId: ${this.getUserId()}, streamUserId: ${t.getUserId()}, streamId: ${t.getStreamId()}`)})):c(e.webrtcType)&&(e.on(M,(t=>{e.promiseHoldMap[t.stream.getUserId()]&&(e.promiseHoldMap[t.stream.getUserId()].resolve(0),delete e.promiseHoldMap[t.stream.getUserId()])})),e.client.on("sei-message",(e=>{const{userId:t,data:r,seiPayloadType:i}=e,n=this.getRemoteStream(t);n&&n.fire("stream-sei-message",{data:r,payloadType:i})}))),e.publishOnly&&(a(e.webrtcType)?e.client.on("stream-added",(e=>{e.destroy()})):c(this.webrtcType)&&e.client.on(w,(e=>{e.stream.close()}))),this.logger.info(`userId: ${this.userId}, publishOnly: ${this.publishOnly}`),this.logger.debug(`add event hanlder success, userId: ${this.userId}, events: ${i.join(",")}`,"client")}fire(e,t){this.emitter&&(e===D&&this.clear(),this.emitter.fire(e,t?[t]:void 0))}on(e,t){return this.emitter.on(e,{fn:t,ctx:this}),this.logger.debug(`client on, userId: ${this.userId}, type: ${e}`,"client"),this}one(e,t){return this.emitter.on(e,{fn:t,ctx:this,max:1}),this.logger.debug(`client one, userId: ${this.userId}, type: ${e}`,"client"),this}off(e,t){return this.emitter&&(this.emitter.off(e,t),this.logger.debug(`client off, userId: ${this.userId}, type: ${e}`,"client")),this}setPublishOnly(e){this.publishOnly=e,this.logger.info(`client publish only, userId: ${this.userId}, value: ${e}`,"client")}destroy(e){return Ns(this,void 0,void 0,(function*(){if(this.emitter&&(this.emitter.off(),this.emitter=null),e?this.clear():this.client&&(yield this.leave()),this.publishStream=null,this.remoteStreamMap={},this.reportTimer&&(this.reportTimer.destroy(),this.reportTimer=null),this.ondevicechangeHandler)try{navigator.mediaDevices.removeEventListener("devicechange",this.ondevicechangeHandler),this.ondevicechangeHandler=null}catch(e){}this.destroyed=!0,this.logger.info("client destroy, userId: "+this.userId,"client")}))}addRemoteStream(e){e.setClient(this),e.setCollection(this.collection),e.syncClientOptions(this.options);const t=this.remoteStreamMap[e.getUserId()]||[];if(t.length){let r=-1;ye(t,((t,i)=>{if(t.getStreamId()===e.getStreamId())return r=i,!1})),r>-1&&(t[r].destroy(),t.splice(r,1))}t.push(e),this.remoteStreamMap[e.getUserId()]=t}removeRemoteStream(e,t){let r,i=this.remoteStreamMap[e];if(i&&i.length)if(t){let n=-1;ye(i,((e,r)=>{if(e.getStreamId()===t)return n=r,!1})),n>-1&&(r=i[n],i.splice(n,1),r.destroy()),0===i.length&&(this.remoteStreamMap[e]=null)}else ye(i,(e=>{e.destroy()})),this.remoteStreamMap[e]=null;return r}getRemoteStream(e,t){const r=this.remoteStreamMap[e];let i;if(r&&r.length)if(t){let e=-1;ye(r,((r,i)=>{if(r.getStreamId()===t)return e=i,!1})),e>-1&&(i=r[e])}else ye(r,(e=>{if("main"===e.getType())return i=e,!1}));return i}getActiveProxy(){var e;return null===(e=this.client)||void 0===e?void 0:e.getActiveProxy()}getClient(){return this.client}reportStats(){if(!this.collection)return;let e=!0;if(this.publishStream&&(e=!1,this.publishStream.getReportStats(this.reportThreshold).then((e=>{this.collection.stats(this.publishStream.getActionStreamId(),e,!0,null,this.publishStream.getExtraReport())})).catch((function(e){}))),Me(this.remoteStreamMap).length){e=!1;for(let e in this.remoteStreamMap)ye(this.remoteStreamMap[e],(e=>{e.isSubscribed()&&e.getReportStats(this.reportThreshold).then((t=>{this.collection.stats(e.getActionStreamId(),t,!1,Object(je.a)(e.getUserId()),e.getExtraReport())})).catch((function(e){}))}))}e&&this.collection.heartbeat()}reportAction(e,t,r,i,n,s){this.collection&&this.collection.action(e,t,r,i,n,s)}getEncodings(e){const t=e.getStreamCodecOption(),r=e.getSourceVideoTrack();let i=t.width,n=t.height,s=t.frameRate;if(r&&r.getSettings){const e=r.getSettings();o.f(e.width)&&(i=e.width),o.f(e.height)&&(n=e.height),o.f(e.frameRate)&&(s=Math.floor(e.frameRate))}if(this.isEnableSmallStream&&(!ut.chrome||i>=398&&n>=308)){const e=Math.min(Math.max(Math.max(tt((i/this.smallStreamCodecOption.width).toFixed(2)),tt((n/this.smallStreamCodecOption.height).toFixed(2))),1),10);return[{active:!0,scale:e,bitrate:1024*this.smallStreamCodecOption.bitrate,fps:t.frameRate||s,width:Math.ceil((t.width||i)/e),height:Math.ceil((t.height||n)/e),rid:"r0",scalabilityMode:this.enableSVC?this.masterResSettings.sdk_video_svc_mode:"L1T1"},{active:!0,scale:1,bitrate:1024*t.bitrate,fps:t.frameRate||s,width:t.width||i,height:t.height||n,rid:"r1",scalabilityMode:this.enableSVC?this.masterResSettings.sdk_video_svc_mode:"L1T1"}]}return this.isEnableSmallStream&&ut.chrome&&(i<398||n<308)&&this.logger.warn("无法开启大小流因为需要视频宽度大于 398,高度大于 308"),[{active:!0,scale:1,bitrate:1024*t.bitrate,fps:t.frameRate||s,width:t.width||i,height:t.height||n,scalabilityMode:this.enableSVC?this.masterResSettings.sdk_video_svc_mode:"L1T1"}]}}var Us=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class Bs extends class{constructor(e,t,r){this.gl=e,this.width=t,this.height=r,this.texture=this.gl.createTexture()}getTexture(){return this.texture}bind(e){o.f(e)&&this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture)}setSize(e,t){this.width=e,this.height=t}setUnpackAlignment(){this.width%8==0?this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,8):this.width%4==0?this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,4):this.width%2==0?this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,2):this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,1)}destroy(){this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}{constructor(e,t,r,i=!1){super(e,t,r),this.useMultisample=i}init(){this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.width,this.height,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.useMultisample?(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR)):(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE))}fill(e){this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.setUnpackAlignment(),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e)}}class Vs{constructor(e,t,r,i){this.gl=e,this.width=t,this.height=r,this.useMultisample=i,this.init()}init(){this.framebuffer=this.gl.createFramebuffer(),this.colorBuffer=this.gl.createRenderbuffer(),this.texture=new Bs(this.gl,this.width,this.height,this.useMultisample),this.texture.bind(),this.texture.init(),this.useMultisample?(this.renderbuffer=this.gl.createFramebuffer(),this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,this.colorBuffer),this.gl.renderbufferStorageMultisample(this.gl.RENDERBUFFER,4,this.gl.RGBA8,this.width,this.height),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.renderbuffer),this.gl.framebufferRenderbuffer(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.RENDERBUFFER,this.colorBuffer),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.framebuffer),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.texture.getTexture(),0)):(this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,this.colorBuffer),this.gl.renderbufferStorage(this.gl.RENDERBUFFER,this.gl.DEPTH_COMPONENT16,this.width,this.height),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.framebuffer),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.texture.getTexture(),0),this.gl.framebufferRenderbuffer(this.gl.FRAMEBUFFER,this.gl.DEPTH_ATTACHMENT,this.gl.RENDERBUFFER,this.colorBuffer)),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null)}toVertices(){return[-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0]}length(){return 4}viewport(){this.gl.viewport(0,0,this.width,this.height)}destroy(){this.framebuffer&&(this.gl.deleteFramebuffer(this.framebuffer),this.framebuffer=null),this.renderbuffer&&(this.gl.deleteFramebuffer(this.renderbuffer),this.renderbuffer=null),this.colorBuffer&&(this.gl.deleteRenderbuffer(this.colorBuffer),this.colorBuffer=null),this.texture&&this.texture.destroy()}getTexture(){return this.texture}getFrameBuffer(){return this.useMultisample?this.renderbuffer:this.framebuffer}getResolution(){return[1/this.width,1/this.height]}getWidth(){return this.width}getHeight(){return this.height}bind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.getFrameBuffer())}clear(){this.gl.clear(this.gl.COLOR_BUFFER_BIT|this.gl.DEPTH_BUFFER_BIT)}resize(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this.destroy(),this.init())}}var Fs=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};class js{constructor(e){this.gl=e.getGL(),this.width=e.getWidth(),this.height=e.getHeight(),this.frame=new Vs(this.gl,this.width,this.height,!1),this.enabled=!0}ready(){return Fs(this,void 0,void 0,(function*(){return!0}))}resize(e,t){this.width=e,this.height=t,this.frame.resize(e,t)}getTarget(){return this.frame}setEnabled(e){this.enabled=e}getEnabled(){return this.enabled}getVertices(){return[-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0]}}class Ws extends class{constructor(e,t,r){this.gl=e,this.vertexShader=t,this.fragmentShader=r,this.vertexShader&&this.vertexShader.compile(e),this.fragmentShader&&this.fragmentShader.compile(e)}link(){this._program=this.gl.createProgram(),this.gl.attachShader(this._program,this.vertexShader.shader),this.gl.attachShader(this._program,this.fragmentShader.shader),this.gl.linkProgram(this._program)}stop(){this.vertexShader.stop(this.gl),this.fragmentShader.stop(this.gl),this.gl.deleteProgram(this._program),this.vertexShader=null,this.fragmentShader=null,this._program=null}bind(){this.gl.useProgram(this._program)}get program(){return this._program}}{constructor(e,t,r,i=!0){super(e,t,r),this.enableColor=i}link(){super.link(),this.aPoint=this.gl.getAttribLocation(this.program,"point"),this.aColor=this.gl.getAttribLocation(this.program,"color"),this.enableColor?(this.gl.enableVertexAttribArray(this.aPoint),this.gl.enableVertexAttribArray(this.aColor)):this.gl.enableVertexAttribArray(this.aPoint)}bind(){super.bind(),this.enableColor?(this.gl.vertexAttribPointer(this.aPoint,3,this.gl.FLOAT,!1,7*Float32Array.BYTES_PER_ELEMENT,0),this.gl.vertexAttribPointer(this.aColor,4,this.gl.FLOAT,!1,7*Float32Array.BYTES_PER_ELEMENT,3*Float32Array.BYTES_PER_ELEMENT)):this.gl.vertexAttribPointer(this.aPoint,3,this.gl.FLOAT,!1,7*Float32Array.BYTES_PER_ELEMENT,0)}}class qs{constructor(e,t){this.type=e,this._shader=null,this._source=t,this.compiled=!1}compile(e){this.compiled||(this._shader=e.createShader(this.type),e.shaderSource(this._shader,this._source),e.compileShader(this._shader),this.compiled=!0)}stop(e){e.deleteShader(this._shader),this._shader=null}get shader(){return this._shader}}class Gs extends qs{constructor(e,t){super(e.VERTEX_SHADER,t)}}class Hs extends qs{constructor(e,t){super(e.FRAGMENT_SHADER,t)}}class zs extends Ws{constructor(e){super(e,new Gs(e,"precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 point;\nattribute vec4 color;\nvarying vec4 v_color;\n\nvoid main(void){\n gl_Position = vec4(point, 1.0);\n v_color = color;\n}\n"),new Hs(e,"precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 v_color;\nuniform sampler2D u_Sampler;\n\nuniform vec2 singleStepOffset;\nuniform vec4 params;\nuniform float brightness;\n\nconst vec3 W = vec3(0.299, 0.587, 0.114);\n\nconst mat3 saturateMatrix = mat3(\n 1.1102, -0.0598, -0.061,\n -0.0774, 1.0826, -0.1186,\n -0.0228, -0.0228, 1.1772);\n\nvec2 blurCoordinates[24];\n\nfloat hardLight(float color) {\n if (color <= 0.5) {\n color = color * color * 2.0;\n }\n else {\n color = 1.0 - ((1.0 - color)*(1.0 - color) * 2.0);\n }\n return color;\n}\n\nvoid main() {\n\n vec2 coord = v_color.xy;\n \n vec3 centralColor = texture2D(u_Sampler, coord).rgb;\n blurCoordinates[0] = coord.xy + singleStepOffset * vec2(0.0, -10.0);\n blurCoordinates[1] = coord.xy + singleStepOffset * vec2(0.0, 10.0);\n blurCoordinates[2] = coord.xy + singleStepOffset * vec2(-10.0, 0.0);\n blurCoordinates[3] = coord.xy + singleStepOffset * vec2(10.0, 0.0);\n blurCoordinates[4] = coord.xy + singleStepOffset * vec2(5.0, -8.0);\n blurCoordinates[5] = coord.xy + singleStepOffset * vec2(5.0, 8.0);\n blurCoordinates[6] = coord.xy + singleStepOffset * vec2(-5.0, 8.0);\n blurCoordinates[7] = coord.xy + singleStepOffset * vec2(-5.0, -8.0);\n blurCoordinates[8] = coord.xy + singleStepOffset * vec2(8.0, -5.0);\n blurCoordinates[9] = coord.xy + singleStepOffset * vec2(8.0, 5.0);\n blurCoordinates[10] = coord.xy + singleStepOffset * vec2(-8.0, 5.0);\n blurCoordinates[11] = coord.xy + singleStepOffset * vec2(-8.0, -5.0);\n blurCoordinates[12] = coord.xy + singleStepOffset * vec2(0.0, -6.0);\n blurCoordinates[13] = coord.xy + singleStepOffset * vec2(0.0, 6.0);\n blurCoordinates[14] = coord.xy + singleStepOffset * vec2(6.0, 0.0);\n blurCoordinates[15] = coord.xy + singleStepOffset * vec2(-6.0, 0.0);\n blurCoordinates[16] = coord.xy + singleStepOffset * vec2(-4.0, -4.0);\n blurCoordinates[17] = coord.xy + singleStepOffset * vec2(-4.0, 4.0);\n blurCoordinates[18] = coord.xy + singleStepOffset * vec2(4.0, -4.0);\n blurCoordinates[19] = coord.xy + singleStepOffset * vec2(4.0, 4.0);\n blurCoordinates[20] = coord.xy + singleStepOffset * vec2(-2.0, -2.0);\n blurCoordinates[21] = coord.xy + singleStepOffset * vec2(-2.0, 2.0);\n blurCoordinates[22] = coord.xy + singleStepOffset * vec2(2.0, -2.0);\n blurCoordinates[23] = coord.xy + singleStepOffset * vec2(2.0, 2.0);\n\n float sampleColor = centralColor.g * 22.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[0]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[1]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[2]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[3]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[4]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[5]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[6]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[7]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[8]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[9]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[10]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[11]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[12]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[13]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[14]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[15]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[16]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[17]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[18]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[19]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[20]).g * 3.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[21]).g * 3.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[22]).g * 3.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[23]).g * 3.0;\n\n sampleColor = sampleColor / 62.0;\n\n float highPass = centralColor.g - sampleColor + 0.5;\n\n for (int i = 0; i < 5; i++) {\n highPass = hardLight(highPass);\n }\n float lumance = dot(centralColor, W);\n float alpha = pow(lumance, params.r);\n vec3 smoothColor = centralColor + (centralColor - vec3(highPass)) * alpha * 0.1;\n\n smoothColor.r = clamp(pow(smoothColor.r, params.g), 0.0, 1.0);\n smoothColor.g = clamp(pow(smoothColor.g, params.g), 0.0, 1.0);\n smoothColor.b = clamp(pow(smoothColor.b, params.g), 0.0, 1.0);\n\n vec3 screen = vec3(1.0) - (vec3(1.0) - smoothColor) * (vec3(1.0) - centralColor);\n vec3 lighten = max(smoothColor, centralColor);\n vec3 softLight = 2.0 * centralColor * smoothColor + centralColor * centralColor - 2.0 * centralColor * centralColor * smoothColor;\n\n gl_FragColor = vec4(mix(centralColor, screen, alpha), 1.0);\n gl_FragColor.rgb = mix(gl_FragColor.rgb, lighten, alpha);\n gl_FragColor.rgb = mix(gl_FragColor.rgb, softLight, params.b);\n\n vec3 satcolor = gl_FragColor.rgb * saturateMatrix;\n gl_FragColor.rgb = mix(gl_FragColor.rgb, satcolor, params.a);\n gl_FragColor.rgb = vec3(gl_FragColor.rgb + vec3(brightness));\n}"))}link(){super.link(),this.samplerLocation=this.gl.getUniformLocation(this.program,"u_Sampler"),this.paramsLocation=this.gl.getUniformLocation(this.program,"params"),this.brightnessLocation=this.gl.getUniformLocation(this.program,"brightness"),this.singleStepOffsetLocation=this.gl.getUniformLocation(this.program,"singleStepOffset")}bindTexture(e=0){this.gl.uniform1i(this.samplerLocation,e)}setBrightness(e){this.gl.uniform1f(this.brightnessLocation,.37*(-.5+e))}setParams(e,t){this.gl.uniform4fv(this.paramsLocation,[1-.8*e,1-.6*e,.1+.45*t,.1+.45*t])}setSize(e,t){this.gl.uniform2fv(this.singleStepOffsetLocation,[2/e,2/t])}setOpacity(e=.5){this.gl.uniform1f(this.opacityLocation,e)}}class Js extends Ws{constructor(e){super(e,new Gs(e,"precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 point;\nattribute vec4 color;\nvarying vec4 v_color;\n\nvoid main(void){\n gl_Position = vec4(point, 1.0);\n v_color = color;\n}\n"),new Hs(e,"precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 v_color;\nuniform sampler2D u_Sampler;\nuniform float opacity;\n\nvoid main () {\n vec4 color = texture2D(u_Sampler, v_color.xy);\n color.a = color.a * opacity;\n gl_FragColor = color;\n}\n"))}link(){super.link(),this.samplerLocation=this.gl.getUniformLocation(this.program,"u_Sampler"),this.opacityLocation=this.gl.getUniformLocation(this.program,"opacity")}bindTexture(e=0){this.gl.uniform1i(this.samplerLocation,e)}setOpacity(e=1){(e<0||e>1)&&(e=1),this.gl.uniform1f(this.opacityLocation,e)}}function Ys(){return!("object"==typeof window&&Ce(window.document))}class Ks{constructor(){this.id=0,this.taskMap=new Map;const e=Je(29);this.worker=new Worker(e),this.workerUrl=e,this.worker.addEventListener("message",(e=>{const t=e.data,r=t.type,i=t.id;if("pong"===r){const e=this.taskMap.get(i);e&&e(!0)}}))}setTimeout(e,t=0){const r=this.id++;return this.taskMap.set(r,e),this.worker.postMessage({type:"ping",data:{timeout:t,id:r}}),r}clearTimeout(e){this.taskMap.delete(e)}destroy(){this.worker&&(this.worker.terminate(),this.worker=null),this.workerUrl&&(URL.revokeObjectURL(this.workerUrl),this.workerUrl=null),this.taskMap&&(this.taskMap.clear(),this.taskMap=null)}}let Qs,Xs=0;function Zs(){return Qs?(Xs++,Qs):(Qs=new Ks,Xs=1,Qs)}function eo(){0!==Xs&&(Xs--,0===Xs&&(Qs.destroy(),Qs=null))}class to{constructor(e,t=!0){this.started=!1,this.interval=e,this.highPerformance=t,this.a=.2,this.b=4,this.equivalent=50,this.timestamp=0,this.compute(),this.messageChannel=new MessageChannel,this.handleEvent(),this.timeoutNext=e=>{e?this.workerTimer=null:this.timer=null,this.running=!1,this.count++,this.onClock&&this.onClock(),this.nextTick()},Ys()||"hidden"!==document.visibilityState||(this.workerSetTimeout=Zs()),this.running=!1}compute(e=!0){this.interval>0&&(this.beta=Math.ceil(this.equivalent*(1-this.b/this.interval)/(this.a-this.b)),this.alpha=Math.floor(this.equivalent/this.interval-this.beta),e&&(this.count=0))}timeoutTick(){this.workerSetTimeout&&"hidden"===document.visibilityState&&this.interval<1e3?this.workerTimer=this.workerSetTimeout.setTimeout(this.timeoutNext,this.interval):this.timer=setTimeout(this.timeoutNext,this.interval)}nextTick(){if(this.started&&!this.running)if(this.running=!0,this.interval>4||!this.highPerformance)this.timeoutTick();else if(this.interval<=0)this.messageChannel.port1.postMessage(null);else{const e=J();e-this.timestamp>this.equivalent&&(this.count=0,this.timestamp=e),this.count<this.beta?this.messageChannel.port1.postMessage(null):this.timeoutTick()}}start(){this.started||(this.started=!0,this.timestamp=J(),this.nextTick())}stop(){this.started=!1,this.timer&&(clearTimeout(this.timer),this.timer=null),this.workerTimer&&this.workerSetTimeout&&this.workerSetTimeout.clearTimeout(this.workerTimer),this.running=!1}isStarted(){return this.started}setInterval(e){this.interval=Math.max(e,0),this.compute()}getInterval(){return this.interval}isZeroTimeout(){return this.interval<4}destroy(){this.stop(),this.workerSetTimeout&&(eo(),this.workerSetTimeout=null),this.onVisibilityChange&&(document.removeEventListener("visibilitychange",this.onVisibilityChange),this.onVisibilityChange=null)}handleEvent(){this.messageChannel.port2.onmessage=()=>{this.started&&(this.running=!1,this.count++,this.onClock&&this.onClock(),this.nextTick())},Ys()||(this.onVisibilityChange=Fe((e=>{"hidden"===document.visibilityState?(this.workerSetTimeout=Zs(),this.timer&&(clearTimeout(this.timer),this.timer=null,this.running=!1),this.nextTick()):(this.workerTimer&&(this.workerSetTimeout.clearTimeout(this.workerTimer),this.workerTimer=null,this.running=!1),this.timer&&(clearTimeout(this.timer),this.timer=null,this.running=!1),eo(),this.workerSetTimeout=null,this.nextTick())}),20),document.addEventListener("visibilitychange",this.onVisibilityChange))}}class ro{constructor(e,t=0,r=0,i=!0){this.task=e,this.timeout=t,this.interval=r,this.autoInterval=i,this.count=0,this.emptyCount=0,this.timestamp=0,this.started=!1,this.clock=new to(this.interval),this.clock.onClock=()=>{if(!this.started)return;this.count++,!1===this.task()&&this.stop();const e=J();if(this.autoInterval&&e-this.timestamp>50){const t=this.emptyCount/this.count;0===this.emptyCount?this.clock.setInterval(Math.max(this.clock.getInterval()>>1,this.interval)):t<.1?this.clock.setInterval(this.clock.getInterval()-1):t>.2?this.clock.setInterval(Math.min(this.clock.getInterval()+1,20)):t>.5&&this.clock.setInterval(this.clock.getInterval()<<1),this.count=0,this.emptyCount=0,this.timestamp=e}}}start(){this.started=!0,this.timeout?this.startTimer=setTimeout((()=>{this.count=0,this.emptyCount=0,this.timestamp=J(),this.clock.start(),this.startTimer=null}),this.timeout):(this.count=0,this.emptyCount=0,this.timestamp=J(),this.clock.start())}stop(){this.started=!1,this.startTimer&&(clearTimeout(this.startTimer),this.startTimer=null),this.clock.stop()}isStarted(){return this.started}emptyTask(){this.emptyCount++}isZeroTimeout(){var e;return null===(e=this.clock)||void 0===e?void 0:e.isZeroTimeout()}restart(){this.clock&&(this.stop(),this.clock.setInterval(this.interval),this.start())}destroy(){this.stop(),this.task=null,this.timeout=null,this.interval=null}}class io extends Ws{constructor(e){super(e,new Gs(e,"precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 point;\nattribute vec4 color;\nvarying vec4 v_color;\n\nvoid main(void){\n gl_Position = vec4(point, 1.0);\n v_color = color;\n}\n"),new Hs(e,"precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 v_color;\nuniform sampler2D u_Sampler;\n\nvoid main () {\n gl_FragColor = texture2D(u_Sampler, v_color.xy);\n}\n"))}link(){super.link(),this.samplerLocation=this.gl.getUniformLocation(this.program,"u_Sampler")}bindTexture(e=0){this.gl.uniform1i(this.samplerLocation,e)}}class no extends js{constructor(e){super(e),this.program=new io(this.gl),this.program.link()}render(e,t,r=0){return this.program.bind(),e.bind(r),this.program.bindTexture(r),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,t,4),{nextUnit:r+1,nextStartIndex:t+4}}destroy(){this.program.stop()}}var so,oo=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};!function(e){e.I420="I420",e.NV12="NV12",e.ABGR="ABGR",e.IMAGE_BIT_MAP="IMAGE_BIT_MAP"}(so||(so={}));class ao{constructor(e=300,t=150){this.width=e,this.height=t,this.sourceHeight=e,this.sourceHeight=t,this.cropTop=0,this.cropLeft=0,this.renders=[],this.verticalFlipEnabled=!1,this.horizontalFlipEnabled=!1,this.generateVertex(),this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,ut.safari&&(document.body.appendChild(this.canvas),this.canvas.style.position="absolute",this.canvas.style.left="-99999px"),this.gl=this.canvas.getContext("webgl2",{alpha:!0,antialias:!0,preserveDrawingBuffer:!0}),this.gl||(this.gl=this.canvas.getContext("webgl",{alpha:!0,antialias:!0,preserveDrawingBuffer:!0})),this.VAO=this.gl.createBuffer(),this.VAO||pe.fatal("顶点缓冲区创建失败"),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.VAO),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.enable(this.gl.BLEND),this.gl.clearColor(0,0,0,0),this.gl.clearDepth(1),this.gl.viewport(0,0,e,t),this.gl.blendFuncSeparate(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA,this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA),this.sourceTexture=new Bs(this.gl,this.sourceWidth,this.sourceHeight),this.sourceTexture.bind(0),this.sourceTexture.init(),this.supportTrackProcessor="undefined"!=typeof MediaStreamTrackProcessor&&!1,this.supportTrackProcessor||(this.video=document.createElement("video"),this.video.loop=!0,this.video.autoplay=!0,this.video.onloadedmetadata=()=>{this.renderTimer&&this.renderTimer.start()}),this.copyRender=new no(this)}generateVertex(){this.verticalFlipEnabled&&this.horizontalFlipEnabled?this.vertex=[-1,1,0,1,0,0,0,-1,-1,0,1,1,0,0,1,1,0,0,0,0,0,1,-1,0,0,1,0,0]:this.verticalFlipEnabled?this.vertex=[-1,1,0,0,0,0,0,-1,-1,0,0,1,0,0,1,1,0,1,0,0,0,1,-1,0,1,1,0,0]:this.horizontalFlipEnabled?this.vertex=[-1,1,0,1,1,0,0,-1,-1,0,1,0,0,0,1,1,0,0,1,0,0,1,-1,0,0,0,0,0]:this.vertex=[-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0]}bufferVertices(){let e=[-1,1,0,0+this.cropLeft,1-this.cropTop,0,0,-1,-1,0,0+this.cropLeft,0+this.cropTop,0,0,1,1,0,1-this.cropLeft,1-this.cropTop,0,0,1,-1,0,1-this.cropLeft,0+this.cropTop,0,0,-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0];e=e.concat(this.vertex),this.waterMarkProgram&&this.waterMarkTexture&&this.waterMarkEnabled&&(e=e.concat(this.waterMarkVertex)),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(e),this.gl.STATIC_DRAW)}generateWaterMarkVertex(){let e=this.waterMark.width,t=this.waterMark.height;const r=e>1||t>1;e&&!t?(t=this.imageElement.height*e/this.imageElement.width,t<1&&(t=t*this.width/this.height)):!e&&t?(e=this.imageElement.width*t/this.imageElement.height,e<1&&(e=e*this.height/this.width)):e||t||(e=100,t=this.imageElement.height*e/this.imageElement.width,t<1&&(t=t*this.width/this.height));let i=this.waterMark.left||0,n=this.waterMark.top||0;r?e=e/this.width*2:e*=2,r?t=t/this.height*2:t*=2,i<=1&&i>=0?i*=2:i=i/this.width*2,n<=1&&n>=0?n*=2:n=n/this.height*2,this.waterMarkVertex=[-1+i,1-n,0,0,1,0,0,-1+i,1-n-t,0,0,0,0,0,-1+i+e,1-n,0,1,1,0,0,-1+i+e,1-n-t,0,1,0,0,0]}resize(e,t,r,i){this.width=e,this.height=t,this.supportTrackProcessor&&r&&i?(this.sourceWidth=r,this.sourceHeight=i):(this.sourceWidth=e,this.sourceHeight=t),this.canvas.width=e,this.canvas.height=t,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.sourceTexture&&(this.sourceTexture.setSize(this.sourceWidth,this.sourceHeight),this.sourceTexture.init()),this.rgbaFrame&&this.rgbaFrame.resize(e,t);for(let r=0;r<this.renders.length;r++)this.renders[r].resize(e,t);this.copyRender.resize(e,t),this.generateWaterMarkVertex(),this.waterMarkTexture.fill(this.imageElement)}render(e,t,r){const i=this.renders.filter((e=>e.getEnabled()));if(i.length)for(let t=0;t<i.length;t++)t===i.length-1?this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null):this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,i[t].getTarget()),i[t].render(e,t===i.length-1?8:0===t?0:4,r++),e=i[t].getTarget().getTexture();else this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.copyRender.render(e,8,r++),e=this.copyRender.getTarget().getTexture();this.waterMarkProgram&&this.waterMarkTexture&&this.waterMarkEnabled&&0!==this.waterMark.width&&0!==this.waterMark.height&&(this.waterMarkProgram.bind(),this.waterMarkTexture.bind(this.format===so.IMAGE_BIT_MAP?0:3),this.waterMarkProgram.bindTexture(this.format===so.IMAGE_BIT_MAP?0:3),this.waterMarkProgram.setOpacity(o.f(this.waterMark.opacity)?this.waterMark.opacity:1),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,12,4))}readVideoFrame(){return oo(this,void 0,void 0,(function*(){if(!this.abortRequest)try{const{done:e,value:t}=yield this.videoFrameReader.read();if(e)return;t&&(yield this.renderVideoFrame(t)),this.readVideoFrame()}catch(e){throw console.log(e),new R(9e3,"read videoFrame failed!")}}))}renderVideoFrame(e){return oo(this,void 0,void 0,(function*(){e.displayWidth===this.width&&e.displayHeight===this.height&&e.codedWidth===this.sourceWidth&&e.codedHeight===this.sourceHeight||(this.resize(e.displayWidth,e.displayHeight,e.codedWidth,e.codedHeight),this.cropLeft=e.visibleRegion.left/e.visibleRegion.width,this.cropTop=e.visibleRegion.top/e.visibleRegion.height),this.bufferVertices(),this.sourceTexture.fill(e),e.close(),this.render(this.sourceTexture,0,1)}))}renderHTMLVideoElement(e){return oo(this,void 0,void 0,(function*(){(e.videoWidth>10&&e.videoWidth!==this.width||e.videoHeight>10&&e.videoHeight!==this.height)&&this.resize(e.videoWidth,e.videoHeight),this.bufferVertices(),this.sourceTexture.fill(e),this.render(this.sourceTexture,0,1)}))}addRender(e){this.renders.push(e)}removeRender(e){for(let t=0;t<this.renders.length;t++)if(this.renders[t]===e)return void this.renders.splice(t,1)}getGL(){return this.gl}getWidth(){return this.width}getHeight(){return this.height}enableVerticalFlip(e){this.verticalFlipEnabled=e,this.generateVertex()}enableHorizontalFlip(e){this.horizontalFlipEnabled=e,this.generateVertex()}onWaterMarkLoaded(){this.waterMarkProgram||(this.waterMarkProgram=new Js(this.gl),this.waterMarkProgram.link()),this.waterMarkTexture?(this.waterMarkTexture.setSize(this.imageElement.width,this.imageElement.height),this.waterMarkTexture.init()):(this.waterMarkProgram.bind(),this.waterMarkTexture=new Bs(this.gl,this.imageElement.width,this.imageElement.height,!1),this.waterMarkTexture.bind(this.format===so.IMAGE_BIT_MAP?0:3),this.waterMarkTexture.init(),this.waterMarkProgram.bindTexture(this.format===so.IMAGE_BIT_MAP?0:3)),this.waterMarkTexture.fill(this.imageElement),this.generateWaterMarkVertex()}setWaterMark(e){const t=!this.waterMark||this.waterMark.url!==e.url;this.waterMark=Le(this.waterMark||{},e),this.waterMark.url&&t?(this.imageElement||(this.imageElement=document.createElement("img"),this.imageElement.crossOrigin="Anonymous",this.imageElement.onload=this.onWaterMarkLoaded.bind(this)),this.imageElement.src=this.waterMark.url):this.generateWaterMarkVertex(),Ce(this.waterMarkEnabled)||(this.waterMarkEnabled=!0)}enableWaterMark(e){this.waterMarkEnabled=e}pipe(e,t){var r;if("video"!==e.kind)throw new R(1002,"track 不是一个 video track");if(this.inputTrack=e,this.abortRequest=!1,t)this.trackFps=t;else{const t=e.getConstraints();this.trackFps=null!==(r=t.frameRate)&&void 0!==r?r:15}if(this.captureStream=this.canvas.captureStream(this.trackFps),this.outputTrack=this.captureStream.getVideoTracks()[0],this.supportTrackProcessor)this.mediaStreamTrackProcessor=new MediaStreamTrackProcessor({track:this.inputTrack}),this.videoFrameReader=this.mediaStreamTrackProcessor.readable.getReader(),this.readVideoFrame();else{let e=new MediaStream;e.addTrack(this.inputTrack),this.video.srcObject=e,this.video.play().catch((e=>{pe.error("play video failed")})),this.renderTimer&&this.renderTimer.destroy(),this.renderTimer=new ro((()=>{this.renderHTMLVideoElement(this.video)}),0,Math.max(1e3/this.trackFps,30))}}getOutputTrack(){return this.outputTrack}stop(){this.renderTimer&&this.renderTimer.stop(),this.captureStream&&(this.captureStream=null),this.mediaStreamTrackProcessor&&(this.mediaStreamTrackProcessor=null),this.video&&(this.video.srcObject=null)}static isSupport(){const e=document.createElement("canvas"),t=e.getContext("webgl");return!!e.captureStream&&!!t}}ao.VIDEO_FORMAT=so,ao.Renders={BeautyRender:class extends js{constructor(e){super(e),this.program=new zs(this.gl),this.program.link(),this.opacity=.99,this.ruddy=.5,this.beauty=.5,this.brightness=.5}render(e,t,r=0){return this.program.bind(),e.bind(r),this.program.bindTexture(r),this.program.setSize(this.width,this.height),this.program.setParams(this.beauty,this.ruddy),this.program.setBrightness(this.brightness),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,t,4),{nextUnit:r+1,nextStartIndex:t+4}}setOpacity(e){this.opacity=e}setBrightness(e){this.brightness=e}setBeauty(e){this.beauty=e}setRuddy(e){this.ruddy=e}destroy(){this.program.stop()}}};var co=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))};Object(pe.setDefaultTag)("brtc"),pe.enableUploadLog(),pe.setUploadLevel("production"===l?pe.INFO:pe.DEBUG);const uo=Le({},pe,{setLevel:function(e){pe.setLevel(e),It.a.Logger.setLogLevel(e)}}),lo={Client:i,Stream:n};function ho(e){return new Gi(e)}function po(e){return new $s(e)}function mo(e){l=e,pe.info("set env "+e)}function fo(e){!function(e){m=e}(e)}function go(e){!function(e){v=e}(e),pe.info("set roomChannelType "+e)}function vo(e){!function(e){y=e}(e),pe.info("set forcePlanBSimulcast "+e)}function yo(e){!function(e){Zi=e}(e),pe.info("set customUrl "+e)}function _o(e){!function(e=[]){_=_.concat(e)}(e),pe.info("set proxies "+JSON.stringify(e))}function bo(e){f=e}function So(){_=[],pe.info("remove proxies")}function Io(){return co(this,void 0,void 0,(function*(){return yield It.a.checkSystemRequirements()}))}function Eo(){return sr()}function To(){return Mn()}const Ro=function(){return Us(this,void 0,void 0,(function*(){if("permissions"in navigator)try{let e=yield Promise.all([navigator.permissions.query({name:"camera"}),navigator.permissions.query({name:"microphone"})]);if(e.some((e=>"prompt"===e.state)))(yield navigator.mediaDevices.getUserMedia({video:!0,audio:!0})).getTracks().forEach((e=>e.stop()));else if(e.some((e=>"denied"===e.state)))throw new R(1010,"获取设备权限失败")}catch(e){throw new R(1010,"获取设备权限失败",e)}else try{(yield navigator.mediaDevices.getUserMedia({video:!0,audio:!0})).getTracks().forEach((e=>e.stop()))}catch(e){throw new R(1010,"获取设备权限失败",e)}}))},wo=jt,Ao=Rs,ko=Cs,Co=As;window.brtcLogPlugin=function(e,t,r){Ot[t]?Ot[t](r,"TencentLog"):uo.info(r,"TencentLog")},uo.setLevel(pe.WARN);const Mo=h,Oo=ao;console.log(`******************************************************************************\n* 欢迎使用 BRTC(v${h}) Web SDK - 百家云实时音视频通信\n* API 文档:https://docs.baijiayun.com/open/\n******************************************************************************`)}])}(BRTC);var ie=Object.create,T=Object.defineProperty,re=Object.getOwnPropertyDescriptor,se=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols,oe=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty,ne=Object.prototype.propertyIsEnumerable,J=(e,t,r)=>t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R=(e,t)=>{for(var r in t||(t={}))H.call(t,r)&&J(e,r,t[r]);if(G)for(var r of G(t))ne.call(t,r)&&J(e,r,t[r]);return e},ae=(e,t)=>{for(var r in t)T(e,r,{get:t[r],enumerable:!0})},Y=(e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of se(t))!H.call(e,n)&&n!==r&&T(e,n,{get:()=>t[n],enumerable:!(i=re(t,n))||i.enumerable});return e},k=(e,t,r)=>(r=null!=e?ie(oe(e)):{},Y(!t&&e&&e.__esModule?r:T(r,"default",{value:e,enumerable:!0}),e)),le=e=>Y(T({},"__esModule",{value:!0}),e),n=(e,t,r)=>new Promise(((i,n)=>{var s=e=>{try{a(r.next(e))}catch(e){n(e)}},o=e=>{try{a(r.throw(e))}catch(e){n(e)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(s,o);a((r=r.apply(e,t)).next())})),Re={};ae(Re,{AudioPlayer:()=>_,BCUser:()=>b,Player:()=>x,checkSystemSupport:()=>Ce,createStream:()=>Pe,default:()=>Te,enumAudioInputDevices:()=>ye,enumAudioOutputDevices:()=>Se,enumVideoDevices:()=>ve,getPermissions:()=>Ee});var dist$1=le(Re),ce={token:""},U=ce;function V({url:e,method:t="get",data:r={},contentType:i="application/json",_header:n={},succCB:s,errCB:o,dataType:a,responseType:c}){let u=U.token;t=t.toUpperCase(),n.Authorization="Bearer "+u,-1==e.indexOf("/proxies")&&(n.checkdelay="570ed35e48494f1d6aa7d1bd20d0a2be",n.ch="web",n.os="web",n.p="3",n.delay=(new Date).getTime(),n.version="2.2.7",n.ver="2.2.7",n.lan="zh",n.osv="",n.wh="",n.apn="");let d={headers:n,method:t};if(c&&(d.responseType=c),"GET"===t){if(r){e+="?";for(let t in r)e+=`${t}=${r[t]}&`;e=e.substring(0,e.length-1)}d.cache="no-store"}else if("RESTFUL"===t){e+="/";for(let t of r)e+=t+"/";e=e.substring(0,e.length-1),t="GET",d.method=t,d.cache="no-store"}else d.body="multipart/form-data"===i?r:JSON.stringify(r);return console.log("\n############# getData host==\n"+e+"\n Header=",n,"\n optins=",d),fetch(e,d).then((t=>"blob"===a?t:ue(t,e,r,c))).then((t=>(console.log(`此接口【${e}】返回的data:`,t),"blob"!==a?(t.msg=t.message||t.msg,t):"200"===t.code||200===t.status?("function"==typeof s&&s(t),t):("function"==typeof o&&o(t),void Promise.reject(t))))).catch((t=>(console.log("\n############## err"+t.message,e),t.msg=t.message||t.msg,Promise.reject(t))))}function ue(e,t,r,i){return e.ok?"blob"===i?e.blob():e.json():500===e.status?Promise.reject({code:500,message:"连接服务器失败, 请检查网络重试!",url:t,param:r}):404===e.status?Promise.reject({code:404,message:"404",url:t,param:r}):502===e.status?Promise.reject({code:502,message:"连接服务器失败, 请检查网络重试!",url:t,param:r}):Promise.reject({code:e.status,message:e.status+"",url:t,param:r})}var b=class e{constructor(e){this.userinfo=e.userinfo,this.permission=e.permission,this.stream=e.stream,this.userId=e.userId,this.customInfo=e.customInfo,this.nickname=e.nickname}static toUser(t,r){var i,n;return new e({userinfo:R({},t.getUserInfo()),userId:t.getID(),stream:t.getStreams(),permission:t.getPermission(),customInfo:R({},null==(n=null==(i=t.params)?void 0:i.info)?void 0:n.customInfo),nickname:t.getNickName()})}},w=require$$0__default.default,de=e=>e;function he(e){return e.participant&&(e.user=b.toUser(e.participant,this.type)),e}var me=[w.BloudEvents.PARTICIPANT_JOINED,w.BloudEvents.UPDATE_USER],B={};function W(){Object.values(w.BloudEvents).forEach((e=>{B[e]||(me.includes(e)?B[e]=he:B[e]=de)}))}var ge=function(){},v=void 0!==typeof console?console:null;function M(e,t,r,i){let n=[];return r&&n.push(r),i&&n.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function P(e,t,r,i=[]){i.unshift(M("DEBUG",e,t,r)),v.log.apply(v.log,i)}function m(e,t,r,i=[]){i.unshift(M("INFO",e,t,r)),v.log.apply(v.log,i)}function F(e,t,r,i=[]){i.unshift(M("WARN",e,t,r)),v.warn.apply(v.warn,i)}function c(e,t,r,i=[]){i.unshift(M("ERROR",e,t,r)),v.error.apply(v.error,i)}/BRTC/.test(ge.toString());var $=k(dist$2.exports),S=class{static singleModeJoin(e,t){return n(this,null,(function*(){try{let r,i;try{r=yield e._getBloudProxiesUrl(e.token)}catch(e){return c("_getBloudProxiesUrl error","","",[JSON.stringify(e)]),Promise.reject(e)}switch(e.identity){case"5":i="RWPSAVM";break;case"3":case"4":i="RWPS";break;case"6":i="RWPAV"}let n={room:e.roomId,user:e.userId.toString(),enableCollection:!1,enableRace:!0,proxies:r.proxies,nickname:e.userinfo.nickname,custom_token:e.customToken,userinfo:e.userinfo,token:e.token,secret:e.secret,forceWS:!0,name:e.name,create:e.tarCreate,disableMediaEngine:e.disableMediaEngine,permission:i};try{e.client&&e.client.destroy()}catch(e){}e.client=new $.Room(n),t(),yield e.client.connect(),m("singleModeJoin==>单一模式加入会议成功",e.userId,1)}catch(t){return c("singleModeJoin==>单一模式加入会议失败",e.userId,1,[JSON.stringify(t)]),e.client=null,Promise.reject(t)}}))}static singleModeLeave(e){return n(this,null,(function*(){if(!e.client)throw new Error("没有 joined");try{yield e.client.leave(),console.log("client leave success",e.userId),e.clearObject()}catch(t){throw console.log("client leave fail",e.userId,[t]),e.clearObject(),new Error(t)}}))}};Object.freeze({}),Object.freeze([]);var X="c",j=1,z=2,E=require$$0__default.default,K=require$$0__default.default,D=require$$0__default.default,p=k(BRTC.exports),Q=require$$0__default.default,a=require$$0__default.default,A=class{constructor(e){this.emitters=[],this.name="",this.type=j,this.appId="",this.brtcAppId="",this.roomId="",this.tarCreate=!1,this.userinfo={},this.userId="",this.isJoining=!1,this.collection="",this.limit=0,this.token="",this.customToken="",this.create=!1,this.host="",this.getProxiesUrl="",this.secret="",this.enableRace=!1,this.disableMediaEngine=!1,this.roomType=1,this.brtcClient=null,this.shareBrtcClient=null,this.hasBloudJoined=!1,this.brtcSig="",this.brtcShareSig="",this.shareContentHint="detail",this.identity="",this.isBig="0",this.joinBrtc=()=>new Promise(((e,t)=>{this.brtcClient.join(this.roomId,this.userId,this.sig).then((()=>(m("join brtc succeed"),e(!0)))).catch((e=>(console.log("brtc入会失败01",e),this.isJoining=!1,t((0,a.JoinBrtcError)(e.message)))))})),this.joinBloud=()=>new Promise(((e,t)=>{S.singleModeJoin(this,(()=>this.addBloudEvent())).then((()=>(m("join bloud succeed"),this.hasBloudJoined=!0,e(!0)))).catch((e=>(c("bloud入会失败02","",[e]),this.isJoining=!1,t(e))))})),this.handleForceUnpublishBloudStream=()=>{c("bloud share stream unpublish failed, create bloud stream and unpub again"),this.client.client.unpublishStream(this.roomId,this.userId,`${this.userId}_screen`)},this.emitter=new K.Emitter(!0),W(),window.BRTC=p}setShareSig(e){this.brtcShareSig=e}clearObject(){this.client&&(this.client.close(),this.client.removeAllListeners()),this.client=null,this.collection&&(this.collection.close(),this.collection=null)}join(e){return n(this,null,(function*(){return new Promise(((t,r)=>n(this,null,(function*(){if(this.isJoining)return Promise.reject(a.RepeatJoinError);if(this.client)return Promise.reject(a.RepeatJoinError);if("string"!=typeof e.getProxiesUrl)return Promise.reject(a.ProxiesUrlTypeError);if(!e.userinfo||e.userinfo&&"object"!=typeof e.userinfo)return Promise.reject(a.JoinUserInfoError);if("number"!=typeof e.type||1!==e.type&&2!==e.type)return Promise.reject(a.JoinTypeError);if(this.userId=e.userId,this.roomId=e.room,this.roomType=e.roomType,this.collection=e.collection,this.userinfo=e.userinfo,this.getProxiesUrl=e.getProxiesUrl,this.appId=e.appId,this.brtcAppId=e.brtcAppId,this.type=e.type,this.tarCreate=e.create,this.limit=e.limit,this.secret=e.secret,this.enableRace=e.enableRace,this.token=e.token,this.customToken=e.customToken,this.name=e.name,this.brtcSig=e.sig,this.identity=e.identity,this.isBig=e.is_big,this.sig=e.sig,U.token=e.token,this.isJoining=!0,this.type===j&&(yield S.singleModeJoin(this,(()=>this.addBloudEvent()))),this.type===z){this.disableMediaEngine=!0;try{this.brtcClient=p.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,audioLevelInterval:200,roomType:"big",silence:!0}),this.createShareBrtcClient(),this.addBrtcEvent(),this.fire("brtc-bound",!0),p.setVTRequestTimeout(5),yield this.joinRoom().then((()=>(this.isJoining=!1,this.fire(E.CustomEvents.JOIN_READY),t(!0)))).catch((e=>(c("join room error","",this.userId,[JSON.stringify(e)]),r(e))))}catch(e){return this.isJoining=!1,c("join room error",X,this.userId,[e]),r(e)}}}))))}))}joinRoom(){return new Promise(((e,t)=>{let r=!1,i=!1;this.joinBloud().then((()=>{if(r=!0,i)return e(!0)})).catch((e=>t(e))),this.joinBrtc().then((()=>{if(i=!0,r)return e(!0)})).catch((e=>t(e)))}))}createShareBrtcClient(){return this.shareBrtcClient||(this.shareBrtcClient=p.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,roomType:"big",silence:!0}),this.shareBrtcClient.on("error",(e=>{this.fire("share-brtc-error",e)}))),this.shareBrtcClient}_getBloudProxiesUrl(e){return new Promise(((t,r)=>{V({url:`${this.getProxiesUrl}/proxies?token=${e}`}).then((r=>{t({proxies:r.proxies,token:e})})).catch((e=>{r((0,a.getBloudProxiesUrlError)(e))}))}))}on(e,t){return this.emitter.on(e,{fn:t,ctx:this}),this}fire(e,t){this.emitter&&this.emitter.fire(e,t?[t]:void 0)}changeMaster(e,t=!1){return this.client.changeMaster(e,t)}getMaster(){return this.client.getMaster()}syncUser(e){return this.client.syncUser(e)}getCreator(){return this.client.getCreator()}getName(){return this.client.getName()}close(){return n(this,null,(function*(){var e;this.leaveBrtcRoom(),null==(e=this.client)||e.close(),this.leaveShare()}))}getMsgSeq(){return this.client.getMsgSeq()}evictUser(e,t){return this.client.evictUser2(this.getMaster(),e,t)}updateUser(e,t){return n(this,null,(function*(){yield this.client.updateUser(e,t)}))}getLimits(){return this.client.getLimits()}getSwitch(){return this.client.getSwitch()}syncRoom(){return this.client.syncRoom()}update(e){return this.client.update(e)}getUsers(e,t,r){return n(this,null,(function*(){let{participants:i,total:n}=yield this.client.getUsers(e,t,r),s=new Map;return i.forEach((e=>{let t=b.toUser(e,this.type);s.set(t.userId,t)})),{users:s,total:n}}))}updateStream(e,t,r){return this.client.updateStream(e,t,r)}getUsersList(e,t,r,i){return n(this,null,(function*(){let{participants:n,total:s,pageIndex:o}=yield this.client.getUsersList(e,r,t,i),a=new Map;return n.forEach((e=>{let t=b.toUser(e,this.type);a.set(t.userId,t)})),{users:a,total:s,pageIndex:o}}))}getTotalUsers(){return this.client.getTotalUsers()}sendMessage(e,t){return this.client.sendMessage(e,t)}customMessage(e,t){return this.client.customMessage(e,t)}getMessages(e,t){return this.client.getMessages(e,t)}getLocalParticipant(){var e;return null==(e=this.client)?void 0:e.getLocalParticipant()}getAudioOff(){return this.client.getAudioOff()}getSelfOpenAudio(){return this.client.getSelfOpenAudio()}getVideoOff(){return this.client.getVideoOff()}getMsgOff(){return this.client.getMsgOff()}getLock(){return this.client.getLock()}getRoomInfo(){let e=R({},this.client.options);return delete e.token,e}setAudioOff(e,t){return this.client.setAudioOff(e,t)}setVideoOff(e){return this.client.setVideoOff(e)}setMsgOff(e){return this.client.setMsgOff(e)}setSwitch(e){return this.client.setSwitch(e)}setLock(e){return this.client.setLock(e)}publish(e){return n(this,null,(function*(){return this.brtcClient.publish(e).catch((e=>Promise.reject((0,a.BrtcPublishError)(JSON.stringify(e)))))}))}unpublish(e){return n(this,null,(function*(){return this.brtcClient.unpublish(e).catch((e=>Promise.reject((0,a.BrtcUnPublishError)(JSON.stringify(e)))))}))}subscribe(e){return n(this,arguments,(function*(e,t={audio:!0,video:!0}){return this.brtcClient.subscribe(e,t).catch((e=>Promise.reject(e)))}))}unsubscribe(e){return n(this,null,(function*(){return this.brtcClient.unsubscribe(e).catch((e=>Promise.reject((0,a.BrtcUnsubscribeError)(JSON.stringify(e)))))}))}addBloudEvent(){let e=this,t=B;let r=Object.values(E.BloudEvents);D.array.each(r,(r=>{!function(r,i){e.client.on(r,(function(){let r=(0,Q.execute)(t[i],e,D.array.toArray(arguments));e.fire(i,r)}))}(r,r)}))}addBrtcEvent(){let e=this;let t=Object.values(E.BrtcEvents);D.array.each(t,(t=>{var r;r=t,e.brtcClient.on(r,(t=>{e.fire(r,t)}))}))}clearBrtcEvent(){var e;null==(e=this.brtcClient)||e.off()}leave(){return n(this,null,(function*(){return console.log("离开会议","userId =>",this.userId,"roomId =>",this.roomId,"userInfo =>",this.userinfo),yield S.singleModeLeave(this),this.leaveBrtcRoom()}))}leaveBrtcRoom(){return n(this,null,(function*(){if(console.log("离开brtc调用堆栈!!!!!"),this.brtcClient&&(this.brtcClient.off(),yield this.brtcClient.leave(),yield this.brtcClient.destroy(!0),this.brtcClient=null),this.shareBrtcClient){try{this.shareBrtcClient.off(),yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(!0),this.shareBrtcClient=null}}))}leaveShare(){return n(this,null,(function*(){if(this.shareBrtcClient){try{yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(!0),this.shareBrtcClient=null}}))}createRecorder(e){return this.client.Recorder(e)}createSpeakerDetector(){return this.client.SpeakerDetector()}createLocalStream(e,t){return n(this,null,(function*(){p.isSmallStreamSupported()?yield this.brtcClient.enableSmallStream():c("simulcast is not supported"),this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return p.createStream(e)}catch(e){return Promise.reject(e)}}))}createPBLocalStream(e,t){return n(this,null,(function*(){this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return p.createStream(e)}catch(e){return Promise.reject((0,a.BrtcCreateStreamError)(JSON.stringify(e)))}}))}creteBloudLocalStream(e,t){return this.client.Stream({audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t,screen:!1})}createBloudScreenStream(e,t){return this.client.Stream({screen:!0,audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t})}updateCustomStats(e,t=!1){return m("updateCustomStats","updateCustomStats","",[" customstats => ",JSON.stringify(e),"replace => ",t]),this.client.updateCustomStats({customStats:e},t)}getCustomStats(){var e;return null==(e=this.client)?void 0:e.getCustomStats()}getDuration(){var e;return null==(e=this.client)?void 0:e.duration}toggleShareScreen(e,t,r){return n(this,null,(function*(){return new Promise(((i,s)=>n(this,null,(function*(){if(e){let e=t.audioHint;try{let t={screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail",sourceType:"screen"};e&&(t.audioHint=e),r&&(t.videoSource=r.videoSource,t.audioSource=r.audioSource);let n=yield p.createStream(t),s="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};n.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:s.frameRate,bitrate:s.bitrate});try{yield n.init()}catch(e){throw c("brtc share stream init failed","","",[String(e)]),new Error(e)}yield this.publishShareStream(n),i(!0)}catch(e){String(e).includes("Permission denied by system")?(c("没有打开共享屏幕录制权限","","this.userId"),s(a.ShareScreenNoPermission)):String(e).includes("Permission denied")?(m("点击了取消共享屏幕","",this.userId,["nickname =>",this.name]),s(a.ShareScreenCanceled)):(c("开启共享屏幕失败","","",[String(e)]),s((0,a.ShareScreenOtherError)("开启共享屏幕失败,请重试")))}}else yield this.unpublishShareStream(),i(!0)}))))}))}shareHTMLMedia(e,t){return n(this,null,(function*(){if(e&&t)try{let e=p.createStream({screen:!0,audio:t.audio,video:t.video,videoSource:t.videoSource,audioSource:t.audioSource,videoHint:"motion",sourceType:"screen"}),r="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:r.frameRate,bitrate:r.bitrate}),yield e.init(),yield this.publishShareStream(e)}catch(e){return Promise.reject((0,a.ToggleShareScreenError)(JSON.stringify(e)))}e||(yield this.unpublishShareStream())}))}publishShareStream(e){return n(this,null,(function*(){if(this.shareBrtcClient||this.createShareBrtcClient(),!this.brtcShareSig)return console.error("brtcShareSig为空"),Promise.reject(a.BrtcShareSigError);{yield this.shareBrtcClient.join(this.roomId,`${this.userId}_screen`,this.brtcShareSig).catch((e=>(c("共享屏幕入会失败","","",[JSON.stringify(e),this.brtcShareSig]),Promise.reject(a.ShareScreenClientJoinedError)))),e.on("video-track-ended",(()=>{this.handleShareStreamEnded()})),yield this.shareBrtcClient.publish(e).catch((t=>(c("共享屏幕流推流失败","","",["err =>",JSON.stringify(t)]),e.destroy(),Promise.reject((0,a.ShareScreenOtherError)("共享屏幕流推流失败,请重试"))))),this.shareBrtcClient.on("sync-room-completed",(()=>{this.fire(E.CustomEvents.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));let t=e.getAudioOn(),r=e.getVideoOn();this.shareScreenStream=e,this.createAndPubBloudShareStream(t,r),setTimeout((()=>{Promise.resolve(!0)}),200)}}))}createAndPubBloudShareStream(e,t,r=!0){this.bloudShareScreenStream=this.createBloudScreenStream({audio_enable:e,video_enable:t},`${this.userId}_screen`),r&&this.bloudShareScreenStream.publish({video_enable:t,audio_enable:e})}replaceShareStreamVideoTrack(e){this.shareScreenStream?this.shareScreenStream.replaceTrack(e):c("当前没有开启共享屏幕,无法替换track")}unpublishShareStream(){return n(this,null,(function*(){return new Promise((e=>n(this,null,(function*(){var t,r,i;try{F("unpublish share stream"),this.shareScreenStream&&(yield null==(t=this.shareBrtcClient)?void 0:t.unpublish(this.shareScreenStream).catch((e=>{c("取消共享屏幕出错","","",[JSON.stringify(e)])}))),yield null==(r=this.shareBrtcClient)?void 0:r.leave().catch((e=>{c("shareBrtcClient leave error","","",[JSON.stringify(e)])})),null==(i=this.shareScreenStream)||i.destroy(),this.shareScreenStream=void 0,this.bloudShareScreenStream?yield this.bloudShareScreenStream.unpublish().then((()=>{this.bloudShareScreenStream=void 0})).catch((e=>{c("bloud share stream unpublish failed"),this.handleForceUnpublishBloudStream()})):this.handleForceUnpublishBloudStream()}catch(e){console.log("取消共享兼容处理",e)}e(!0)}))))}))}setShareScreenContentHint(e){this.shareContentHint=e}releaseRoom(){return n(this,null,(function*(){yield this.client.release()}))}handleShareStreamEnded(){setTimeout((()=>{var e;(!this.shareScreenStream||"live"!==(null==(e=this.shareScreenStream.getVideoTrack())?void 0:e.readyState))&&(c("share stream video track ended"),this.fire("toggle-screen-share",!1))}),2e3)}setCustomUrl(e){p.setCustomUrl(e)}bloudReconnect(){return n(this,null,(function*(){yield this.client.leave(),yield S.singleModeJoin(this,(()=>this.addBloudEvent()))}))}searchUsers(e,t,r){return n(this,null,(function*(){let{participants:i}=yield this.client.searchUsers(e,t,r),n=new Map;return i.forEach((e=>{let t=b.toUser(e,this.type);n.set(t.userId,t)})),{users:n}}))}queryUsers(e){return n(this,null,(function*(){let{participants:t}=yield this.client.queryUsers(e),r=new Map;return t.forEach((e=>{let t=b.toUser(e,this.type);r.set(t.userId,t)})),{users:r}}))}handleBloudRejoin(){return n(this,null,(function*(){return S.singleModeJoin(this,(()=>this.addBloudEvent()))}))}},f=k(BRTC.exports),Z=require$$0__default.default,O=require$$0__default.default,I="bp",x=class extends Z.Emitter{constructor(e,t){super(),this.playEvent=()=>{this.videoStatus="PLAYING",m("stream big video playing",I,this.stream.getUserId())},this.pauseEvent=()=>{this.videoStatus="PAUSED",this.fire(O.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"video",state:this.videoStatus,reason:"pause"}]),m("stream big video pause",I,this.stream.getUserId())},this.stalledEvent=()=>{this.videoStatus="PAUSED",this.fire(O.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"video",state:this.videoStatus,reason:"stalled"}]),m("stream big video stalled",I,this.stream.getUserId())},this.element=e,this.options=t,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.backgroundColor="#202020",this.container.style.overflow="hidden",e.appendChild(this.container)}playVideo(){if(!this.video){if(!this.stream.getVideoTrack())return;this.video=document.createElement("video"),this.video.autoplay=!0,this.video.playsInline=!0,this.video.muted=!!this.options.muted,this.video.style.width="100%",this.video.style.height="100%",this.video.style.position="absolute";let e="";this.options.rotateX&&(e=`rotateX(${this.options.rotateX}deg)`),this.options.rotateY&&(e=`${e} rotateY(${this.options.rotateY}deg)`),e&&(this.video.style.transform=e),this.options.fit&&(this.video.style.objectFit=this.options.fit),this.video.id=`video_${this.stream.getStreamId()}_big`,this.container.appendChild(this.video),this.video.addEventListener("playing",this.playEvent),this.video.addEventListener("pause",this.pauseEvent),this.video.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e,this.videoStatus="STOPPED"}play(e){return n(this,null,(function*(){this.stream=e,this.container.id=`player_${e.getStreamId()}_big_container`,this.stream.hasVideo()&&this.playVideo();try{this.video&&(yield this.video.play())}catch(e){c("big player play video failed","","",[JSON.stringify(e)]),this.fire(O.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return n(this,null,(function*(){this.stream=e;try{this.stream.hasVideo()&&t&&this.playVideo(),this.stream.hasVideo()&&t&&(yield this.video.play())}catch(e){c("big player replay video failed","","",[JSON.stringify(e)]),this.fire(O.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}muteVideo(){this.video&&(this.video.srcObject=void 0,this.videoStatus="STOPPED")}unmuteVideo(){if(this.video&&this.stream&&"STOPPED"===this.videoStatus){let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e}}destroy(){this.video&&(this.video.removeEventListener("playing",this.playEvent),this.video.removeEventListener("pause",this.pauseEvent),this.video.removeEventListener("stalled",this.stalledEvent),this.video.style.display="none",this.video=null);try{this.container.style.display="none",this.element.removeChild(this.container)}catch(e){}this.container=null,P("stream player destroy",I,this.stream.getUserId())}resume(){return n(this,null,(function*(){this.video&&(yield this.video.play()),P("stream player resume",I,this.stream.getUserId())}))}getVideoFrame(){if(this.video&&"STOPPED"!==this.videoStatus){let e=document.createElement("canvas");return e.width=this.video.videoWidth,e.height=this.video.videoHeight,e.getContext("2d").drawImage(this.video,0,0),e.toDataURL("image/png")}}},ee=require$$0__default.default,te=require$$0__default.default,L=require$$0__default.default,C="ap",_=class extends te.Emitter{constructor(e,t){super(),this.sinkId="",this.audioLevel=1,this.playEvent=()=>{this.audioStatus="PLAYING",m("stream audio playing",C,this.stream.getUserId())},this.pauseEvent=()=>{this.audioStatus="PAUSED",this.fire(L.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"pause"}]),m("stream audio pause",C,this.stream.getUserId())},this.stalledEvent=()=>{this.audioStatus="PAUSED",this.fire(L.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"stalled"}]),m("stream audio stalled",C,this.stream.getUserId())},this.element=e,this.options=t}get streamId(){return this.stream.getStreamId()}playAudio(){if(!this.audio){if(!this.stream.getAudioTrack())return;this.audio=document.createElement("audio"),this.audio.autoplay=!0,this.audio.playsInline=!0,this.audio.muted=this.options.muted,this.audio.id=`audio_${this.stream.getStreamId()}_back`,this.element.appendChild(this.audio),this.sinkId&&this.setSinkId(this.sinkId),this.audio.volume=this.audioLevel,this.audio.addEventListener("playing",this.playEvent),this.audio.addEventListener("pause",this.pauseEvent),this.audio.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e,this.audioStatus="STOPPED"}setSinkId(e){return n(this,null,(function*(){this.sinkId=e,this.audio&&ee.is.func(this.audio.setSinkId)&&(yield this.audio.setSinkId(e))}))}setVolume(e){this.audio&&(this.audioLevel=e,this.audio.volume=e)}play(e){return n(this,null,(function*(){this.stream=e,this.stream.hasAudio()&&this.playAudio();try{this.audio&&(yield this.audio.play())}catch(e){c("player play audio failed","","",[JSON.stringify(e)]),this.fire(L.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return n(this,null,(function*(){this.stream=e;try{this.stream.hasAudio()&&r&&this.playAudio(),this.stream.hasAudio()&&r&&(yield this.audio.play())}catch(e){c("player replay audio failed","","",[JSON.stringify(e)]),this.fire(L.PlayerEvents.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}P("audio stream replay",C,this.stream.getUserId())}))}muteAudio(){this.audio&&(this.audio.srcObject=void 0,this.audioStatus="STOPPED")}unmuteAudio(){if(this.audio&&this.stream&&"STOPPED"===this.audioStatus){let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e}}destroy(){var e,t,r;null==(e=this.audio)||e.removeEventListener("playing",this.playEvent),null==(t=this.audio)||t.removeEventListener("pause",this.pauseEvent),null==(r=this.audio)||r.removeEventListener("stalled",this.stalledEvent);try{this.element.removeChild(this.audio)}catch(e){}this.audio=null,P("stream player destroy",C,this.stream.getUserId())}resume(){return n(this,null,(function*(){this.audio?(yield this.audio.play(),m("stream player resume",C,this.stream.getUserId())):c("try resume audio play, but, audio not exits",C,this.stream.getUserId())}))}},ye=f.enumAudioInputDevices,Se=f.enumAudioOutputDevices,ve=f.enumVideoDevices,Ee=f.getPermissions,Ce=f.checkSystemSupport,Pe=f.createStream,Te=A;class BoomError extends Error{constructor(e,t,r,i){super(),this.code=e,this.error=r,this.BoomErrorFlag=!0,this.eName=i,this.message=t}static instanceOf(e){return!(!e||!e.BoomErrorFlag)}getCode(){return this.code}}const LOCAL_ERROR=1e3,INVALID_PARAMETER=1001,INVALID_OPERATION=1002,CLIENT_BANNED=4005,USER_NOT_EXIT=9001,DEBUG=1,WARN=3,EMPTY_FUNCTION=function(){};function formatLog(e,t,r,i){let n=[];return r&&n.push(r),i&&n.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function info(e,t,r,i=[]){i.unshift(formatLog("INFO",e,t,r)),console.log(...i)}function warn(e,t,r,i=[]){i.unshift(formatLog("WARN",e,t,r)),console.log(...i)}function error$1(e,t,r,i=[]){i.unshift(formatLog("ERROR",e,t,r)),console.log(...i)}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}/BRTC/.test(EMPTY_FUNCTION.toString());var UnsubscriptionError=createErrorClass((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function arrRemove(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,r,i,n;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=__values(s),a=o.next();!a.done;a=o.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(isFunction(c))try{c()}catch(e){n=e instanceof UnsubscriptionError?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var d=__values(u),l=d.next();!l.done;l=d.next()){var h=l.value;try{execFinalizer(h)}catch(e){n=null!=n?n:[],e instanceof UnsubscriptionError?n=__spreadArray(__spreadArray([],__read(n)),__read(e.errors)):n.push(e)}}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}}if(n)throw new UnsubscriptionError(n)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&arrRemove(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}(),EMPTY_SUBSCRIPTION=Subscription.EMPTY;function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}var config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},timeoutProvider={setTimeout:function(e,t){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var n=timeoutProvider.delegate;return(null==n?void 0:n.setTimeout)?n.setTimeout.apply(n,__spreadArray([e,t],__read(r))):setTimeout.apply(void 0,__spreadArray([e,t],__read(r)))},clearTimeout:function(e){var t=timeoutProvider.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function reportUnhandledError(e){timeoutProvider.setTimeout((function(){throw e}))}function noop(){}var context=null;function errorContext(e){if(config.useDeprecatedSynchronousErrorHandling){var t=!context;if(t&&(context={errorThrown:!1,error:null}),e(),t){var r=context,i=r.errorThrown,n=r.error;if(context=null,i)throw n}}else e()}var Subscriber=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,isSubscription(t)&&t.add(r)):r.destination=EMPTY_OBSERVER,r}return __extends(t,e),t.create=function(e,t,r){return new SafeSubscriber(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Subscription),_bind=Function.prototype.bind;function bind(e,t){return _bind.call(e,t)}var ConsumerObserver=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){handleUnhandledError(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){handleUnhandledError(e)}else handleUnhandledError(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){handleUnhandledError(e)}},e}(),SafeSubscriber=function(e){function t(t,r,i){var n,s,o=e.call(this)||this;isFunction(t)||!t?n={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=i?i:void 0}:o&&config.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},n={next:t.next&&bind(t.next,s),error:t.error&&bind(t.error,s),complete:t.complete&&bind(t.complete,s)}):n=t;return o.destination=new ConsumerObserver(n),o}return __extends(t,e),t}(Subscriber);function handleUnhandledError(e){reportUnhandledError(e)}function defaultErrorHandler(e){throw e}var EMPTY_OBSERVER={closed:!0,next:noop,error:defaultErrorHandler,complete:noop},observable="function"==typeof Symbol&&Symbol.observable||"@@observable";function identity(e){return e}function pipeFromArray(e){return 0===e.length?identity:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Observable=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var i=this,n=isSubscriber(e)?e:new SafeSubscriber(e,t,r);return errorContext((function(){var e=i,t=e.operator,r=e.source;n.add(t?t.call(n,r):r?i._subscribe(n):i._trySubscribe(n))})),n},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=getPromiseCtor(t))((function(t,i){var n=new SafeSubscriber({next:function(t){try{e(t)}catch(e){i(e),n.unsubscribe()}},error:i,complete:t});r.subscribe(n)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=getPromiseCtor(e))((function(e,r){var i;t.subscribe((function(e){return i=e}),(function(e){return r(e)}),(function(){return e(i)}))}))},e.create=function(t){return new e(t)},e}();function getPromiseCtor(e){var t;return null!==(t=null!=e?e:config.Promise)&&void 0!==t?t:Promise}function isObserver(e){return e&&isFunction(e.next)&&isFunction(e.error)&&isFunction(e.complete)}function isSubscriber(e){return e&&e instanceof Subscriber||isObserver(e)&&isSubscription(e)}var ObjectUnsubscribedError=createErrorClass((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),Subject=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return __extends(t,e),t.prototype.lift=function(e){var t=new AnonymousSubject(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new ObjectUnsubscribedError},t.prototype.next=function(e){var t=this;errorContext((function(){var r,i;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var n=__values(t.currentObservers),s=n.next();!s.done;s=n.next()){s.value.next(e)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}}}))},t.prototype.error=function(e){var t=this;errorContext((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}}))},t.prototype.complete=function(){var e=this;errorContext((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,i=r.hasError,n=r.isStopped,s=r.observers;return i||n?EMPTY_SUBSCRIPTION:(this.currentObservers=null,s.push(e),new Subscription((function(){t.currentObservers=null,arrRemove(s,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,i=t.thrownError,n=t.isStopped;r?e.error(i):n&&e.complete()},t.prototype.asObservable=function(){var e=new Observable;return e.source=this,e},t.create=function(e,t){return new AnonymousSubject(e,t)},t}(Observable),AnonymousSubject=function(e){function t(t,r){var i=e.call(this)||this;return i.destination=t,i.source=r,i}return __extends(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:EMPTY_SUBSCRIPTION},t}(Subject),BehaviorSubject=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return __extends(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,i=e._value;if(t)throw r;return this._throwIfClosed(),i},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Subject);Object.freeze({}),Object.freeze([]);const LOGGER_TAG_CLIENT="c";var MODEL_SORT_ENUM_STAND,MODEL_SORT_ENUM_ZY,STREAM_TYPE;!function(e){e[e.SCREEN_MASTER=0]="SCREEN_MASTER",e[e.SCREEN_MANAGER_AUDIO_VIDEO=1]="SCREEN_MANAGER_AUDIO_VIDEO",e[e.SCREEN_MANAGER_AUDIO=2]="SCREEN_MANAGER_AUDIO",e[e.SCREEN_MANAGER_VIDEO=3]="SCREEN_MANAGER_VIDEO",e[e.SCREEN_MANAGER=4]="SCREEN_MANAGER",e[e.SCREEN_GUEST_AUDIO_VIDEO=5]="SCREEN_GUEST_AUDIO_VIDEO",e[e.SCREEN_GUEST_AUDIO=6]="SCREEN_GUEST_AUDIO",e[e.SCREEN_GUEST_VIDEO=7]="SCREEN_GUEST_VIDEO",e[e.SCREEN_GUEST=8]="SCREEN_GUEST",e[e.SCREEN_COMMONUSER_AUDIO_VIDEO=9]="SCREEN_COMMONUSER_AUDIO_VIDEO",e[e.SCREEN_COMMONUSER_AUDIO=10]="SCREEN_COMMONUSER_AUDIO",e[e.SCREEN_COMMONUSER_VIDEO=11]="SCREEN_COMMONUSER_VIDEO",e[e.SCREEN_OTHER=12]="SCREEN_OTHER",e[e.MASTER=13]="MASTER",e[e.LOCAL=14]="LOCAL",e[e.MANAGER_AUDIO_VIDEO=15]="MANAGER_AUDIO_VIDEO",e[e.MANAGER_AUDIO=16]="MANAGER_AUDIO",e[e.MANAGER_VIDEO=17]="MANAGER_VIDEO",e[e.MANAGER=18]="MANAGER",e[e.RAISE_HAND=19]="RAISE_HAND",e[e.RAISE_AUDIO=20]="RAISE_AUDIO",e[e.RAISE_VIDEO=21]="RAISE_VIDEO",e[e.GUEST_AUDIO_VIDEO=22]="GUEST_AUDIO_VIDEO",e[e.GUEST_AUDIO=23]="GUEST_AUDIO",e[e.GUEST_VIDEO=24]="GUEST_VIDEO",e[e.GUEST=25]="GUEST",e[e.SIGNAL=26]="SIGNAL",e[e.COMMONUSER_AUDIO_VIDEO=27]="COMMONUSER_AUDIO_VIDEO",e[e.COMMONUSER_AUDIO=28]="COMMONUSER_AUDIO",e[e.COMMONUSER_VIDEO=29]="COMMONUSER_VIDEO",e[e.OTHER=30]="OTHER"}(MODEL_SORT_ENUM_STAND||(MODEL_SORT_ENUM_STAND={})),function(e){e[e.SCREEN=0]="SCREEN",e[e.RAISE_AUDIO=1]="RAISE_AUDIO",e[e.RAISE_VIDEO=2]="RAISE_VIDEO",e[e.LOCAL=3]="LOCAL",e[e.MASTER_AUDIO_VIDEO=4]="MASTER_AUDIO_VIDEO",e[e.MANAGER_AUDIO_VIDEO=5]="MANAGER_AUDIO_VIDEO",e[e.AUDIO_VIDEO=6]="AUDIO_VIDEO",e[e.MASTER_AUDIO=7]="MASTER_AUDIO",e[e.MANAGER_AUDIO=8]="MANAGER_AUDIO",e[e.AUDIO=9]="AUDIO",e[e.MASTER_VIDEO=10]="MASTER_VIDEO",e[e.MANAGER_VIDEO=11]="MANAGER_VIDEO",e[e.VIDEO=12]="VIDEO",e[e.MASTER=13]="MASTER",e[e.MANAGER=14]="MANAGER",e[e.GUEST=15]="GUEST",e[e.COMMON_USER=16]="COMMON_USER",e[e.SIGNAL=17]="SIGNAL",e[e.OTHER=18]="OTHER"}(MODEL_SORT_ENUM_ZY||(MODEL_SORT_ENUM_ZY={})),function(e){e[e.SUB_MAIN=0]="SUB_MAIN",e[e.SINGLE=1]="SINGLE",e[e.SHARE=2]="SHARE",e[e.OTHER=3]="OTHER"}(STREAM_TYPE||(STREAM_TYPE={}));const STREAM_SUFFIX_SCREEN="_screen",MOBILE_STREAM_SUFFIX_SCREEN="screen-",SIGNAL_SUFFIX="xinhao_",RECEIVE_SUBSCRIBE_MESSAGE="sub-message",USER_SORT_NUM_CHANGE="user-sort-num-change",BIND_ELEMENT="bind-element",HANDLE_STREAM_CONNECT_ERROR="stream-connect-error",RAISE_HAND="raise-hand",MANUAL_SUBSCRIPTION="manual-subscription",UNSUBSCRIBE_STREAM="unsubscribe-stream",CHANG_IS_GUEST="change-is-guest",BIND_BIG_ELEMENT="bind-big-element",NO_CONTAINER="no-container",MODEL_SORT_NUM_CHANGE="model-sort-num-change",ADD_PULL_USER="add-pull-user",SET_VOLUME="set-volume",ADD_AUDIO_PLAY="add-audio-play";function mitt(e){return{all:e=e||new Map,on:function(t,r){var i=e.get(t);i?i.push(r):e.set(t,[r])},off:function(t,r){var i=e.get(t);i&&(r?i.splice(i.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var i=e.get(t);i&&i.slice().map((function(e){e(r)})),(i=e.get("*"))&&i.slice().map((function(e){e(t,r)}))}}}class BoomEmitter{static getInstance(){return BoomEmitter.emitter||(BoomEmitter.emitter=mitt()),BoomEmitter.emitter}}function getSortNum(e){return 2===_selfSortType?sortZY(e):sortStand(e)}function sortStand(e){let t=MODEL_SORT_ENUM_STAND.OTHER;return e.isSharing?(t=e.isMaster?MODEL_SORT_ENUM_STAND.SCREEN_MASTER:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO_VIDEO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_VIDEO:e.isManager?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER:e.isCommonUser?e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_OTHER:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_GUEST,t):(e.isMaster?t=MODEL_SORT_ENUM_STAND.MASTER:e.isLocal?t=MODEL_SORT_ENUM_STAND.LOCAL:e.isManager?t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_VIDEO:MODEL_SORT_ENUM_STAND.MANAGER:e.raiseHand?t=MODEL_SORT_ENUM_STAND.RAISE_HAND:e.isCommonUser?e.isSignal?t=MODEL_SORT_ENUM_STAND.SIGNAL:e.isCommonUser&&(t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.OTHER):t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_VIDEO:MODEL_SORT_ENUM_STAND.GUEST,t)}function sortZY(e){let t;return t=e.isToupingma?MODEL_SORT_ENUM_ZY.SCREEN:e.raiseHand?MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?MODEL_SORT_ENUM_ZY.RAISE_AUDIO:e.raiseVideoHands?MODEL_SORT_ENUM_ZY.RAISE_VIDEO:e.isLocal?MODEL_SORT_ENUM_ZY.LOCAL:e.isMaster&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO_VIDEO:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO_VIDEO:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.AUDIO_VIDEO:e.isMaster&&e.audioEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO:e.audioEnable?MODEL_SORT_ENUM_ZY.AUDIO:e.isMaster&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_VIDEO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_VIDEO:e.videoEnable?MODEL_SORT_ENUM_ZY.VIDEO:e.isMaster?MODEL_SORT_ENUM_ZY.MASTER:e.isManager?MODEL_SORT_ENUM_ZY.MANAGER:e.isCommonUser?MODEL_SORT_ENUM_ZY.COMMON_USER:e.isSignal?MODEL_SORT_ENUM_ZY.SIGNAL:MODEL_SORT_ENUM_ZY.GUEST,t}BoomEmitter.emitter=void 0,BoomEmitter.removeEmitter=()=>{var e,t,r,i,n,s,o,a,c,u,d,l,h,p;null===(e=BoomEmitter.emitter)||void 0===e||e.off(RECEIVE_SUBSCRIBE_MESSAGE),null===(t=BoomEmitter.emitter)||void 0===t||t.off(USER_SORT_NUM_CHANGE),null===(r=BoomEmitter.emitter)||void 0===r||r.off(HANDLE_STREAM_CONNECT_ERROR),null===(i=BoomEmitter.emitter)||void 0===i||i.off(RAISE_HAND),null===(n=BoomEmitter.emitter)||void 0===n||n.off(UNSUBSCRIBE_STREAM),null===(s=BoomEmitter.emitter)||void 0===s||s.off(MANUAL_SUBSCRIPTION),null===(o=BoomEmitter.emitter)||void 0===o||o.off(CHANG_IS_GUEST),null===(a=BoomEmitter.emitter)||void 0===a||a.off(BIND_ELEMENT),null===(c=BoomEmitter.emitter)||void 0===c||c.off(BIND_BIG_ELEMENT),null===(u=BoomEmitter.emitter)||void 0===u||u.off(NO_CONTAINER),null===(d=BoomEmitter.emitter)||void 0===d||d.off(MODEL_SORT_NUM_CHANGE),null===(l=BoomEmitter.emitter)||void 0===l||l.off(ADD_PULL_USER),null===(h=BoomEmitter.emitter)||void 0===h||h.off(SET_VOLUME),null===(p=BoomEmitter.emitter)||void 0===p||p.off(ADD_AUDIO_PLAY),BoomEmitter.emitter=void 0};class BMUser{constructor(e,t=!1){var r;this.streamModels=new Map,this.sortNum=100,this.raiseVideoHands=!1,this.raiseAudioHands=!1,this.raiseHand=!1,this.isAudience=!1,this.isCommonUser=!1,this.inBackground=!1,this.raiseHandTime=0,this.userId=e.userId,this.userInfo=e.userInfo,this.nickName=e.nickname,this.isMaster=!!e.isMaster,this.isManager=!!e.isManager,this.isToupingma=!!e.isToupingma,this.isLocal=t,this.hasMultiple=!!e.hasMultiple,this.isCreate=!!e.isCreate,this.hasShare=!!e.hasShare,this.avatar=null===(r=e.userInfo)||void 0===r?void 0:r.avatar,this.permission=e.permission,this.raiseAudioHands=!!e.raiseAudioHands,this.raiseVideoHands=!!e.raiseVideoHands,this.raiseHand=!!e.raiseHand,this.isAudience=!!e.isAudience,this.isCommonUser=!!e.isCommonUser,this.inBackground=!!e.inBackground,this.audienceEnableSpeaking=!!e.audienceEnableSpeaking,this.raiseHandTime=e.raiseHandTime||0;const i={operation:"none",user:this};this.watcher=new BehaviorSubject(i),this.updateSortNum(!1)}get isWeb(){return!(!this.userInfo.pos||!this.userInfo.pos.includes("web")&&!this.userInfo.pos.includes("pc"))}setup(e,t,r){this.isLocal=!0,this.userId=e,this.userInfo=t,this.nickName=r||t.nickname,this.avatar=t.avatar}getMainStreamModel(){return this.streamModels.get(this.userId)}get nickname(){return this.nickName}getShareStreamModel(){return this.streamModels.get(`${this.userId}${STREAM_SUFFIX_SCREEN}`)}get audioEnable(){const e=this.getMainStreamModel();return!!e&&e._audio_enable}get isMixer(){return this.userId.includes("-mixer-")}get videoEnable(){const e=this.getMainStreamModel();return!!e&&e._video_enable}get isSharing(){let e=!1;for(let t of this.streamModels.values())if(t.isShare){e=!0;break}return e}get isSignal(){var e;return!!(null===(e=this.userId)||void 0===e?void 0:e.startsWith(SIGNAL_SUFFIX))}checkLocalHasMaster(){return this.isMaster||this.isManager}addStream(e,t){this.streamModels.set(e,t),this.watcher.next({operation:"changeShare",user:this})}removeStream(e){this.streamModels.delete(e),e.includes(STREAM_SUFFIX_SCREEN)&&info("删除的是共享屏幕的流:","","",["streamId =>",e]),setTimeout((()=>{this.watcher.next({operation:"changeShare",user:this})}),400)}getID(){return this.userId}getNickName(){return this.nickName}getUserInfo(){return this.userInfo}getStreams(){return this.streamModels}updateUserInfo(e,t={},r){var i,n,s,o,a,c;const u=null===(i=null==t?void 0:t.params)||void 0===i?void 0:i.customInfo,d=(null==u?void 0:u.updateKeys)||[];let l=!1,h="none";if(info("updateUserInfo =>","updateUser",e.userId,["updateKeys",d.toString(),"permission",null===(n=e.permission)||void 0===n?void 0:n.permission,"isMaster =>",this.isMaster,"isManager =>",this.isManager]),this.nickName!==e.nickname&&(h="changeNickName"),this.isMaster||!this.isManager||e.permission.getManage()||(h="removeManager",this.isManager=!1),this.isMaster||this.isManager||!e.permission.getManage()||-1!=d.indexOf("changeMaster")||(h="getManager",this.isManager=!0),e.userinfo.pos)this.userInfo=e.userinfo;else{const t=this.userInfo.pos;this.userInfo=e.userinfo,this.userInfo.pos=t}(d.includes("changeMaster")||d.includes("permission"))&&(e.permission=t.getPermission()),d.includes("raiseHandsAudio")&&(this.raiseAudioHands=u.raiseHandsAudio,h="raiseHandsAudio",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsAudio",user:this}),l=!0),d.includes("raiseHandsVideo")&&(this.raiseVideoHands=u.raiseHandsVideo,h="raiseHandsVideo",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsVideo",user:this}),l=!0),d.includes("raiseHand")&&(this.raiseHand=u.raiseHand,this.raiseHandTime=u.raiseHandTime,h="raiseHand",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHand",user:this}),l=!0),1!==r.conferenceMode&&this.isAudience&&d.includes("permission")&&(-1!==(null===(o=null===(s=t.params)||void 0===s?void 0:s.customInfo)||void 0===o?void 0:o.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!0),this.audienceEnableSpeaking=!0,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceEnable()),-1===(null===(c=null===(a=t.params)||void 0===a?void 0:a.customInfo)||void 0===c?void 0:c.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!1),this.audienceEnableSpeaking=!1,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceDisable())),d.includes("inBackground")&&(h="inBackground",this.inBackground=u.inBackground),this.nickName=e.nickname,this.permission=e.permission;let p=!this.isCommonUser;this.isCommonUser=!e.permission.getSubscribe(),p!==!this.isCommonUser&&(info(`身份有发生过变化,从${p?"嘉宾":"普通参会者"} => ${this.isCommonUser?"普通参会者":"嘉宾"}`),BoomEmitter.emitter.emit(CHANG_IS_GUEST,{user:this,isGuest:!this.isCommonUser,preIsGuest:p})),h&&this.watcher.next({operation:h,user:this}),(!l||l&&!this.isLocal)&&this.updateSortNum(!0)}hasManager(){return this.isManager||this.isMaster}getNicknameSuffix(){let e="";return this.isLocal&&this.isMaster?e="(我、主持人)":this.isLocal&&this.isManager?e="(我、联席主持人)":this.isLocal?e="(我)":this.isMaster?e="(主持人)":this.isManager?e="(联席主持人)":this.isSharing&&!this.isToupingma?e="的共享屏幕":this.isSharing&&this.isToupingma&&(e="(仅共享屏幕)"),e}updateSortNum(e=!0,t=!1){let r=getSortNum(this);this.setSortNum(r,e,t)}setSortNum(e,t,r){this.sortNum!==e&&(this.sortNum=e,t&&BoomEmitter.emitter.emit(USER_SORT_NUM_CHANGE,{isCommon:this.isCommonUser,shouldDelay:r}))}}const NULL=null,UNDEFINED=void 0,RAW_FUNCTION="function";Object.freeze({}),Object.freeze([]);const EMPTY_STRING="";function func(e){return typeof e===RAW_FUNCTION}function indexOf(e,t,r){return e.indexOf(t,r!==UNDEFINED?r:0)}function has(e,t){return indexOf(e,t)>=0}function toString(e,t){return e!=NULL&&e.toString?e.toString():t!==UNDEFINED?t:EMPTY_STRING}function isNative(e){return func(e)&&has(toString(e),"[native code]")}typeof setImmediate===RAW_FUNCTION&&isNative(setImmediate)&&setImmediate,typeof MessageChannel===RAW_FUNCTION&&isNative(MessageChannel);const notGetTalkInterval=3e5;function handleTime(e){let t=new Date(e),r=new Date,i=t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,n=t.getDate()<10?"0"+t.getDate():t.getDate(),s=t.getHours()<10?"0"+t.getHours():t.getHours(),o=t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes();return r.setHours(0,0,0,0)==t.setHours(0,0,0,0)?s+":"+o:i+"月"+n+"日 "+s+":"+o}function sortUsers(e){return e.sort(((e,t)=>e.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND&&t.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND?e.raiseHandTime-t.raiseHandTime:e.sortNum-t.sortNum))}function sortStreamModels(e){return e.sort(((e,t)=>e.sortNum!==t.sortNum?t.sortNum-e.sortNum:Number(e.getUser().isCommonUser)-Number(t.getUser().isCommonUser)))}function getIsCommonUser(e){return!getPermission(e,"s")}function getIsManager(e){return getPermission(e,"m")}function getIsMaster(e){return getPermission(e,"o")}function getPermission(e,t){return e.toLowerCase().includes(t)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}const ignoreUserId=["-mixer-","-rtmpmixer-","record#","robot_","stt_"],BLOUD_PAGE_SIZE=500,PERMISSION_NOT_COMMON="RWPSAVMO,RWPSAVM,RWPSAV";class BMUserVM{constructor(e,t,r){this.userList=new Map,this.audiencesList=new Map,this.signalList=new Map,this.commonUserList=new Map,this.userListWatcher=new BehaviorSubject(Array.from(this.userList.values())),this.audiencesListWatcher=new BehaviorSubject(Array.from(this.audiencesList.values())),this.commonUserListWatcher=new BehaviorSubject(Array.from(this.commonUserList.values())),this.signalListWatcher=new BehaviorSubject(Array.from(this.signalList.values())),this.masterUserWatcher=new BehaviorSubject(null),this.getForceUserWatcher=new BehaviorSubject(!1),this.commTimer=200,this.addBCUser=(e,t=!1)=>{var r;const i=this.addUser(e);if(!this.room.bmStreamVm.streamModels.get(e.userId)){const t=this.getUser(e.userId);t?this.room.bmStreamVm.createStreamModel(t):error$1(`there is no user named ${e.userId}, and create streamModel failed!!!`)}{const i=this.room.bmStreamVm.streamModels.get(e.userId);i&&(e.stream.size?e.stream.forEach((r=>__awaiter(this,void 0,void 0,(function*(){var n,s,o;const{video_enable:a,audio_enable:c,customInfo:u}=r;if(r.screen){this.room.bmStreamVm.shareBloudStateMap.set(e.userId,{audio:c,video:a,customInfo:u,userId:e.userId,streamId:r.getID(),isScreen:!0});const o={id:i.userId,isScreen:!0,isWeb:i.isWeb};if(t){const t=new Map;t.set(e.userId,o),yield null===(n=this.room)||void 0===n?void 0:n.processUser(t)}else null===(s=this.room)||void 0===s||s.addUser2Queue(o)}else if(i&&(i.updateBloudStream({video:a,audio:c,isScreen:r.screen,customInfo:u},this.room.bmStreamVm),t)){const t={id:i.userId,isScreen:!1,isWeb:i.isWeb},r=new Map;r.set(e.userId,t),null===(o=this.room)||void 0===o||o.processUser(r)}})))):(i.bloudStream&&i.updateBloudStream(void 0,this.room.bmStreamVm),null===(r=this.room)||void 0===r||r.bmStreamVm.removeShareStreamModelByUId(e.userId)))}return i&&i.isMaster&&this.masterUserWatcher.next(i),null==i||i.updateSortNum(!1),i},this.updateAllSort=()=>{this.updateUserSort(),this.updateCommonUserSort()},this.updateSortByType=e=>{var t,r;(null===(t=this.room)||void 0===t?void 0:t.isSingleColumns)||e.isCommon?(null===(r=this.room)||void 0===r?void 0:r.isBig)&&e.shouldDelay?this.updateDelayCommonUserSort():this.updateCommonUserSort():this.updateUserSort()},this.updateUserSort=debounce((()=>{const e=this.sortUsers();this.userListWatcher.next(BMUserVM.filterUsers(e))}),200,{maxWait:1e3}),this.updateCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),this.commTimer,{maxWait:12e3}),this.updateDelayCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),12e4,{maxWait:12e4}),this.updateAudienceUserSort=()=>{const e=this.sortAudiences();this.audiencesListWatcher.next(BMUserVM.filterUsers(e))},this.updateSignalUserSort=()=>{const e=this.sortSignalUsers();this.signalListWatcher.next(e)},this.transBloudUsers=(e,t="",r=!1,i=0)=>__awaiter(this,void 0,void 0,(function*(){const n=new Map;yield this.getAllUsers(e,n,t,r).catch((()=>i<3?(error$1("get bloud user error, retry"),i+=1,void this.transBloudUsers(e,t,r,i)):void error$1("get current page of bloud users after 10 times final failed","","",[" page ",e," permission ",t]))),yield this.initUserList(n),n.clear();let s=[];for(let e of this.userList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands)&&s.push(e);this.room.roomInfo.setRaiseHandsList(s),this.updateAllSort(),this.room.bmStreamVm.updateModelSort()})),this.boomCore=e,this.localUser=t,this.room=r,BoomEmitter.emitter||error$1("init boom emitter error"),BoomEmitter.emitter.on(CHANG_IS_GUEST,this.handleUserRoleChange.bind(this)),BoomEmitter.emitter.on(USER_SORT_NUM_CHANGE,this.updateSortByType)}handleUserRoleChange(e){var t,r,i;return __awaiter(this,void 0,void 0,(function*(){const{user:n,isGuest:s,preIsGuest:o}=e,a=null===(t=this.room)||void 0===t?void 0:t.roomInfo.isBigRoom;info("handleUserRoleChange","",n.userId,["isGuest =>",s,"preIsGuest =>",o,"isBigRoom =>",a]);if(1===(null===(r=this.room)||void 0===r?void 0:r.userListColumns)||(o?this.userList.delete(n.userId):this.commonUserList.delete(n.userId),s?this.userList.set(n.userId,n):this.commonUserList.set(n.userId,n)),a)if(s)n.isLocal&&(yield this.initUsers());else{const e=null===(i=this.room)||void 0===i?void 0:i.getLocalParticipant().isCommonUser;if(n.isLocal&&(this.handleUnSubCommonUser(),this.handleCommonUserChange(),this.commonUserList.set(n.userId,n)),e){const e=n.getMainStreamModel();e&&e.unSubscribeStream(),n.isLocal||this.commonUserList.delete(n.userId)}}this.updateAllSort()}))}addUser(e){var t;const r=this.getUser(e.userId);if(r)return info("该用户已经加入房间",LOGGER_TAG_CLIENT,e.userId),this.updateUser(r,e),null;let i;return this.boomCore.userId==e.userId?(this.updateUser(this.localUser,e),i=this.localUser):i=this.toBMUser(e),1===(null===(t=this.room)||void 0===t?void 0:t.userListColumns)?this.commonUserList.set(i.userId,i):i.isAudience?this.audiencesList.set(i.userId,i):i.isSignal?this.signalList.set(i.userId,i):i.isCommonUser?this.commonUserList.set(i.userId,i):this.userList.set(i.userId,i),i}removeUser(e){let t=this.userList.delete(e);return t||(t=this.signalList.delete(e)),t||(t=this.audiencesList.delete(e)),t||(t=this.commonUserList.delete(e)),t||warn("userList中未找到该用户, 移除无效",LOGGER_TAG_CLIENT,e),t}videoEnable(e){const t=this.getUser(e);if(t)return t.videoEnable;throw new BoomError(USER_NOT_EXIT,"用户不存在")}audioEnable(e){const t=this.getUser(e);if(t)return t.audioEnable;throw new BoomError(USER_NOT_EXIT,"用户不存在")}checkIsMaster(e){if(!e)return!1;const t=this.boomCore.getMaster();return!!t&&t===e}checkLocalHasMaster(){return this.localUser.isMaster||this.localUser.isManager}checkUserHasMaster(e){const t=this.userList.get(e);return!!t&&t.permission.getManage()}getUser(e){let t;return t=(null==e?void 0:e.startsWith(SIGNAL_SUFFIX))?this.signalList.get(e):this.userList.get(e),t||(t=this.commonUserList.get(e)),t||(t=this.audiencesList.get(e)),t}getAllUsers(e,t,r="",i=!1){return __awaiter(this,void 0,void 0,(function*(){let n;if(i){let{users:t,total:i}=yield this.boomCore.getUsersList(e,r,BLOUD_PAGE_SIZE);n=t}else{let{users:t,total:i}=yield this.boomCore.getUsers(e,r,BLOUD_PAGE_SIZE);n=t}n.forEach((e=>{t.set(e.userId,e)}))}))}initUserList(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){const i=e.get(this.localUser.userId);if(i){const e=this.addUser(i);if(!(null===(t=this.room)||void 0===t?void 0:t.bmStreamVm.getStreamModelByUId(i.userId))){const e=this.getUser(i.userId);e?null===(r=this.room)||void 0===r||r.bmStreamVm.createStreamModel(e):error$1("there is no local streamModel exits, and create failed!!!")}(null==e?void 0:e.isMaster)&&this.masterUserWatcher.next(e)}e.delete(this.localUser.userId),e&&e.size>0&&this.addBcUsersMap(e)}))}addBcUsersMap(e,t=!1){e.forEach((e=>{this.addBCUser(e,t)}))}updateMaster(e,t,r){const i=this.getUser(e);i&&(i.isManager&&(i.isManager=!1),i.isMaster=!0,i.updateSortNum());const n=this.getUser(t);return n&&(n.isMaster=!1,r&&(n.isManager=!0),n.updateSortNum()),i||n||error$1("未找到该用户, updateMaster未生效",LOGGER_TAG_CLIENT,e,["masterId => ",e,"oldMasterId => ",t]),{master:i,oldMaster:n}}managerChangeToGuest(e){const t=this.getUser(e);return t?t.isManager?(t.permission.setManage(!1),t.permission.setSubscribe(!0),this.boomCore.updateUser(e,{customInfo:{permission:t.permission.get()}}),t.watcher.next({operation:"getGuest",user:t}),this.updateAllSort()):error$1("该用户不是管理员,无法设置为嘉宾",LOGGER_TAG_CLIENT,e):error$1("未找到该用户, managerChangeToGuest未生效",LOGGER_TAG_CLIENT,e),t}updateManager(e,t,r=!0){const i=this.getUser(e);return i?(i.permission.setManage(t),i.permission.setSubscribe(t),this.boomCore.updateUser(e,{customInfo:{permission:i.permission.get()}}),i.watcher.next({operation:t?"getManager":"removeManager",user:i}),this.updateAllSort()):error$1("userList中未找到该用户, updateManager未生效",LOGGER_TAG_CLIENT,e),i}getLocalUser(){return this.localUser}updateUser(e,t){var r,i,n,s,o;const a=this.checkIsMaster(t.userId),c=((null===(r=t.permission)||void 0===r?void 0:r.getManage())||getIsManager(null===(i=t.permission)||void 0===i?void 0:i.permission))&&!((null===(n=t.permission)||void 0===n?void 0:n.getOwn())||getIsMaster(null===(s=t.permission)||void 0===s?void 0:s.permission));let u="none";const d=e.isMaster;e.isManager!==c&&(u=c?"getManager":"removeManager"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),10),d!==a&&(u=a?"getMaster":"removeMaster"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),100);const l=e.raiseHand,h=t.customInfo.raiseHand;l!==h&&(!h&&l&&this.room.roomInfo.removeSimpleRaiseHandUser(e.userId),setTimeout((()=>{e.watcher.next({operation:"raiseHand",user:e})}),300));const p=e.raiseVideoHands,m=t.customInfo.raiseHandsVideo;p!==m&&(!m&&p&&this.room.roomInfo.removeVideoRaiseHandUser(e.userId),setTimeout((()=>{e.watcher.next({operation:"raiseHandsVideo",user:e})}),300));const f=e.raiseAudioHands,g=t.customInfo.raiseHandsAudio;f!==g&&(!g&&f&&this.room.roomInfo.removeRaiseHandUser(e.userId),setTimeout((()=>{e.watcher.next({operation:"raiseHandsAudio",user:e})}),300));e.nickname!==t.nickname&&setTimeout((()=>{e.watcher.next({operation:"changeNickName",user:e})}),300),e.userInfo=t.userinfo,e.nickName=t.nickname,e.userId=t.userId,e.permission=t.permission,e.avatar=t.userinfo.avatar,e.isToupingma=t.userinfo.pos.includes("_toupingma"),e.raiseHand=h,e.isMaster=a,e.isCreate=this.boomCore.getCreator()===t.userId,e.isAudience=!t.permission.getAudio(),e.isCommonUser=!t.permission.getSubscribe(),e.isManager=c,e.inBackground=!!(null===(o=null==t?void 0:t.customInfo)||void 0===o?void 0:o.inBackground),e.updateSortNum()}updateLocalUserPermission(e){const t=this.getLocalUser();t.isMaster=getIsMaster(e),t.isManager=!getIsMaster(e)&&getIsManager(e),t.isCommonUser=getIsCommonUser(e),t.watcher.next({operation:"none",user:t})}toBMUser(e){var t,r;let i={};i.userInfo=e.userinfo,i.nickname=e.nickname,i.userId=e.userId,i.streamModels=[],i.permission=e.permission,i.stream=e.stream,i.isToupingma=!(!e.userinfo.pos||!e.userinfo.pos.includes("_toupingma")),i.isMaster=this.checkIsMaster(i.userId),i.isAudience=!e.permission.getAudio(),i.isCommonUser=!e.permission.getSubscribe()||getIsCommonUser(e.permission.permission),i.raiseAudioHands=e.customInfo.raiseHandsAudio,i.raiseVideoHands=e.customInfo.raiseHandsVideo,i.raiseHand=e.customInfo.raiseHand,i.raiseHandTime=e.customInfo.raiseHandTime,i.inBackground=e.customInfo.inBackground,i.isCreate=this.boomCore.getCreator()===e.userId;let n=this.boomCore.getLocalParticipant();if(!n)throw new BoomError(INVALID_PARAMETER,"BCUserVM addUser时未找到本地用户");return n.getID()==i.userId&&(i.isLocal=!0),!(null===(t=i.permission)||void 0===t?void 0:t.getManage())&&!getIsManager(null===(r=i.permission)||void 0===r?void 0:r.permission)||i.isMaster||(i.isManager=!0),new BMUser(i,i.isLocal)}sortUsers(){return sortUsers(Array.from(this.userList.values()))}sortAudiences(){return sortUsers(Array.from(this.audiencesList.values()))}sortCommonUsers(){return sortUsers(Array.from(this.commonUserList.values()))}sortSignalUsers(){return sortUsers(Array.from(this.signalList.values()))}static filterUsers(e){return e.filter((e=>!ignoreUserId.some((t=>e.userId.includes(t)))))}initUsers(){var e;return __awaiter(this,void 0,void 0,(function*(){const t=yield this.getTotalUserNumber();info(`initUsers total users num: ${t}`);const r=Math.ceil(t/BLOUD_PAGE_SIZE);let i=0;const n=[],s=e=>__awaiter(this,void 0,void 0,(function*(){e<r&&(yield this.transBloudUsers(e-1))})),o=e=>__awaiter(this,void 0,void 0,(function*(){for(const t of e)yield t(),yield sleep(50)}));if(this.localUser.isCommonUser&&(null===(e=this.room)||void 0===e?void 0:e.isBig))this.commonUserList.set(this.localUser.userId,this.localUser),yield this.transBloudUsers(-1,PERMISSION_NOT_COMMON,!0);else{for(;i<r;)n.push(s.bind(null,i)),i+=1;o(n)}}))}handleUnSubCommonUser(){this.commonUserList.forEach((e=>{const t=e.getMainStreamModel();(null==t?void 0:t.hasPulled)&&t.unSubscribeStream()}))}handleCommonUserChange(){let e=new Map;this.room.bmStreamVm.streamModels.forEach((t=>{t.getUser().isCommonUser&&!t.isLocal||e.set(t.userId,t)})),this.room.bmStreamVm.streamModels=e,this.commonUserList.clear()}getUsers(e,t,r="RWPAV"){return __awaiter(this,void 0,void 0,(function*(){const{users:i,total:n}=yield this.boomCore.getUsers(e,r,t),s=[];return i.forEach((e=>{const t=this.toBMUser(e);s.push(t)})),{userList:s,total:n}}))}getUsersList(e,t,r="",i=!1){var n,s;return __awaiter(this,void 0,void 0,(function*(){const{users:o,total:a,pageIndex:c}=yield this.boomCore.getUsersList(e,r,t,i),u=[];return o.forEach((e=>{const t=this.toBMUser(e);u.push(t)})),i&&(null===(n=this.room)||void 0===n?void 0:n.roomInfo.totalWaitRoomUserWatcher.value)!==a&&(null===(s=this.room)||void 0===s||s.roomInfo.totalWaitRoomUserWatcher.next(a)),{userList:u,total:a,pageIndex:c}}))}getTotalUserNumber(){return __awaiter(this,void 0,void 0,(function*(){const e=()=>__awaiter(this,void 0,void 0,(function*(){const{total:e}=yield this.boomCore.getUsers(0,"",1);return e})),t=r=>{e().then((e=>{r(e)})).catch((e=>{error$1("getTotalUserNumber error","","",[JSON.stringify(e)]),t(r)}))};return new Promise(((e,r)=>__awaiter(this,void 0,void 0,(function*(){t(e)}))))}))}clearUsers(){this.userList.clear(),this.commonUserList.clear(),this.audiencesList.clear(),this.signalList.clear()}searchUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!1);let i=[],n=[];return r.forEach((e=>{const t=this.userList.get(e.userId);if(t)return void i.push(t);const r=this.commonUserList.get(e.userId);r&&n.push(r)})),{userList:i,commonUserList:n}}catch(e){return Promise.reject(new BoomError(LOCAL_ERROR,"boomCore.searchUsers发生错误:"+(null==e?void 0:e.message)))}}))}searchWaitRoomUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!0),i=[];return r.forEach((e=>{const t=this.toBMUser(e);i.push(t)})),i}catch(e){return Promise.reject(new BoomError(LOCAL_ERROR,"search wait room users error"))}}))}}class BMMessageInfo{constructor(e){this.isMeetingNotice=!1,this.userId=e.userId,this.message=e.message,this.role=e.role,this.isLocal=e.isLocal,this.avatar=e.avatar,this.nickName=e.nickName,this.to=e.to,this.isDanger=e.isDanger,this.seq=e.seq,this.failed=e.failed;let t=!1;e.isMeetingNotice&&(t=!0),this.isMeetingNotice=t,e.sendTime?(this.timeStamp=e.sendTime,this.time=handleTime(this.timeStamp)):(this.timeStamp=(new Date).getTime(),this.time=handleTime(this.timeStamp))}}function isShareStream(e){const t=e.getStreamId();return e.getUserId().toString().endsWith(STREAM_SUFFIX_SCREEN)||t.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()}function checkStreamIsNormal(e){var t,r,i,n;if(e&&!e.isLocal){(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)))&&setTimeout((()=>{var t,r,i,n;(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)))&&(warn("用户流检测,但是流订阅出现了问题,需要重新订阅","用户流检测",e.userId,[" nickname => ",e.nickname,"isDisplay =>",e.isDisplay]),e.hasPulled=!1,e.pulledStreamType="small",e.sendMessage2Room())}),2e3)}}function handleBloudReconnectStreamEvent(e){var t,r;const i=e.getLocalStreamModel();if(i&&!(null==i?void 0:i.stream))e.bloudStream&&(info("brtc 已经没有流了,bloud 的流要取消掉"),e.bloudStream.unpublish(),i.updateBloudStream(void 0,e),e.bloudStream=null);else if(i&&i.stream){info("brtc 流已经重推上去了,bloud要重新发推流的逻辑");const t=i.stream.getAudioOn(),r=i.stream.getVideoOn();e.publishBloudStream(t,r).then((()=>{info("brtc stream repub success bloud repub success, notify reconnect success"),e.localStreamConnectErrorWatcher.next(require$$0.BMStreamReconnectSuccess(t,r))}))}if(e.localIsShare){info("brtc has share stream, and bloud need to republish share stream");const i=null===(t=e.room)||void 0===t?void 0:t.boomCore.shareScreenStream;if(i){const t=i.getAudioOn(),n=i.getVideoOn();try{null===(r=e.room)||void 0===r||r.boomCore.createAndPubBloudShareStream(t,n)}catch(e){error$1("bloud 共享屏幕流,断网重连重推流失败")}}}}const handleReconnectedStream=debounce((e=>{if(e.networkState.bloud&&e.networkState.brtc)try{e.streamQueue.restart()}catch(t){e.streamQueue.setQueueProcessor(e.queueProcessor),e.streamQueue.restart()}}),300);function handleStreamPublished(e,t,r,i){const n=e.stream;if(info("本地推流","本地推流",n.getUserId()),n){const e=t.getLocalStreamModel();if(e&&t.updateStreamModel(e,n),i[require$$0.BrtcEvents.STREAM_PUBLISHED].next({published:!0,model:e}),1===r.conferenceMode){r.getLocalParticipant().isAudience&&t.getStreamModels().forEach((e=>{e.sendMessage2Room()}))}}else i[require$$0.BrtcEvents.STREAM_PUBLISHED].next({published:!1})}function handleBloudStreamPublished(e,t,r){info("bloud publish stream"),handleBloudStreamPubAUpdate(e,t,!0),r[require$$0.BloudEvents.STREAM_PUBLISHED].next(e)}function handleBloudStreamPubAUpdate(e,t,r=!1){var i;info("bloud stream update","","",[JSON.stringify(e)]);const n=e.userId,s=e.isScreen,o=t.streamModels.get(n);if(o)if(s){t.shareBloudStateMap.set(n,e);const r={id:n,isWeb:o.isWeb,isScreen:s};null===(i=t.room)||void 0===i||i.addUser2Queue(r)}else o.updateBloudStream(e,t,r),o.getUser().updateSortNum();else error$1("bloud stream update, but can not get streamModel","",n)}function handleBloudStreamUnPublished(e,t,r){info("bloud unpublish stream","","",[JSON.stringify(e)]),handleBloudStreamUnpublish(e,t),r[require$$0.BloudEvents.STREAM_REMOVED].next(e)}function handleBloudStreamUpdated(e,t,r){info("bloud stream update","","",[JSON.stringify(e)]);const i=e.streamId,n=e.userId,s=e.params.customInfo;let o;o=i.includes("_screen")?t.shareStreamModels.get(n):t.streamModels.get(n),o?o.updateBloudCustomInfo(s):error$1("bloud stream update, but can not get streamModel","",n,["streamId =>",i]),r[require$$0.BloudEvents.UPDATE_STREAM].next(e)}function handleBloudStreamUnpublish(e,t){var r,i,n;const s=e.userId;if(e.isScreen){const e=t.shareStreamModels.get(s);if(e){const r=e.stream;r?(r.destroy(),t.remoteStreamUnpublished(r)):t.removeShareStreamModelByUId(s);const i={id:s,isWeb:e.isWeb,isScreen:!0};null===(n=t.room)||void 0===n||n.streamQueue.removeUsers([i])}}else{const e=t.streamModels.get(s);if(e){e.updateBloudStream(void 0,t);const n=e.stream;n&&(null===(r=t.room.audioPlayer)||void 0===r||r.removeStream(n),t.remoteStreamUnpublished(n),n.destroy());const o={id:s,isWeb:e.isWeb,isScreen:!1};null===(i=t.room)||void 0===i||i.streamQueue.removeUsers([o])}}}function handleShareStreamFailed(e,t){setTimeout((()=>__awaiter(this,void 0,void 0,(function*(){info("handle republish share stream");try{const r=e.boomCore.shareScreenStream;if(r){const i=r.getAudioOn(),n=r.getVideoOn();yield e.boomCore.shareBrtcClient.publish(r),e.boomCore.createAndPubBloudShareStream(i,n),info("handle republish share stream success"),t.localShareError.next(require$$0.BMShareStreamReconnectSuccess())}else warn("no share stream exist, unpublish share stream, to prevent share stream state error"),t.toggleShareScreen(!1,void 0)}catch(e){error$1("handle republish share stream failed , now unpublish"),t.localShareError.next(require$$0.BMShareStreamReconnectFailed()),yield t.toggleShareScreen(!1,void 0)}}))),1e3)}function setupRoomInfo(e,t,r){const i=e.permission,n=e.total;i&&r.updateLocalUserPermission(i),t.isInWaitRoom=e.joinwait;const s=e.waitroom;t.roomInfo.isOpenWaitRoom.next(s),t.roomInfo.totalUserWatcher.next(n);const o=e.audiooff,a=e.selfopenaudio;o===t.roomInfo.audioOff&&a===t.roomInfo.selfopenaudio||null!=o&&null!=a&&t.roomInfo.setAudioOff(o,a)}function handleRoomConnected(e,t,r,i,n=!0){var s;return __awaiter(this,void 0,void 0,(function*(){info("room-connected",t.getLocalParticipant().userId,"room-connected",["roomId =>",t.roomInfo.roomID," local permission => ",e.permission]),t.forceId=null===(s=e.customStats.forceOn)||void 0===s?void 0:s.user,handleInitRoomInfo(e,t),setupRoomInfo(e,t,r),n&&i[require$$0.BloudEvents.ROOM_CONNECTED].next(e)}))}function handleInitJoinRoomUsers(e){return __awaiter(this,void 0,void 0,(function*(){info("join ready init users"),e.isInWaitRoom||(e.forceId&&(yield e.getForceUser(e.forceId)),yield e.userVM.initUsers())}))}function handleRoomUpdated(e,t){info("update-stats "," ","",["options => ",JSON.stringify(e.options)]),e.options&&"audiooff"==e.options[0]||"selfopenaudio"==e.options[1]?t.roomInfo.setAudioOff(e.room.audiooff,e.room.selfopenaudio):e.options&&"lock"==e.options[0]?t.roomInfo.setlock(e.room.lock):e.options&&"waitroom"==e.options[0]&&t.roomInfo.isOpenWaitRoom.next(e.stats.waitroom)}function handleInitRoomInfo(e,t){t.roomInfo.msgSeq=e.msgSeq,e.customStats&&t.roomInfo.initCustomStats(e.customStats)}function exitUserUpdateStream(e,t,r,i,n){var s;e.updateUser(t,r);const o=r.stream,a=i.streamModels.get(t.userId);if(a||error$1("bmUserVM中存在该用户,但是bmStreamModelVM中不存在该用户,佛了"),!o.size){(null==a?void 0:a.bloudStream)&&(a.updateBloudStream(void 0,i),n.streamQueue.removeUsers([{id:t.userId,isScreen:!1},{id:t.userId,isScreen:!0}]));const e=i.shareStreamModels.get(t.userId);if(e&&!e.isLocal){try{null===(s=e.stream)||void 0===s||s.destroy()}catch(e){}i.removeShareStreamModel(e)}}o.get(`${t.userId}_screen`)&&n.addUser2Queue({id:t.userId,isScreen:!0,isWeb:t.isWeb});const c=o.get(t.userId);c&&(null==a||a.updateBloudStream({audio:c.audio_enable,video:c.video_enable,isScreen:!1},i))}function addUsers(e,t,r,i){e.isSingleColumns?t.commonUserList.forEach((n=>{const s=r.get(n.userId);if(s)return r.delete(n.userId),void exitUserUpdateStream(t,n,s,i,e);t.commonUserList.delete(n.userId),i.streamModels.delete(n.userId),i.shareStreamModels.delete(n.userId)})):t.userList.forEach((n=>{const s=r.get(n.userId);if(s)return exitUserUpdateStream(t,n,s,i,e),void(n.isCommonUser?t.userList.delete(n.userId):r.delete(n.userId));t.userList.delete(n.userId),i.streamModels.delete(n.userId),i.shareStreamModels.delete(n.userId)})),e.userVM.addBcUsersMap(r)}function handleRoomSync(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){const n=t.getLocalParticipant().userId,{users:s}=yield t.boomCore.queryUsers([n]),o=s.get(n);o&&r.updateUser(r.localUser,o);const a=t.getLocalParticipant().isCommonUser;if(t.isBig&&a){const{users:e}=yield t.boomCore.getUsersList(0,PERMISSION_NOT_COMMON,500);addUsers(t,r,e,i)}else{const e=(yield t.userVM.getTotalUserNumber())/BLOUD_PAGE_SIZE;let n=new Map;for(let r=0;r<e;r++){let{users:e}=yield t.boomCore.getUsers(r-1,"",BLOUD_PAGE_SIZE);e.forEach((e=>{n.set(e.userId,e)}))}addUsers(t,r,n,i)}handleInitRoomInfo(e,t),t.userVM.updateAllSort(),t.bmStreamVm.updateModelSort()}))}function handleBrtcRoomReconnecting(e,t,r){info("brtc room reconnecting"),t.networkState.brtc=!1,t.streamWSReconnectWatcher.next(!1),r[require$$0.BrtcEvents.BRTC_ROOM_ROCONNECTING].next(e)}function handleBrtcRoomReconnected(e,t,r){info("brtc room reconnected"),t.networkState.brtc=!0,handleReconnectedStream(t),r[require$$0.BrtcEvents.BRTC_ROOM_RECONNECTED].next(e)}function handleBloudRoomReconnecting(e,t,r){info("bloud room reconnecting"),t.networkState.bloud=!1,t.bloudWSReconnectWatcher.next(!1),r[require$$0.BloudEvents.RECONNECTING].next(e)}function handleBloudRoomReconnected(e,t,r){return __awaiter(this,void 0,void 0,(function*(){t.hasSyncPermission?(info("bloud room reconnected"),t.bloudWSReconnectWatcher.next(!1),r[require$$0.BloudEvents.MOVE_USER_ROOM].next(null),yield t.syncRoom().then((()=>{t.hasSyncPermission=!0,r[require$$0.BloudEvents.ROOM_CONNECTED].next(e)})).catch((e=>{error$1("sync room error",JSON.stringify(e));if(43===e.code)return t.hasSyncPermission=!1,void r[require$$0.BloudEvents.USER_REJOINED].next(e);t.hasSyncPermission=!1,r[require$$0.BloudEvents.TIMEOUT].next(e)}))):r[require$$0.BloudEvents.TIMEOUT].next(e)}))}function handleBloudRoomSync(e,t,r,i,n){return __awaiter(this,void 0,void 0,(function*(){info("bloud sync room completed"),setupRoomInfo(e,r,t),yield handleRoomSync(e,r,t,i),handleBloudReconnectStreamEvent(i),r.networkState.bloud=!0,handleReconnectedStream(r),r.bloudWSReconnectWatcher.next(!0),n[require$$0.BloudEvents.ROOM_SYNCED].next(e)}))}const{USER_REJOINED:USER_REJOINED,PARTICIPANT_JOINED:PARTICIPANT_JOINED,CHANGE_MASTER:CHANGE_MASTER,EVICTED:EVICTED,UPDATE_USER:UPDATE_USER,PARTICIPANT_LEFT:PARTICIPANT_LEFT,CUSTOM_MESSAGE:CUSTOM_MESSAGE,MOVE_USER_ROOM:MOVE_USER_ROOM}=require$$0.BloudEvents;function handleParticipantJoin(e,t,r,i,n,s){var o,a,c,u,d,l,h,p,m,f,g,v,y;const _=null===(a=null===(o=null==e?void 0:e.participant)||void 0===o?void 0:o.params)||void 0===a?void 0:a.info.sync,b=e.mode;info("用户入会","用户入会",e.user.userId,["sync => ",_,"mode =>",b]);const S=t.room.isBig&&r.streamModels.size>1e3;let I=!1;if(_){let r=t.userList.get(e.user.userId);if(r||(r=t.commonUserList.get(e.user.userId)),r)return void(r.inBackground!=!!(null===(u=null===(c=e.user)||void 0===c?void 0:c.customInfo)||void 0===u?void 0:u.inBackground)&&(r.inBackground=!!(null===(l=null===(d=e.user)||void 0===d?void 0:d.customInfo)||void 0===l?void 0:l.inBackground),r.watcher.next({operation:"inBackground",user:r})))}1===b&&(null===(h=t.room)||void 0===h?void 0:h.isBig)&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId));if(getIsCommonUser(e.user.permission.permission)){t.userList.get(e.user.userId)&&(t.userList.delete(e.user.userId),r.streamModels.delete(e.user.userId),I=!0)}else{const i=t.commonUserList.get(e.user.userId);(null===(p=t.room)||void 0===p?void 0:p.isSingleColumns)||i&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId),I=!0)}let E=t.addBCUser(e.user);if(E){E.inBackground!=!!(null===(f=null===(m=e.user)||void 0===m?void 0:m.customInfo)||void 0===f?void 0:f.inBackground)&&(E.inBackground=!!(null===(v=null===(g=e.user)||void 0===g?void 0:g.customInfo)||void 0===v?void 0:v.inBackground),E.watcher.next({operation:"inBackground",user:E}));let o=!1;if(ignoreUserId.forEach((e=>{(null==E?void 0:E.userId.includes(e))&&(o=!0)})),I?t.updateAllSort():(null===(y=t.room)||void 0===y?void 0:y.isSingleColumns)?t.updateCommonUserSort():E?E.isCommonUser?S?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),!o){if(1!==e.mode){const e=new BMMessageInfo({isMeetingNotice:!0,userId:E.userId,message:E.nickName+"加入"+(2==i.roomType?"直播":"会议")});n.addMessage(e,!0)}s[PARTICIPANT_JOINED].next({user:E,mode:b,data:e})}}}function handleLeaveUsers(e,t,r,i,n,s,o){var a;const c=e.userIds;info("bloud leave users","","",["userIds =>",c]),c.length&&(c.forEach((e=>{const a=leaveUser(e,t,r,n);a&&sendLeveNotification(a,s,o,i,!0,0)})),(null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():t.updateAllSort(),n.updateModelSort())}function handleParticipantLeft(e,t,r,i,n,s,o){var a;info(`bloud participant left ===>${e.userId}, ${e.mode}`);const c=1===e.mode,u=e.userId,d=r.isBig&&n.streamModels.size>1e3;if(u){const l=leaveUser(u,t,r,n);if((null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():l?l.isCommonUser?d?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),n.updateModelSort(),c)return void i[PARTICIPANT_LEFT].next({user:l,mode:e.mode,data:e});l&&sendLeveNotification(l,s,o,i,1!==e.mode,e.mode)}else warn("participant-left触发=======>但是该用户信息不存在",LOGGER_TAG_CLIENT,null,[e.userId]),i[PARTICIPANT_LEFT].next({user:e.userId,mode:e.mode,data:e})}function sendLeveNotification(e,t,r,i,n,s){let o=!1;if(ignoreUserId.forEach((t=>{(null==e?void 0:e.userId.includes(t))&&(o=!0)})),!o){if(n){const i=new BMMessageInfo({isMeetingNotice:!0,userId:e.userId,message:(null==e?void 0:e.nickName)+"离开"+(2==t.roomType?"直播":"会议")});r.addMessage(i,!0)}i[PARTICIPANT_LEFT].next({user:e,mode:s})}}function leaveUser(e,t,r,i){const n=t.getUser(e);return t.removeUser(e),r.streamQueue.removeUsers([{id:e,isScreen:!1},{id:e,isScreen:!0}]),i.removeStreamModelByUId(e),i.removeShareStreamModelByUId(e),r.roomInfo.removeRaiseHandUser(e),r.roomInfo.removeVideoRaiseHandUser(e),r.roomInfo.removeSimpleRaiseHandUser(e),i.shareBloudStateMap.delete(e),n}function handleChangeMaster(e,t,r,i,n){info("changeMaster =>","changeMaster","",["master: => ",e.master,"oldMaster =>",e.oldMaster]);const s=e.master,o=e.oldMaster,a=e.isKeep;if(s){let c=t.updateMaster(s,o,a);c.master&&(c.master.watcher.next({operation:"getMaster",user:c.master}),r.userVM.masterUserWatcher.next(c.master)),c.oldMaster&&(c.oldMaster.watcher.next({operation:"removeMaster",user:c.oldMaster}),a&&c.oldMaster.watcher.next({operation:"getManager",user:c.oldMaster}));const u=n.getStreamModelByUId(o),d=n.getStreamModelByUId(s);null==u||u.updateSortNum(),null==d||d.updateSortNum(),i[CHANGE_MASTER].next({master:c.master,oldMaster:c.oldMaster,data:e})}else warn("change-master触发=======>但是房间内找不到master",LOGGER_TAG_CLIENT,null,s),i[CHANGE_MASTER].next(null)}function handleEvict(e,t,r,i,n){var s;const o=e.userId,a=t.getUser(o);info("踢出用户 => ","evict ",null==a?void 0:a.userId,["nickname => ",null==a?void 0:a.nickName]);const c=leaveUser(o,t,i,r);(null===(s=t.room)||void 0===s?void 0:s.isSingleColumns)?t.updateCommonUserSort():c?c.isCommonUser?t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),n[EVICTED].next(e)}function handleUpdateUser(e,t,r,i,n){var s,o;if(info("用户信息被改变","",null===(s=e.user)||void 0===s?void 0:s.userId),null===(o=e.user)||void 0===o?void 0:o.userId){let s=t.getUser(e.user.userId),o=i.getStreamModelByUId(e.user.userId);s?s.updateUserInfo(e.user,e.participant,r):console.warn("participant-update: bmUser is null"),o&&o.updateSortNum(!0),n[UPDATE_USER].next({bmUser:s,params:e.participant.params})}}const handleUserRejoined=debounce(((e,t)=>{e[USER_REJOINED].next(t)}),1e3);function handleMoveUserRoom(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){info("bloud move user room","","",[r]);const n=r.toWait;if(e.isInWaitRoom=n,n){e.handleResetOtherStreamStatus(),t.userList.clear(),t.userListWatcher.next([]),t.commonUserList.clear(),t.commonUserListWatcher.next([]),t.getForceUserWatcher.next(!1),e.bmStreamVm.streamModels.clear(),e.bmStreamVm.clearDetector(),e.bmStreamVm.speakerWatcher.next(null),i[CUSTOM_MESSAGE].next(null),e.messageWatcher.next({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),e.audioPlayer.destroy();const r=e.bmStreamVm.localModel;r&&e.bmStreamVm.streamModels.set(r.userId,r),e.bmStreamVm.streamModelsWatcher.next([]),e.bmStreamVm.shareStreamModels.clear(),e.bmStreamVm.shareStreamModelsWatcher.next([]),e.roomInfo.raiseHandsWatcher.next([]),e.roomInfo.raiseVideoHandsWatcher.next([]),e.roomInfo.raiseSimpleHandsWatcher.next([]),i[MOVE_USER_ROOM].next(n),Object.values(e.observes).forEach((e=>{e.next(null)}))}else{const{audiooff:s,selfopenaudio:o,lock:a}=r.info;a!==e.roomInfo.lock&&e.roomInfo.setlock(a),s===e.roomInfo.audioOff&&o===e.roomInfo.selfopenaudio||e.roomInfo.setAudioOff(s,o),yield handleRoomConnected(r.info,e,t,i,!0),yield handleInitJoinRoomUsers(e),i[MOVE_USER_ROOM].next(n)}}))}function handleSendMessage(e,t,r,i){var n,s,o,a,c,u,d,l,h;let p=Object.assign({},e);if(p.message){if(p.message="string"==typeof p.message?JSON.parse(p.message):p.message,info("new-message","","",[" method => ",p.message.method]),"send-talk"===p.message.method){const i=p.user===(null===(n=t.getLocalUser())||void 0===n?void 0:n.userId),m=(null===(o=null===(s=p.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.status)||"",f=null===(u=null===(c=null===(a=p.message)||void 0===a?void 0:a.params)||void 0===c?void 0:c.stream)||void 0===u?void 0:u.avatar,g=e.seq,v=new BMMessageInfo({userId:p.user,message:m,isLocal:i,avatar:f,to:p.to,seq:g,nickName:null===(h=null===(l=null===(d=p.message)||void 0===d?void 0:d.params)||void 0===l?void 0:l.stream)||void 0===h?void 0:h.nickname,sendTime:(new Date).getTime()});r.addMessage(v,!1)}i[require$$0.BloudEvents.SEND_MESSAGE].next(p)}}function handleCustomMessage(e,t,r){var i,n,s,o,a,c,u,d,l,h,p,m,f;let g=Object.assign({},e);if(g.message)if(g.message="string"==typeof g.message?JSON.parse(g.message):g.message,info("custom-message","","",[" method => ",g.message.method]),"video-force-change"==g.message.method){const e="enabled"==g.message.params.status;info(`远端控制本地摄像头: ${e}`),t.messageWatcher.next({type:MessageType.VIDEO_FORCE_CHANGE,status:e,fromUserId:g.user})}else if("audio-force-change"==g.message.method){let e;e="checkUserAudio"==g.message.params.status?g.message.params.status:"enabled"==g.message.params.status,info(`远端控制本地麦克风: ${e}`),t.messageWatcher.next({type:MessageType.AUDIO_FORCE_CHANGE,status:e,fromUserId:g.user,isNotCancelRootReport:null===(i=g.message.params)||void 0===i?void 0:i.isNotCancelRootReport})}else if("raise-hands"===g.message.method)t.raiseHandleRespWatcher.next(g.message.params);else if("give-like"===g.message.method)null===(n=t.roomVM)||void 0===n||n.giveLikeList.push({userId:g.user,nickName:null===(a=null===(o=null===(s=g.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.stream)||void 0===a?void 0:a.nickname,time:(new Date).getTime(),type:null===(d=null===(u=null===(c=g.message)||void 0===c?void 0:c.params)||void 0===u?void 0:u.stream)||void 0===d?void 0:d.type}),null===(l=t.roomVM)||void 0===l||l.giveLikeListWatcher.next(null===(h=t.roomVM)||void 0===h?void 0:h.giveLikeList);else if("resp-to-check-devices"===g.message.method)(null===(p=g.message)||void 0===p?void 0:p.params)&&(g.message.params.fromUserId=g.user),r[require$$0.BloudEvents.CUSTOM_MESSAGE].next(g);else if("usercount"===g.message.method){if(g.message.params){let e=null===(f=null===(m=g.message)||void 0===m?void 0:m.params)||void 0===f?void 0:f.total;e?(e=Number(e),e<0&&(warn("服务返回的usercount为负数,"+e),e=0)):(warn("服务未返回usercount,"+e),e=0),t.roomInfo.totalUserWatcher.next(e)}}else if("waitusercount"===g.message.method){if(g.message.params){const e=g.message.params.total;t.roomInfo.totalWaitRoomUserWatcher.next(e)}}else r[require$$0.BloudEvents.CUSTOM_MESSAGE].next(g)}let reconnectFailed=0,shareReconnectFailed=0;const NETWORK_ERROR_QUEUE=new Set;function handleBRTCRoomError(e,t,r,i,n){return __awaiter(this,void 0,void 0,(function*(){error$1("brtc error","brtc error","",[(new Date).toLocaleTimeString(),JSON.stringify(e),e.getCode()]);if(4002===e.getCode()){t.BRTCConnectFailed=!0,t.networkState.brtc=!1,warn("brtc 信令通道错误,需要重新走入会","brtc error",""),t.streamWSReconnectWatcher.next(!1);try{yield r.brtcClient.leave("room_close")}catch(e){error$1("brtc 离会失败")}setTimeout((()=>__awaiter(this,void 0,void 0,(function*(){t.handleResetOtherStreamStatus(),yield reconnectBrtcWS(r,t,n,e).catch((t=>{info("brtc断网重连失败, 处理一下退会逻辑","","",[JSON.stringify(t)]),n[require$$0.BrtcEvents.ERROR].next(e)}))}))),1e3)}else n[require$$0.BrtcEvents.ERROR].next(e)}))}function reconnectBrtcWS(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{setTimeout((()=>{info("brtc重连"),e.brtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>__awaiter(this,void 0,void 0,(function*(){info("brtc断网重连成功, 重新处理拉流和推流"),t.networkState.brtc=!0,setTimeout((()=>{t.brtcNetEnableWatcher.next(!0)}),2e3),handleReconnectedStream(t),t.BRTCConnectFailed=!1,reconnectFailed=0,yield t.handleRePushSelf(),t.streamWSReconnectWatcher.next(!0),n(!0)})))).catch((n=>{const o=n.getCode();info("断网重连入会失败","","",[n,o]),reconnectFailed<=10?(reconnectFailed+=1,e.brtcClient.isJoinning=!1,setTimeout((()=>{reconnectBrtcWS(e,t,r,i)}),2e3)):(error$1("brtc断网重连失败,处理一下退会"),reconnectFailed=0,r[require$$0.BrtcEvents.ERROR].next(i),s(!1))}))}),7e3)}))}))}function reconnectBRTCShareWS(e){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{setTimeout((()=>{info("共享屏幕重连"),e.shareBrtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>{shareReconnectFailed=0,t(!0)})).catch((t=>{const r=t.getCode();if(info("共享屏幕断网重连入会失败","","",[t,r]),!(shareReconnectFailed<=3))throw error$1("共享屏幕用户重连失败,处理一下取消共享屏幕"),shareReconnectFailed=0,new Error("共享屏幕重连失败");shareReconnectFailed+=1,reconnectBRTCShareWS(e)}))}),7e3)}))}))}function handleBloudError(e,t,r,i,n){return __awaiter(this,void 0,void 0,(function*(){error$1("network-error","network-error","local-client",["本地链接出现问题","netconnectiong => ",e.netConnecting]),e.netConnecting?yield handleBloudRoomReconnected(i,e,n):n[require$$0.BloudEvents.TIMEOUT].next(i)}))}function handleCustomStats(e,t,r){let i=null==e?void 0:e.updateKeys;info("update-custom-stats"," "," ",["updateKeys => ",JSON.stringify(i)]),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich"))||(null==i?void 0:i.includes("fileUpdateLook"))||(null==i?void 0:i.includes("fileUpdateDown"))||(null==i?void 0:i.includes("fileUpdateEdit"))||(null==i?void 0:i.includes("fileUpdateModel"))||(null==i?void 0:i.includes("screenShareModel"))||(null==i?void 0:i.includes("onlyOnePersonShare"))||(null==i?void 0:i.includes("chatEnable"))||(null==i?void 0:i.includes("giveLikeEnable"))||(null==i?void 0:i.includes("cloudRecord"))||(null==i?void 0:i.includes("joinAudioEnable"))||(null==i?void 0:i.includes("joinVideoEnable"))||(null==i?void 0:i.includes("userListEnable"))||(null==i?void 0:i.includes("audioEnable"))||(null==i?void 0:i.includes("videoEnable"))||(null==i?void 0:i.includes("modifyNameEnable"))||(null==i?void 0:i.includes("backgroundAIEnable"))||(null==i?void 0:i.includes("recordEnable"))||(null==i?void 0:i.includes("joinMicrophoneDisable"))||(null==i?void 0:i.includes("joinCameraDisable"))||(null==i?void 0:i.includes("raiseHandEnable"))||(null==i?void 0:i.includes("forceOpenUserMic"))||(null==i?void 0:i.includes("forceOpenUserCamera"))||(null==i?void 0:i.includes("joinCueVoice")))&&t.roomInfo.updateOperationPermission(e.customStats),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich")))&&t.roomInfo.chatNoticeWatcher.next(e),r[require$$0.BloudEvents.UPDATE_CUSTOM_STATS].next(e)}var dist={},eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,i,s,o){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new n(i,s||e,o),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 o(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,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},a.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,o=new Array(s);n<s;n++)o[n]=i[n].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,n,s,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,u,d=this._events[a],l=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,s),!0;case 6:return d.fn.call(d.context,t,i,n,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var h,p=d.length;for(u=0;u<p;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,i);break;case 4:d[u].fn.call(d[u].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,i,n){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||n&&!a.once||i&&a.context!==i||o(this,s);else{for(var c=0,u=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||i&&a[c].context!==i)&&u.push(a[c]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(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}(eventemitter3);var pTimeout$1={exports:{}},pFinally$1=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))));const pFinally=pFinally$1;class TimeoutError extends Error{constructor(e){super(e),this.name="TimeoutError"}}const pTimeout=(e,t,r)=>new Promise(((i,n)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);const s=setTimeout((()=>{if("function"==typeof r){try{i(r())}catch(e){n(e)}return}const s=r instanceof Error?r:new TimeoutError("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),n(s)}),t);pFinally(e.then(i,n),(()=>{clearTimeout(s)}))}));pTimeout$1.exports=pTimeout,pTimeout$1.exports.default=pTimeout,pTimeout$1.exports.TimeoutError=TimeoutError;var priorityQueue={},lowerBound$1={};function lowerBound(e,t,r){let i=0,n=e.length;for(;n>0;){const s=n/2|0;let o=i+s;r(e[o],t)<=0?(i=++o,n-=s+1):n=s}return i}Object.defineProperty(lowerBound$1,"__esModule",{value:!0}),lowerBound$1.default=lowerBound,Object.defineProperty(priorityQueue,"__esModule",{value:!0});const lower_bound_1=lowerBound$1;class PriorityQueue{constructor(){Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]})}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const i=lower_bound_1.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}priorityQueue.default=PriorityQueue,Object.defineProperty(dist,"__esModule",{value:!0});const EventEmitter=eventemitter3.exports,p_timeout_1=pTimeout$1.exports,priority_queue_1=priorityQueue,empty=()=>{},timeoutError=new p_timeout_1.TimeoutError;class PQueue extends EventEmitter{constructor(e){var t,r,i,n;if(super(),Object.defineProperty(this,"_carryoverConcurrencyCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isIntervalIgnored",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalCap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalEnd",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queueClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_concurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isPaused",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_resolveEmpty",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_resolveIdle",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_throwOnTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:priority_queue_1.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(n=null===(i=e.interval)||void 0===i?void 0:i.toString())&&void 0!==n?n:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother()}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=empty,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=empty)}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother)return this.emit("active"),this._queue.dequeue()(),e&&this._initializeIntervalIfNeeded(),!0}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={},r=null){return new Promise(((i,n)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const s=void 0===this._timeout&&void 0===t.timeout?e():p_timeout_1.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&n(timeoutError),r&&r("resolve-timeout")}));r&&r("resolving"),i(await s),this._isPaused?r&&r("resolve-paused"):r&&r("resolve")}catch(e){this._isPaused?r&&r("resolve-paused"):r&&r("resolve"),n(e)}this._next()}),t),this._tryToStartAnother()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}var _default=dist.default=PQueue;class Pqueue{constructor(e,t=!0){this.queue=new _default({concurrency:e,autoStart:t,carryoverConcurrencyCount:!0,timeout:3e3,completeAction:e=>{console.log("task complete",e)}}),this.queueArray=[],this.isTaskPending=t}addQueue(e,t,r=0,i=""){this.queue.isPaused&&this.queue.start();let n={};n.taskID=t,n.status="pending",this.queue.add(e,{priority:r,timeout:3e3},(e=>{if(n.status=e,"resolve"===n.status||"resolve-paused"===n.status||"resolve-timeout"===n.status){const e=this.queueArray.findIndex((e=>n.taskID===e.taskID));-1!==e&&this.queueArray.splice(e,1)}})),this.queueArray.push(n)}clearQueue(){this.queue.clear(),this.queueArray=[],this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{console.log("clearQueue全部完事")}))}startQueue(){this.queue.start()}pauseQueue(){return this.queue.pause(),console.log(`size:${this.size()}`),this.isTaskPending=!1,this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{})),this.queueArray}size(){return this.queue.size}pending(){return this.queue.pending}checkTaskStatus(){return this.isTaskPending}setTaskStatus(e){this.isTaskPending=e}onIdle(){return this.queue.onIdle()}onEmpty(){return this.queue.onEmpty()}}const streamPullQueue=new Pqueue(4),eventQueue=new Pqueue(10);var MessageType,PlayerState;function attachEvents(e,t,r,i,n){info("attachEvents init");let s={};e.on("toggle-screen-share",(()=>{error$1("share stream video track ended, now unpublish share stream"),r.localShareError.next(require$$0.BMShareStreamReconnectFailed()),r.toggleShareScreen(!1,void 0).then((()=>{}))})),e.on("client-banned",(()=>__awaiter(this,void 0,void 0,(function*(){yield n.boomCore.leaveShare()})))),e.on("share-brtc-error",(t=>__awaiter(this,void 0,void 0,(function*(){if(4002===t.getCode())try{info("brtc share client disconnected, reconnecting"),yield e.shareBrtcClient.leave("room_close"),reconnectBRTCShareWS(e).then((()=>__awaiter(this,void 0,void 0,(function*(){if(info("brtc share client reconnected, retry repub share stream"),yield sleep(1e3),e.shareScreenStream){const t=e.shareScreenStream.getAudioOn(),r=e.shareScreenStream.getVideoOn();e.shareBrtcClient.publish(e.shareScreenStream),e.createAndPubBloudShareStream(t,r)}})))).catch((e=>{throw new Error("共享屏幕重新入会失败")}))}catch(e){r.toggleShareScreen(!1,void 0).then((()=>{})).catch((e=>{error$1("共享发生错误退会失败","","",[JSON.stringify(e)])}))}}))));let o=[];return o=o.concat(Object.values(require$$0.BloudEvents)),o=o.concat(Object.values(require$$0.BrtcEvents)),o=o.concat(Object.values(require$$0.CustomEvents)),o.forEach((e=>{s[e]=new BehaviorSubject(null)})),o.forEach((o=>{switch(o){case require$$0.BrtcEvents.STREAM_PUBLISHED:e.on(require$$0.BrtcEvents.STREAM_PUBLISHED,(e=>{eventQueue.addQueue(handleStreamPublished.bind(null,e,r,n,s),require$$0.BrtcEvents.STREAM_PUBLISHED)}));break;case require$$0.BrtcEvents.BRTC_SYNC_ROOM_COMPLETED:e.on(require$$0.BrtcEvents.BRTC_SYNC_ROOM_COMPLETED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(n.handleResetOtherStreamStatus.bind(n),require$$0.BrtcEvents.BRTC_SYNC_ROOM_COMPLETED)}))));break;case require$$0.CustomEvents.BRTC_SHARE_SYNC_ROOM_COMPLETED:e.on(require$$0.CustomEvents.BRTC_SHARE_SYNC_ROOM_COMPLETED,(()=>{info("brtc share client sync completed, retry publish share stream"),eventQueue.addQueue(handleShareStreamFailed.bind(null,n,r),require$$0.CustomEvents.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));break;case require$$0.BrtcEvents.BRTC_ROOM_ROCONNECTING:e.on(require$$0.BrtcEvents.BRTC_ROOM_ROCONNECTING,(e=>{eventQueue.addQueue(handleBrtcRoomReconnecting.bind(null,e,n,s),require$$0.BrtcEvents.BRTC_ROOM_ROCONNECTING)}));break;case require$$0.BrtcEvents.BRTC_ROOM_RECONNECTED:e.on(require$$0.BrtcEvents.BRTC_ROOM_RECONNECTED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBrtcRoomReconnected.bind(null,e,n,s),require$$0.BrtcEvents.BRTC_ROOM_RECONNECTED)}))));break;case require$$0.BrtcEvents.CLIENT_BANNED:e.on(require$$0.BrtcEvents.CLIENT_BANNED,(e=>{info("brtc client banned"),handleUserRejoined(s,e)}));break;case require$$0.BrtcEvents.ERROR:e.on(require$$0.BrtcEvents.ERROR,(t=>__awaiter(this,void 0,void 0,(function*(){n.netConnecting?eventQueue.addQueue(handleBRTCRoomError.bind(null,t,n,e,r,s),require$$0.BrtcEvents.ERROR):NETWORK_ERROR_QUEUE.add(handleBRTCRoomError.bind(null,t,n,e,r,s))}))));break;case require$$0.BloudEvents.SYNC_FAILED:e.on(require$$0.BloudEvents.SYNC_FAILED,(e=>{error$1("bloud sync failed, leave room"),s[require$$0.BloudEvents.TIMEOUT].next(e)}));break;case require$$0.BloudEvents.ROOM_CONNECTED:e.on(require$$0.BloudEvents.ROOM_CONNECTED,(e=>__awaiter(this,void 0,void 0,(function*(){return handleRoomConnected(e,n,t,s)}))));break;case require$$0.CustomEvents.JOIN_READY:e.on(require$$0.CustomEvents.JOIN_READY,(()=>handleInitJoinRoomUsers(n)));break;case require$$0.BloudEvents.PARTICIPANT_JOINED:e.on(require$$0.BloudEvents.PARTICIPANT_JOINED,(o=>__awaiter(this,void 0,void 0,(function*(){n.isInWaitRoom||eventQueue.addQueue(handleParticipantJoin.bind(null,o,t,r,e,i,s),require$$0.BloudEvents.PARTICIPANT_JOINED)}))));break;case require$$0.BloudEvents.PARTICIPANT_LEFT:e.on(require$$0.BloudEvents.PARTICIPANT_LEFT,(o=>{n.isInWaitRoom||eventQueue.addQueue(handleParticipantLeft.bind(null,o,t,n,s,r,e,i),require$$0.BloudEvents.PARTICIPANT_LEFT)}));break;case require$$0.BloudEvents.LEAVE_USERS:e.on(require$$0.BloudEvents.LEAVE_USERS,(o=>eventQueue.addQueue(handleLeaveUsers.bind(null,o,t,n,s,r,e,i),require$$0.BloudEvents.LEAVE_USERS)));break;case require$$0.BloudEvents.CHANGE_MASTER:e.on(require$$0.BloudEvents.CHANGE_MASTER,(e=>{eventQueue.addQueue(handleChangeMaster.bind(null,e,t,n,s,r),require$$0.BloudEvents.CHANGE_MASTER)}));break;case require$$0.BloudEvents.SEND_MESSAGE:e.on(require$$0.BloudEvents.SEND_MESSAGE,(e=>{eventQueue.addQueue(handleSendMessage.bind(null,e,t,i,s),require$$0.BloudEvents.SEND_MESSAGE)}));break;case require$$0.BloudEvents.CUSTOM_MESSAGE:e.on(require$$0.BloudEvents.CUSTOM_MESSAGE,(e=>{eventQueue.addQueue(handleCustomMessage.bind(null,e,n,s),require$$0.BloudEvents.CUSTOM_MESSAGE)}));break;case require$$0.BloudEvents.EVICTED:e.on(require$$0.BloudEvents.EVICTED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleEvict.bind(null,e,t,r,n,s),require$$0.BloudEvents.EVICTED)}))));break;case require$$0.BloudEvents.UPDATE_USER:e.on(require$$0.BloudEvents.UPDATE_USER,(e=>{eventQueue.addQueue(handleUpdateUser.bind(null,e,t,n,r,s),require$$0.BloudEvents.UPDATE_USER)}));break;case require$$0.BloudEvents.UPDATE_STATS:e.on(require$$0.BloudEvents.UPDATE_STATS,(e=>{eventQueue.addQueue(handleRoomUpdated.bind(null,e,n),require$$0.BloudEvents.UPDATE_STATS)}));break;case require$$0.BloudEvents.UPDATE_CUSTOM_STATS:e.on(require$$0.BloudEvents.UPDATE_CUSTOM_STATS,(e=>{eventQueue.addQueue(handleCustomStats.bind(null,e,n,s),require$$0.BloudEvents.UPDATE_CUSTOM_STATS)}));break;case require$$0.BloudEvents.TIMEOUT:e.on(require$$0.BloudEvents.TIMEOUT,(t=>{eventQueue.addQueue(handleBloudError.bind(null,n,e,r,t,s),require$$0.BloudEvents.TIMEOUT)}));break;case require$$0.BloudEvents.USER_REJOINED:e.on(require$$0.BloudEvents.USER_REJOINED,(e=>{info("bloud user rejoined"),handleUserRejoined(s,e)}));break;case require$$0.BloudEvents.RECONNECTING:e.on(require$$0.BloudEvents.RECONNECTING,(e=>{eventQueue.addQueue(handleBloudRoomReconnecting.bind(null,e,n,s),require$$0.BloudEvents.RECONNECTING)}));break;case require$$0.BloudEvents.RECONNECTED:e.on(require$$0.BloudEvents.RECONNECTED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomReconnected.bind(null,e,n,s),require$$0.BloudEvents.RECONNECTED)}))));break;case require$$0.BloudEvents.ROOM_SYNCED:e.on(require$$0.BloudEvents.ROOM_SYNCED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomSync.bind(null,e,t,n,r,s),require$$0.BloudEvents.ROOM_SYNCED)}))));break;case require$$0.BloudEvents.STREAM_PUBLISHED:e.on(require$$0.BloudEvents.STREAM_PUBLISHED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPublished.bind(null,e,r,s),require$$0.BloudEvents.STREAM_PUBLISHED)}))));break;case require$$0.BloudEvents.STREAM_REMOVED:e.on(require$$0.BloudEvents.STREAM_REMOVED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUnPublished.bind(null,e,r,s),require$$0.BloudEvents.STREAM_REMOVED)}))));break;case require$$0.BloudEvents.UPDATE_STREAM:e.on(require$$0.BloudEvents.UPDATE_STREAM,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUpdated.bind(null,e,r,s),require$$0.BloudEvents.UPDATE_STREAM)}))));case require$$0.BloudEvents.STREAM_UPDATE:e.on(require$$0.BloudEvents.STREAM_UPDATE,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPubAUpdate.bind(null,e,r),require$$0.BloudEvents.STREAM_UPDATE)}))));break;case require$$0.BloudEvents.MOVE_USER_ROOM:e.on(require$$0.BloudEvents.MOVE_USER_ROOM,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleMoveUserRoom.bind(null,n,t,e,s),require$$0.BloudEvents.MOVE_USER_ROOM)}))));break;default:e.on(o,(e=>s[o].next(e)))}})),s}!function(e){e.INIT="init",e.VIDEO_FORCE_CHANGE="video-force-change",e.AUDIO_FORCE_CHANGE="audio-force-change"}(MessageType||(MessageType={}));class BMRoomVM{constructor(e,t,r){this.room=null,this.tipQueueObj={},this.roomInfo=r,this.userVM=t,this.boomCore=e,this.giveLikeList=[],this.giveLikeListWatcher=new Subject}initWithRoom(e){this.room=e}evictUser(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!e)return Promise.reject(require$$0.BmEvictUserError("未传递用户id"));if(!this.userVM.checkLocalHasMaster())return Promise.reject(require$$0.BmEvictUserError("只有主持人权限才能踢出用户"));if(this.userVM.checkIsMaster(e))return Promise.reject(require$$0.BmEvictUserError("主持人不能被踢出"));try{yield this.boomCore.evictUser(e,t)}catch(e){return Promise.reject(require$$0.BmEvictUserError(`踢出用户失败${JSON.stringify(e)}`))}}))}updateUser(e,t){return __awaiter(this,void 0,void 0,(function*(){return e?t?void(yield this.boomCore.updateUser(e,{customInfo:t}).catch((e=>Promise.reject(require$$0.BmUpdateUserError(`boomCore updateUser出错 ${JSON.stringify(e)}`))))):Promise.reject(require$$0.BmUpdateUserError("info为空,请写入要更新的信息")):Promise.reject(require$$0.BmUpdateUserError("未传递目标用户id"))}))}changeMaster(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(!e)return Promise.reject(require$$0.BmChangeMasterError("未传递主持人id"));if(!this.userVM.checkLocalHasMaster()&&!(null===(r=this.userVM.getUser(e))||void 0===r?void 0:r.isCreate))return console.error("该用户没有管理员权限, 无法改变主持人",LOGGER_TAG_CLIENT,e),Promise.reject(require$$0.BmChangeMasterError("您没有管理员权限, 无法改变主持人"));try{yield this.boomCore.changeMaster(e,t)}catch(e){return Promise.reject(require$$0.BmChangeMasterError(`boomCore changeMaster error ${e}`))}}))}updateManager(e,t,r=!0){return __awaiter(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()?this.userVM.updateManager(e,t,r):(console.error("该用户没有管理员权限, 无法改变联席主持人",LOGGER_TAG_CLIENT,e),Promise.reject(require$$0.BmUpdateManagerError("该用户没有管理员权限, 无法改变主持人"))):Promise.reject(require$$0.BmUpdateManagerError("未传递联席主持人id"))}))}changeNickName(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={nickname:t};yield this.updateUser(e,r)}))}sendMessageWithMaster(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!this.userVM.checkLocalHasMaster())return Promise.reject(require$$0.BmSetRemoteAudioEnable("您不是主持人,没有该权限"));if(t){if(!this.userVM.getUser(t))return Promise.reject(require$$0.BmSetRemoteAudioEnable(`uid: ${t} 未找到用户`))}try{yield this.boomCore.customMessage(JSON.stringify(e),t)}catch(e){return Promise.reject(e)}}))}setRemoteAudioEnable(e,t,r){return __awaiter(this,void 0,void 0,(function*(){let i=e?"enabled":"disabled";"enabled"==i&&r&&(i="checkUserAudio");let n={domain:"room-control",method:"audio-force-change",params:{status:i,isNotCancelRootReport:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(n,t).catch((e=>Promise.reject(require$$0.BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}setRemoteVideoEnable(e,t){return __awaiter(this,void 0,void 0,(function*(){let r={domain:"room-control",method:"video-force-change",params:{status:e?"enabled":"disabled",fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(require$$0.BmSetRemoteVideoEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}closeRemoteShare(e){return __awaiter(this,void 0,void 0,(function*(){let t={domain:"room-control",method:"close-remote-share",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(require$$0.BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}tipUser(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){let n={domain:"room-control",method:"tip-user",params:{fromUserId:this.boomCore.getLocalParticipant().getID(),message:t,richMsg:r}};i?this.tipQueueObj[e]=setTimeout((()=>{this.sendMessageWithMaster(n,e)}),60*(i.minutes||0)*1e3+1e3*(i.seconds||0)):this.sendMessageWithMaster(n,e).catch((e=>Promise.reject(require$$0.BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${JSON.stringify(e)}`))))}))}raiseHands(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){const i=null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().getID();let n={};"raiseHand"===e?(n.raiseHand=t,n.raiseHandTime=Math.floor((new Date).getTime()/1e3)):n["audio"===e?"raiseHandsAudio":"raiseHandsVideo"]=t,yield this.updateUser(i,n)}))}handleRaiseHands(e,t,r){var i,n,s;return __awaiter(this,void 0,void 0,(function*(){let o={domain:"user-control",method:"raise-hands",params:{raiseHandsType:e,raiseHands:t}};try{if(r)yield this.boomCore.customMessage(JSON.stringify(o),r);else{const t=null===(i=this.room)||void 0===i?void 0:i.roomInfo.raiseHandsWatcher.getValue(),r=null===(n=this.room)||void 0===n?void 0:n.roomInfo.raiseVideoHandsWatcher.getValue(),a=null===(s=this.room)||void 0===s?void 0:s.roomInfo.raiseSimpleHandsWatcher.getValue();0===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})),null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),1===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),2===e&&(null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),3===e&&(null==a||a.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})))}}catch(e){return Promise.reject(new BoomError(LOCAL_ERROR,"boomCore.sendMessage发生错误"))}}))}updateCustomStats(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){yield this.boomCore.updateCustomStats(e,t).catch((t=>Promise.reject(require$$0.updateCustomStatsError(`${JSON.stringify(e)} - ${JSON.stringify(t)}`))))}))}sendChatNotice(e,t,r){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatNotice:e,chatNoticeRich:t,showTipNotice:r}).catch((e=>e))}))}giveLikeEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({giveLikeEnable:e}).catch((e=>e))}))}changeAutoMute(e){return __awaiter(this,void 0,void 0,(function*(){return this.updateCustomStats({autoMute:e})}))}allUserReceiveJoinLeaveMessages(e){return __awaiter(this,void 0,void 0,(function*(){return this.updateCustomStats({allUserReceiveJoinLeaveMessages:e})}))}userJoinMasterVoice(e){return __awaiter(this,void 0,void 0,(function*(){return this.updateCustomStats({userJoinMasterVoice:e})}))}userGiveLike(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){let i=(new Date).getTime(),n={domain:"room-control",method:"give-like",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:i,nickname:this.userVM.localUser.nickName,type:e||1}}},s=this.userVM.getLocalUser();try{yield this.boomCore.customMessage(JSON.stringify(n),void 0),this.giveLikeList.push({userId:null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant().userId,nickName:null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().nickName,time:(new Date).getTime(),type:e}),this.giveLikeListWatcher.next(this.giveLikeList)}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==s?void 0:s.userId),new BoomError(CLIENT_BANNED,"用户点赞==>sendMessage出错")}}))}chatEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatEnable:e}).catch((e=>e))}))}joinAudioEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinAudioEnable:e}).catch((e=>e))}))}joinVideoEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinVideoEnable:e}).catch((e=>e))}))}userListEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({userListEnable:e}).catch((e=>e))}))}audioEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({audioEnable:e}).catch((e=>e))}))}videoEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({videoEnable:e}).catch((e=>e))}))}modifyNameEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({modifyNameEnable:e}).catch((e=>e))}))}backgroundAIEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({backgroundAIEnable:e}).catch((e=>e))}))}forceOpenUserCamera(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserCamera:e}).catch((e=>e))}))}forceOpenUserMic(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserMic:e}).catch((e=>e))}))}joinCueVoice(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCueVoice:e}).catch((e=>e))}))}recordEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({recordEnable:e}).catch((e=>e))}))}raiseHandEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({raiseHandEnable:e}).catch((e=>e))}))}joinMicrophoneDisable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinMicrophoneDisable:e}).catch((e=>e))}))}joinCameraDisable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCameraDisable:e}).catch((e=>e))}))}changeFileUpdateModelPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateModel:e}).catch((e=>e))}))}changeFileUpdateLookPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateLook:e}).catch((e=>e))}))}changeFileUpdateDownPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateDown:e}).catch((e=>e))}))}changeFileUpdateEditPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateEdit:e}).catch((e=>e))}))}changeScreenShareModelPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({screenShareModel:e}).catch((e=>e))}))}changeOnlyOnePersonSharePermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({onlyOnePersonShare:e}).catch((e=>e))}))}setForceOnUser(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOn:{user:e}}).catch((e=>e))}))}updateHostLayout(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){if(this.userVM.checkLocalHasMaster())return this.updateCustomStats({from:{fromTag:"masterId"},hostLayout:e},t);info("您不是主持人,没有该上报权限",LOGGER_TAG_CLIENT)}))}checkDevices(e){return __awaiter(this,void 0,void 0,(function*(){const t={domain:"user-control",method:"check-devices",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(require$$0.BmCheckDeviceError(`检测对方设备send-message发生错误: ${e}`))))}))}resp2CheckDevices(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-check-devices",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};if(!t)return Promise.reject(require$$0.BmCheckDeviceError(`响应设备检测: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(require$$0.BmCheckDeviceError(`响应响应设备检测send-message发生错误 ${e}`))}}))}changeRemoteVideoProfile(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-video-profile",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(require$$0.BmChangeVideoProfileError(`调节对方的视频分辨率send-message发生错误: ${e}`))))}))}resp2ChangeRemoteVideoProfile(e,t,r){return __awaiter(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"resp-to-change-video-profile",params:{status:e,profile:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(require$$0.BmChangeVideoProfileError(`响应调节视频分辨率: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(i),t)}catch(e){return Promise.reject(require$$0.BmChangeVideoProfileError(`响应调节视频分辨率send-message发生错误 ${e}`))}}))}changeRemoteAudioProfile(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-audio-profile",params:{microphoneDevice:e.microphoneDevice,speakerDevice:e.speakerDevice,echoCancellation:e.echoCancellation,noiseSuppression:e.noiseSuppression,autoGainControl:e.autoGainControl,speakerVolume:e.speakerVolume,microVolume:e.microVolume,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(require$$0.BmChangeAudioProfileError(`调节音频send-message发生错误 ${JSON.stringify(e)}`))))}))}resp2ChangeRemoteAudioProfile(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-change-audio-profile",params:{status:e,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(require$$0.BmChangeAudioProfileError(`响应调节音频: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(require$$0.BmChangeAudioProfileError(`响应调节音频send-message发生错误 ${e}`))}}))}}class BMChatVM{constructor(e,t,r){this.messageList=[],this.hasDangerMessageWatcher=new Subject,this.notificationMessageList=debounce((()=>{this.messageListWatcher.next(this.messageList)}),500),this.boomCore=e,this.userVM=t,this.bmRoom=r,this.messageListWatcher=new BehaviorSubject(this.messageList)}sendMessage(e,t,r){return __awaiter(this,void 0,void 0,(function*(){let i=e.replace(/(^\s*)|(\s*$)/g,""),n=(new Date).getTime(),s={domain:"room-control",method:"send-talk",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:n,nickname:this.userVM.localUser.nickName},status:i}},o=this.userVM.getLocalUser();try{let e,a=!1,c=r;c||(yield this.boomCore.sendMessage(JSON.stringify(s),t).then((t=>{e=t.seq})).catch((e=>{warn("sendmessage 出错","",null==o?void 0:o.userId,[e]),e&&39===e.code&&(a=!0,this.hasDangerMessageWatcher.next(!0))})));const u=new BMMessageInfo({userId:null==o?void 0:o.userId,message:i,isLocal:null==o?void 0:o.isLocal,avatar:null==o?void 0:o.avatar,nickName:null==o?void 0:o.nickName,sendTime:n,to:t,isDanger:a,seq:e,failed:c});return this.addMessage(u,!1),c?Promise.reject(u):Promise.resolve()}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==o?void 0:o.userId),new BoomError(CLIENT_BANNED,"发送聊天消息==>sendMessage出错")}}))}addMessage(e,t){if(!t||this.bmRoom.participantNotice){if(0==this.messageList.length||e.timeStamp-this.messageList[this.messageList.length-1].timeStamp>=notGetTalkInterval){const e=new BMMessageInfo({isMeetingNotice:!0,message:""});this.messageList.push(e)}this.messageList.push(e),this.notificationMessageList()}}updateMessageListWatcher(e){this.messageList=e,this.messageListWatcher.next(this.messageList)}getHistoryMessage(){return __awaiter(this,void 0,void 0,(function*(){const e=yield this.boomCore.getMessages(0,this.boomCore.getMsgSeq());let t=[];return e.items.forEach((e=>{if(e.private||e.to)return!1;if(0==e.msg.length||-1==e.msg.indexOf("{"))return!1;const r=JSON.parse(e.msg);if("send-talk"!=r.method)return!1;const i=e.seq;let n=r.params,s=n.stream.user?n.stream.user:e.userId;n.stream.nickname,n.status,(new Date).getTime();const o=new BMMessageInfo({userId:s,message:n.status,nickName:n.stream.nickname,isLocal:s==this.userVM.localUser.userId,avatar:n.stream.avatar,sendTime:n.stream.sendTime,seq:i});t.push(o)})),Promise.resolve(t)}))}}class BMSpeaker{constructor(e,t){this.user=e,this.stream=t}getID(){return this.stream.getStreamId()}getUser(){return this.user}}function getMasterSort(e,t){return 16|~~e<<1|~~t}function getLocalSort(e,t){return 12|~~e<<1|~~t}function getManagerSort(e,t){return 8|~~e<<1|~~t}function getGuestSort(e,t){return 4|~~e<<1|~~t}!function(e){e[e.NO_CONTAINER=0]="NO_CONTAINER",e[e.NO_PLAYING=1]="NO_PLAYING",e[e.PLAYING=2]="PLAYING"}(PlayerState||(PlayerState={}));const namespace$1=`.streammodel${Math.random()}`;class BMStreamModel{constructor(e,t){this.streamType=STREAM_TYPE.OTHER,this.pullFailedNum=0,this._video_enable=!1,this._audio_enable=!1,this.videoEnableWatcher=new BehaviorSubject(this._video_enable),this.audioEnableWatcher=new BehaviorSubject(this._audio_enable),this.streamUpdateWatcher=new Subject,this.isSubScribedWatcher=new Subject,this.playStateChangeWatcher=new Subject,this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.audioLevelWatcher=new Subject,this.isCurrentDisplay=!1,this.isDisplay=!1,this.isDisplayObserve=new Subject,this.isInBig=!1,this.isInBigObserve=new Subject,this._hasPulled=!1,this.playerId="",this.shouldPull=!1,this._pulledStreamType="small",this.pulledStreamGoal="small",this.bigPlayerId="",this.isPlayingBig=!1,this.muted=!1,this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount=0,this.sortNum=-1,this.handleDisplayChange=e=>{var t;this.isDisplay!==e&&(this.isDisplay=e,null===(t=this.stream)||void 0===t||t.stop(),this.isDisplay||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.pulledStreamType="small"),this.sendMessage2Room())},this.onPlayerStateChange=e=>{var t,r;"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&(info("播放失败, 需要调用 resume 方法"),this.playStateChangeWatcher.next(this)),"PAUSED"!==e.state&&"pause"!==e.reason||(this.player&&(null===(t=this.player)||void 0===t||t.resume()),null===(r=this.stream)||void 0===r||r.resume())},this.handleStreamConnectError=()=>{info("流出现的connect-error userId","",this.userId,["streamId ==>",this.streamId,"nickname =>",this.nickname,"isLocal => ",this.isLocal]),this.isLocal?BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!0}):BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!1})},this.bindElement=e=>{this.playerId=e,(this.isLocal||this.stream&&this.stream.isSubscribed())&&this.sendMessage2Room()},this.bindBigElement=e=>{this.bigPlayerId=e,(this.isLocal||this.stream&&this.stream.isSubscribed())&&this.sendMessage2Room()},this.sendMessage2Room=debounce((()=>{BoomEmitter.emitter.emit(RECEIVE_SUBSCRIBE_MESSAGE,{stream:this})}),100),this.emitBindElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_ELEMENT,{stream:this})}),50),this.emitBindBigElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_BIG_ELEMENT,{stream:this})}),50),this.currentIsPlaying=e=>{const t=document.getElementById(e);if(!t)return PlayerState.NO_CONTAINER;let r,i,n=0;const s=Array.from(t.children);return r=s.length>0,i=s.length,s.forEach((e=>{0===e.children.length&&(n+=1,e.style.display="none",t.removeChild(e))})),r&&i>n?PlayerState.PLAYING:PlayerState.NO_PLAYING},this.play=()=>__awaiter(this,void 0,void 0,(function*(){var e;const t=this.stream;if(t)if(this.isDisplay&&this.videoEnable){const e=this.currentIsPlaying(this.playerId);if(e===PlayerState.NO_CONTAINER)warn("找不到播放器容器","stream play",this.userId,["流 id =>",this.streamId,"nickname =>",this.nickname,"playerId =>",this.playerId]),this.playerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"small"});else if(e===PlayerState.NO_PLAYING)try{yield t.play(this.playerId,{backgroundColor:"#202020",fit:"contain",audio:!1}),info("远端流播放结束",this.userId,this.streamId,[this.nickname]),this.checkSmallVideo()}catch(e){t.stop(),setTimeout((()=>{error$1("播放小流失败, 尝试重新播放","播放",this.userId,[this.streamId,this.stream,"error => ",JSON.stringify(e)]),this.play()}),2e3)}}else try{null===(e=this.stream)||void 0===e||e.stop()}catch(e){}})),this.playInBig=()=>__awaiter(this,void 0,void 0,(function*(){var e;const t=this.stream;if(t){const r=this.currentIsPlaying(this.bigPlayerId);this.isInBig&&this.videoEnable&&this.bigPlayerId?r===PlayerState.NO_CONTAINER?(warn("找不到 bigPlayerId","大流播放",this.userId,["流 id =>",this.streamId]),this.bigPlayerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"big"})):r===PlayerState.NO_PLAYING&&(this.initBigPlayer(),this.player&&(yield this.player.play(t),this.isPlayingBig=!0,this.checkBigVideo()),info("远端流大流播放结束",this.userId,this.streamId,[this.nickname])):(null===(e=this.player)||void 0===e||e.destroy(),this.player=null,this.isPlayingBig=!1)}})),this.collectAudioLevel=()=>{this.stream?(this.stream.off("audio-level"+namespace$1,this.handleAudioLevel),this.stream.on("audio-level"+namespace$1,this.handleAudioLevel)):warn("collection audio level but not have brtc stream")},this.handleAudioLevel=e=>{this.audioLevelWatcher.next(e)},this.checkBigVideo=debounce((()=>{if(this.videoEnable&&this.stream){const e=`video_${this.stream.getStreamId()}_big`;if(!this.isShare&&this.isDisplay&&this.playerId){const t=!!document.getElementById(e);if(this.isInBig){if(t)return void this.checkVideoDecodeFrame(e);error$1("stream is playing in big, but no video element, replay now"),this.playInBig()}}this.isShare&&this.isInBig&&this.bigPlayerId&&this.checkVideoDecodeFrame(e)}}),2e3),this.checkStreamIsPlaying=debounce((()=>{if(this.isDisplay&&this.videoEnable){if(!this.stream)return;if(!document.getElementById(this.playerId))return;this.currentIsPlaying(this.playerId)===PlayerState.NO_PLAYING||(error$1(`${this.userId} - ${this.nickname}: current is ${this.isDisplay}, but there is no player, try play again`),this.play())}}),1e3),this.user=e,this.updateUser(e),this._stream=t,this.isDisplayObserve.subscribe((e=>{this.handleDisplayChange(e)})),this.isInBigObserve.subscribe((e=>{this.handleIsInBig(e)})),this.updateSortNum(!1)}get hasPulled(){return this._hasPulled}set hasPulled(e){this._hasPulled=e}get pulledStreamType(){return this._pulledStreamType}set pulledStreamType(e){this._pulledStreamType=e}get uuid(){return this.isShare?`${this.userId}_share`:this.userId}get isAudience(){return this.user.isAudience}get canShow(){return!this.isAudience||(this.audioEnable||this.videoEnable)}changeMute(e){this.muted!==e&&(this.muted=e,this.handleSpeakerChange())}handleSpeakerChange(){var e,t;this.isLocal||(this.muted?null===(e=this.stream)||void 0===e||e.setAudioVolume(0):null===(t=this.stream)||void 0===t||t.setAudioVolume(1))}get isToupingma(){return this.user.isToupingma}get isMixer(){return this.user.isMixer}get isSignal(){return this.user.isSignal}genReceiveSubMsg(){let e=null;return e=this.isDisplay?{audio:!0,video:!0,streamType:"small"}:{audio:!0,video:!1,streamType:"small"},e}handleIsInBig(e){this.isInBig!==e&&(this.isInBig=e,info("isInBig change","",this.userId,["streamId =>",this.streamId,"isInBig => ",e]),this.isInBig?this.pulledStreamGoal="big":this.pulledStreamGoal="small",this.sendMessage2Room(),this.isShare&&(this.isInBig||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0)))}setVideoEnable(e){this._video_enable!==e&&(this._video_enable=e,this.videoEnableWatcher.next(e))}setAudioEnable(e){this._audio_enable!==e&&(this._audio_enable=e,this.audioEnableWatcher.next(e))}updateStream(e,t=!0,r){if(this._stream&&this._stream.off(namespace$1),this._stream=e,e){const i=e.getVideoOn(),n=e.getAudioOn();info("更新用户的流","updateStream",null==e?void 0:e.getUserId(),["nickname =>",this.nickname,"audioOn",n,"videoOn",i,"streamId",e.getStreamId()]),n&&(this.isShare||r.addToDetector(new BMSpeaker(this.user,e)),this.collectAudioLevel()),e.on("player-state-changed"+namespace$1,this.onPlayerStateChange),e.on("connect-error"+namespace$1,this.handleStreamConnectError),e.on("stream-connection-error"+namespace$1,this.handleStreamConnectError),t&&this.sendMessage2Room()}else this.hasPulled=!1,this.pulledStreamType="small",this.streamType=STREAM_TYPE.OTHER}updateBloudStream(e,t,r=!1){var i,n,s,o;let a=!1,c=!1;if(e){if(this.bloudStream={audio:e.audio,video:e.video,isScreen:e.isScreen},e.customInfo&&(this.bloudStream.customInfo&&(null===(i=this.bloudStream.customInfo)||void 0===i?void 0:i.volume)===e.customInfo.volume||Number.isNaN(e.customInfo.volume)||this.setRemoteAudioLevel(e.customInfo.volume),this.bloudStream.customInfo=e.customInfo),this.stream&&(this.bloudStream.audio?this.isShare||(t.addToDetector(new BMSpeaker(this.user,this.stream)),this.collectAudioLevel()):t.removeFromDetector(this.stream.getStreamId())),this.bloudStream.video!==this._video_enable&&(a=!0),this.bloudStream.audio!=this._audio_enable&&(c=!0),this.setVideoEnable(this.bloudStream.video),this.setAudioEnable(this.bloudStream.audio),r){try{null===(n=this.stream)||void 0===n||n.destroy()}catch(e){}this.stream&&(null===(s=t.room.audioPlayer)||void 0===s||s.removeStream(this.stream)),this.updateStream(void 0,!1,t),this._stream=void 0}c&&!this.audioEnable&&this.stream&&(null===(o=t.room.audioPlayer)||void 0===o||o.removeStream(this.stream)),(this.bloudStream.audio||this.bloudStream&&this.isDisplay)&&(!this.stream||r?BoomEmitter.emitter.emit(ADD_PULL_USER,{id:this.userId,isWeb:this.isWeb,isScreen:this.isShare}):(this.isLocal||this.hasPulled&&this.stream.isSubscribed()||this.sendMessage2Room(),a&&this.sendMessage2Room(),!this.isLocal&&c&&this.audioEnable&&this.stream.isSubscribed()&&BoomEmitter.getInstance().emit(ADD_AUDIO_PLAY,{stream:this})))}else this.bloudStream=void 0,this.setVideoEnable(!1),this.setAudioEnable(!1),this.stream&&t.removeFromDetector(this.stream.getStreamId());this.updateSortNum(!0),this.streamUpdateWatcher.next(!0)}updateBloudCustomInfo(e){var t;this.bloudStream?(this.bloudStream.customInfo&&(null===(t=this.bloudStream.customInfo)||void 0===t?void 0:t.volume)===e.volume||Number.isNaN(e.volume)||this.setRemoteAudioLevel(e.volume),this.bloudStream.customInfo=e):error$1("updateBloudCustomInfo, but bloudStream is undefined","","",["userId =>",this.userId])}get streamId(){return this._stream?this._stream.getStreamId():this.userId}get bStreamId(){return this.isShare?`${this.userId}_screen`:this.userId}get userId(){return this.user.userId}get stream(){return this._stream}get isLocal(){return this.user.isLocal}get isShare(){var e,t,r;return this.stream?this.user.isWeb?null===(t=null===(e=this.stream)||void 0===e?void 0:e.getUserId().toString())||void 0===t?void 0:t.endsWith(STREAM_SUFFIX_SCREEN):!(!this.stream||!this.stream.getType||"assist"!==this.stream.getType()):!!(null===(r=this.bloudStream)||void 0===r?void 0:r.isScreen)}get isWeb(){return this.user.isWeb}get audioEnable(){return this._audio_enable}get videoEnable(){return this._video_enable}get brtcPlayerId(){return`player_${this.stream.getStreamId()}`}get selfPlayerId(){return`player_${this.stream.getStreamId()}_big_container`}get nickname(){var e;return this.user.isToupingma?`${this.user.nickName}(的投屏)`:(null===(e=this.streamId)||void 0===e?void 0:e.includes(STREAM_SUFFIX_SCREEN))?`${this.user.nickName}(的屏幕共享)`:this.user.nickName}get audioLevel(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.getAudioLevel())||0}getUser(){return this.user}setRemoteAudioLevel(e){if(this.isLocal)throw new Error("不能设置本地流的音量");BoomEmitter.emitter.emit(SET_VOLUME,{streamId:this.streamId,volume:e})}getStats(){var e;return null===(e=this._stream)||void 0===e?void 0:e.getStats()}initBigPlayer(){try{if(this.bigPlayerId){const e=document.querySelector(`#${this.bigPlayerId}`);if(!e)return void console.error("播放大流失败,找不到大流容器",this.userId,this.streamId,this.bigPlayerId);this.player&&this.player.destroy(),this.player=null,this.player=new dist$1.Player(e,{fit:"contain"}),this.player.on("player-state-changed",(e=>{var t;this.stream&&(info("big player state change","","",[JSON.stringify(e)]),"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&this.playStateChangeWatcher.next(this),"PAUSED"===e.state&&(null===(t=this.player)||void 0===t||t.resume()))}))}}catch(e){error$1("初始化大窗口的播放器失败",this.userId,this.streamId,e.message)}}stop(){var e;null===(e=this._stream)||void 0===e||e.stop()}destroy(){var e;null===(e=this._stream)||void 0===e||e.destroy()}isPlaying(){var e;return null===(e=this._stream)||void 0===e?void 0:e.isPlaying()}replay(){var e;return null===(e=this._stream)||void 0===e?void 0:e.replay()}resume(){var e,t;null===(e=this._stream)||void 0===e||e.resume(),null===(t=this.player)||void 0===t||t.resume()}hasAudio(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasAudio())||!1}hasVideo(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasVideo())||!1}updateUser(e){this.user=e;const t=this.user.userInfo.pos;t?t.includes("web")||t.includes("pc")?this.streamType=STREAM_TYPE.SUB_MAIN:t.includes("_toupingma")?this.streamType=STREAM_TYPE.SHARE:this.streamType=STREAM_TYPE.SINGLE:this.streamType=STREAM_TYPE.SINGLE}updateSortNum(e=!0){const t=this.getSortNum();this.setSortNum(t,e)}setSortNum(e,t){this.sortNum!==e&&(this.sortNum=e,t&&(BoomEmitter.emitter.emit(MODEL_SORT_NUM_CHANGE,null),this.user.updateSortNum(!0)))}getSortNum(){return this.user.isMaster?getMasterSort(this.audioEnable,this.videoEnable):this.user.isLocal?getLocalSort(this.audioEnable,this.videoEnable):this.user.isManager?getManagerSort(this.audioEnable,this.videoEnable):getGuestSort(this.audioEnable,this.videoEnable)}checkSmallVideo(){if(this.videoEnable&&this.stream&&!this.isShare){if(!!document.getElementById(this.playerId)){const e=`video_${this.stream.getStreamId()}`;if(!!document.getElementById(e))return void this.checkVideoDecodeFrame(e);error$1("stream is display, but no video element, should replay now"),this.play()}}}checkVideoDecodeFrame(e){const t=document.getElementById(e);if(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),!t)return info("黑帧检测没有播放容器",this.userId,"",["streamId =>",this.streamId,"isShare =>",this.isShare,"playerId =>",this.playerId,"bigPlayerId =>",this.bigPlayerId,"isDisplay => ",this.isDisplay,"isInbig =>",this.isInBig]),void(this.isShare&&this.isInBig&&this.bigPlayerId&&(warn("share stream has no video player, retry play"),this.playInBig()));this.checkVideoTimer=setTimeout((()=>{var r,i,n;const s=(null==t?void 0:t.getVideoPlaybackQuality)&&(null===(r=null==t?void 0:t.getVideoPlaybackQuality())||void 0===r?void 0:r.totalVideoFrames)||0;if(!t||t.getVideoPlaybackQuality){if(s>0)return clearTimeout(this.checkVideoTimer),void(this.checkFailedCount=0);if(this.checkCount>10){if(error$1("检测超过了十次,还没有视频流,需要重新拉取","黑帧检测",this.userId,["streamId =>",this.streamId,"nickname =>",this.nickname,"videoContainer => ",e]),this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount+=1,this.checkFailedCount<=3){this.hasPulled=!1,this.pulledStreamType="small",null===(i=this._stream)||void 0===i||i.off(namespace$1);try{null===(n=this._stream)||void 0===n||n.destroy()}catch(e){}this._stream=void 0,this.sendMessage2Room()}}else this.checkCount+=1,this.checkVideoDecodeFrame(e)}else this.checkVideoTimer&&clearTimeout(this.checkVideoTimer)}),200)}subscribeStream(){this.shouldPull=!0,BoomEmitter.emitter.emit(MANUAL_SUBSCRIPTION,{stream:this})}unSubscribeStream(){this.shouldPull=!1,BoomEmitter.emitter.emit(UNSUBSCRIBE_STREAM,{stream:this})}unAttach(e){var t,r,i,n;info("unattach stream play","",this.userId,["streamId =>",this.streamId,"nickname =>",this.nickname,"types =>",e]),"all"===e?(null===(t=this.stream)||void 0===t||t.stop(),null===(r=this.player)||void 0===r||r.destroy()):"big"===e?null===(i=this.player)||void 0===i||i.destroy():"small"===e&&(null===(n=this.stream)||void 0===n||n.stop())}}function getHTMLMediaStreamOptions(e){let t=null;const r=e.videoElement,i=r.offsetWidth,n=r.offsetHeight;if(r.captureStream?t=r.captureStream():r.mozCaptureStream&&(t=r.mozCaptureStream()),t){const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];return{video:!!e,audio:!!r,videoSource:e,audioSource:r,width:i,height:n}}return null}function getMediaStreamInfo(e,t){try{const r=e.getVideoTracks()[0],i=e.getAudioTracks()[0];return{video:!!r,audio:!!i,videoSource:r,audioSource:i,width:t.width,height:t.height}}catch(e){return console.log("获取共享音频参数有误",e),null}}function transShareScreen2User(e){return e.split("_")[0]}const namespace=`.streammuteevent${Math.random()}`;class BMStreamModelVM{constructor(){this.streamModels=new Map,this.streamModelsWatcher=new BehaviorSubject(BMStreamModelVM.filterStreamModels(this.sortStreamModels())),this.shareStreamModels=new Map,this.shareStreamModelsWatcher=new BehaviorSubject(Array.from(this.shareStreamModels.values())),this.localStreamErrorWatcher=new Subject,this.localModel=null,this.room=null,this.bloudStream=null,this.videoStream=null,this.audioStream=null,this.audioStats=!1,this.videoStats=!1,this.localIsShare=!1,this.isShareWatcher=new Subject,this._speaker_enable=!0,this.speakerEnableWatcher=new BehaviorSubject(this._speaker_enable),this.mixStreamModelWatcher=new BehaviorSubject(null),this.canvasTimer=null,this._isRecording=!1,this._slicingRecord=!1,this.isRecordingWatcher=new BehaviorSubject(this._isRecording),this._speaker=null,this._speakers=new Map,this.speakerWatcher=new BehaviorSubject(this._speaker),this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.localStreamConnectErrorWatcher=new Subject,this.localShareError=new Subject,this.shareBloudStateMap=new Map,this.updateModelSort=debounce((()=>{const e=this.sortStreamModels();this.streamModelsWatcher.next(BMStreamModelVM.filterStreamModels(e))}),200,{maxWait:500}),this.handleNoContainer=e=>{const{type:t,container:r,id:i}=e;let n;n="share"===t?this.shareStreamModels.get(i):this.streamModels.get(i),n&&("small"===r?this.noContainerWatcher.next(n):this.noBigContainerWatcher.next(n))},this.getHTMLMediaStream=getHTMLMediaStreamOptions,this.getMediaStream=getMediaStreamInfo,this.createCanvas(),setTimeout((()=>{this.canvasDisplay()}),100),BoomEmitter.emitter.on(MODEL_SORT_NUM_CHANGE,this.updateModelSort),BoomEmitter.emitter.on(NO_CONTAINER,this.handleNoContainer)}static filterStreamModels(e){return e.filter((e=>!e.isToupingma)).filter((e=>!ignoreUserId.some((t=>e.userId.includes(t))))).filter((e=>e.canShow))}initWithRoom(e){return this.room=e,this}setSpeakerEnable(e){var t;this._speaker_enable!==e&&(null===(t=this.room.audioPlayer)||void 0===t||t.mute(!e),this._speaker_enable=e,this.speakerEnableWatcher.next(e))}getStreamModels(){return Array.from(this.streamModels.values())}getStreamModelByUId(e){return this.streamModels.get(e)}getShareStreamModelByUId(e){return this.shareStreamModels.get(e)}getLocalStreamModel(){return this.localModel}createStreamModel(e,t){const r=new BMStreamModel(e,void 0);return t&&r.updateStream(t,!0,this),r.isShare?(e.addStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`,r),this.addShareStreamModel(r)):(e.addStream(e.userId,r),this.addStreamModel(r)),r}addStreamModel(e){e&&(e.isLocal?this.localModel||(this.localModel=e,this.streamModels.set(this.localModel.userId,this.localModel)):this.streamModels.set(e.userId,e))}addShareStreamModel(e){e&&(e.isLocal||(this.shareStreamModels.set(e.userId,e),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))))}removeStreamModel(e){if(!e)return;const t=e.getUser();this.streamModels.delete(e.userId),t.removeStream(e.userId)}removeShareStreamModelByUId(e){var t,r,i,n;const s=this.shareStreamModels.get(e);if(s){try{null===(t=s.stream)||void 0===t||t.stop(),null===(r=s.stream)||void 0===r||r.destroy()}catch(e){}s.audioEnable&&s.stream&&(null===(n=null===(i=this.room)||void 0===i?void 0:i.audioPlayer)||void 0===n||n.removeStream(s.stream)),this.removeShareStreamModel(s)}}removeShareStreamModel(e){if(!e)return;const t=e.getUser();this.shareStreamModels.delete(e.userId),t.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`),t.updateSortNum(!0),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}removeStreamModelByUId(e){var t,r,i;const n=this.getStreamModelByUId(e);if(n){if(n.stream){this.removeFromDetector(n.streamId);try{n.stream.stop(),n.stream.destroy()}catch(e){}}n.audioEnable&&(n.stream?null===(r=null===(t=this.room)||void 0===t?void 0:t.audioPlayer)||void 0===r||r.removeStream(n.stream):null===(i=this.room)||void 0===i||i.audioPlayer.removeStreamByUid(e)),this.removeStreamModel(n)}return n}remoteStreamPublished(e){const t=e.getStreamId(),r=e.getUserId().toString();let i,n=this.getStreamModelByUId(r);if(n||(i=transShareScreen2User(String(r)),n=this.getStreamModelByUId(i)),n){if(isShareStream(e)){let t;if(i&&(t=this.shareStreamModels.get(i)),t){if(t.isLocal)return;t.hasPulled=!1,t.pulledStreamType="small",t.updateStream(e,!0,this),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}else{const t=this.createStreamModel(n.getUser(),e),r=e.getVideoOn(),i=e.getAudioOn(),s=this.shareBloudStateMap.get(n.userId);s?t.updateBloudStream({audio:s.audio,video:s.video,isScreen:!0,customInfo:s.customInfo},this):t.updateBloudStream({audio:i,video:r,isScreen:!0},this),t.streamType=STREAM_TYPE.SHARE}}else n.hasPulled=!1,n.pulledStreamType="small",this.updateStreamModel(n,e);n.getUser().isMixer&&this.mixStreamModelWatcher.next(n),this.changeSingleStreamSpeaker(n).catch((e=>{error$1("设置单股流的扬声器的播放出现了问题","设置播放音量",null==n?void 0:n.userId)}))}else error$1("brtc有人推流了,但是找不到对应的streamModel, 找不到对应的用户","",r,["streamId => ",t,"types =>",e.getType&&e.getType()])}remoteStreamUnpublished(e){var t,r,i;let n;const s=e.getUserId().toString(),o=e.getStreamId();let a=!1;if(s.includes(STREAM_SUFFIX_SCREEN)){const e=transShareScreen2User(String(s));if(e==(null===(r=null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant())||void 0===r?void 0:r.userId))return info("本地用户取消共享屏幕","取消共享屏幕",s),void this.localModel.getUser().removeStream(s);n=this.getShareStreamModelByUId(e),a=!0}else o.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()?(n=this.getShareStreamModelByUId(s),a=!0):n=this.getStreamModelByUId(s);if(this.removeFromDetector(o),this.removeFromRecorder(e),!n)return void error$1("brtc有人取消推流 但是找不到对应的streamModel","取消推流",s,[o]);const c=null===(i=n.stream)||void 0===i?void 0:i.getStreamId();if(c===o)return n.hasPulled=!1,n.pulledStreamType="small",a||n.streamType===STREAM_TYPE.SHARE?(n.updateStream(void 0,!0,this),void this.removeShareStreamModel(n)):(n.updateStream(void 0,!0,this),n);error$1("当前取消推流的和当前绑定的不是同一股流","",s,["streamId =>",o,"streamModel.streamId",c])}sortStreamModels(){return sortStreamModels(Array.from(this.streamModels.values()))}updateStreamModel(e,t){e.updateStream(t,!0,this)}updateShareStreamModel(e,t){e.updateStream(t,!0,this)}setLocalVideoEnable(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(!(null===(r=this.room)||void 0===r?void 0:r.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地摄像头,不与响应");if(!this.room.mediaPermission.camera)return Promise.reject(require$$0.BMCameraNotAuthError());const i=this.getLocalStreamModel();if(info(`开关本地摄像头, 状态 => ${e}`,"本地用户",null==i?void 0:i.userId),i)if(e)if(null==i?void 0:i.stream){if(t)yield i.stream.replaceTrack(t).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}));else{if("CanvasCaptureMediaStreamTrack"===i.stream.getVideoTrack().constructor.name){const e=yield this.createVideoStream().catch((e=>Promise.reject(e)));yield i.stream.replaceTrack(e).then((()=>{info("replace video track success")})).catch((e=>(error$1("本地视频流更换视频流失败","","",JSON.stringify(e)),this.handleStreamUpdateFailed(),Promise.reject(require$$0.BMOpenCameraError()))))}}if(!(yield i.stream.unmuteVideo()))return error$1("brtc unmuteVideo失败"),this.handleStreamUpdateFailed(),Promise.reject(require$$0.BMOpenCameraError());info("brtc unmute video success"),yield this.bloudStream.setVideoEnabled(!0).then((()=>{i.updateStream(i.stream,!0,this),i.updateBloudStream({video:!0,audio:i.audioEnable,isScreen:!1},this),i.playInBig()})).catch((e=>{error$1("bloud unmuteVideo失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!1,!0,i,t).catch((e=>{var t,r,i,n,s;return error$1("开启本地摄像头失败","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));else{i.stream&&(yield this.muteOrUnpublishStream("video",!0,i).catch((e=>(error$1("关闭本地摄像头失败","","",[e]),Promise.reject(require$$0.BmSetLocalVideoEnable(e))))))}}))}handleStreamUpdateFailed(){return __awaiter(this,void 0,void 0,(function*(){error$1("brtc unmute stream failed, now unpublish"),yield this.unpublishStream()}))}setLocalAudioEnable(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(!(null===(t=this.room)||void 0===t?void 0:t.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地麦克风,不与响应");if(!this.room.mediaPermission.microphone)return Promise.reject(require$$0.BMMicNotAuthError());const r=this.getLocalStreamModel();if(info(`开关本地麦克风, 状态 => ${e}`,"本地用户",null==r?void 0:r.userId),r)if(e){if(null==r?void 0:r.stream){const e=yield r.stream.unmuteAudio();if(info(`unmute local stream audio res : ${e}`),!e)return error$1("brtc unmuteAudio失败","本地用户",""),yield this.handleStreamUpdateFailed(),Promise.reject(require$$0.BMOpenMicroError());info("unmute audio success"),yield this.bloudStream.setAudioEnabled(!0).then((()=>{info("bloud stream set audio enable"),r.updateStream(r.stream,!1,this),r.updateBloudStream({audio:!0,video:r.videoEnable,isScreen:!1},this)})).catch((e=>{error$1("bloud unmuteAudio失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!0,!1,r).catch((e=>{var t,r,i,n,s;return error$1("开启本地麦克风失败","","",[e]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));(null==r?void 0:r.stream)&&this.addToRecorder(null==r?void 0:r.stream)}else{const e=r.stream;if(e){this.removeFromRecorder(e),this.removeFromDetector(e.getStreamId());try{yield this.muteOrUnpublishStream("audio",!0,r)}catch(e){return error$1("关闭本地麦克风失败","","",[JSON.stringify(e)]),Promise.reject(require$$0.BmSetLocalAudioEnable(e))}}}}))}joinWithAudioAndAudio(e,t){return __awaiter(this,void 0,void 0,(function*(){info("join with audio and video","join publish","",[e,t]);const r=this.getLocalStreamModel();r&&(yield this.createStreamAndPublish(e,t,r).catch((e=>{var t,r,i,n,s;return error$1("join create and publish failed","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)})))}))}changeSpeaker(e,t=!1){var r,i;return __awaiter(this,void 0,void 0,(function*(){if(info("change speaker","","",[JSON.stringify(e)]),!e.deviceId)throw new require$$0.BoomError(LOCAL_ERROR,"切换扬声器失败!,原因: 选择的设备没有deviceId"+(null==e?void 0:e.name));try{this.room.setSelectSpeakerDevice(e),null===(i=null===(r=this.room)||void 0===r?void 0:r.audioPlayer)||void 0===i||i.setDevice(e.deviceId,t)}catch(e){throw error$1("切换扬声器失败","","",["error",null==e?void 0:e.message,JSON.stringify(e)]),new require$$0.BoomError(LOCAL_ERROR,"切换扬声器失败")}}))}changeSingleStreamSpeaker(e){return __awaiter(this,void 0,void 0,(function*(){const t=this.room.selectAudioOutputDevice;t&&(e.isLocal||e.stream&&(yield e.stream.setAudioOutput(t.deviceId)))}))}changeAudioInput(e){var t,r,i;return __awaiter(this,void 0,void 0,(function*(){info("change audio input device","","",[JSON.stringify(e)]);const n=null===(t=this.localModel)||void 0===t?void 0:t.stream;if(null===(r=this.room)||void 0===r||r.setSelectAudioDevice(e),n){return"ended"===(null===(i=n.getAudioTrack())||void 0===i?void 0:i.readyState)?(error$1("try to change audio input device but audio track is ended"),!1):(this.removeFromRecorder(n),yield n.switchDevice("audio",e.deviceId),this.addToRecorder(n),!0)}}))}changeVideoInput(e){var t,r,i,n;return __awaiter(this,void 0,void 0,(function*(){info("change video input device","","",[JSON.stringify(e)]);const s=null===(t=this.localModel)||void 0===t?void 0:t.stream;if(null===(r=this.room)||void 0===r||r.setSelectVideoDevice(e),s){return"ended"===(null===(i=s.getVideoTrack())||void 0===i?void 0:i.readyState)?(error$1("try to change video input device but video track is ended"),!1):(yield s.switchDevice("video",e.deviceId),(null===(n=this.localModel)||void 0===n?void 0:n.isDisplay)&&this.localModel.isInBig&&this.localModel.playInBig(),!0)}}))}muteSpeaker(e){return __awaiter(this,void 0,void 0,(function*(){info("静音扬声器 状态 =>","","",["status =>",e]);try{this.setSpeakerEnable(e)}catch(t){return Promise.reject(require$$0.BmSetLocalSpeakerEnable(`开关扬声器失败 ${e} error: ${JSON.stringify(t)}`))}}))}createLocalAudioStream(){var e;return __awaiter(this,void 0,void 0,(function*(){this.room.mediaPermission.microphone?(yield this.room.initDevices(),this.room.audioDevices.length?(null===(e=this.audioStream)||void 0===e||e.destroy(),this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},this.localModel.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e))))):error$1("there is no audio device exists")):error$1("there is no microphone permission")}))}createStreamAndPublish(e,t,r,i){var n,s,o,a,c,u,d,l;return __awaiter(this,void 0,void 0,(function*(){let h=BMStreamModelVM.getCanvasStream();if(yield this.room.initDevices(),t)null===(a=this.brtcStream)||void 0===a||a.destroy(),(null===(c=this.room)||void 0===c?void 0:c.audioDevices.length)||(error$1("当前电脑中没有音频输入设备,重新获取"),yield null===(u=this.room)||void 0===u?void 0:u.initDevices()),(null===(d=this.room)||void 0===d?void 0:d.videoDevices.length)||(error$1("当前电脑中没有视频输入设备, 重新获取"),yield null===(l=this.room)||void 0===l?void 0:l.initDevices()),this.room.audioDevices.length>0?this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:this.room.mediaPermission.microphone},r.userId).catch((e=>(error$1("create brtc audio and video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))):(error$1("没有音频输入设备,只能创建视频流"),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!1},r.userId).catch((e=>(error$1("create brtc video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))));else{const e=h.getVideoTracks()[0];this.audioStream||(this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},r.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e)))));const t=null===(n=this.audioStream)||void 0===n?void 0:n.getAudioTrack();if(!t||t&&t.muted)throw null===(s=this.audioStream)||void 0===s||s.destroy(),this.audioStream=null,this.localStreamErrorWatcher.next("audio"),error$1("麦克风设备不可用","","",["muted => ?",null==t?void 0:t.muted]),require$$0.getStreamError("麦克风");null===(o=this.brtcStream)||void 0===o||o.destroy(),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!0,videoSource:e,audioSource:t},r.userId).catch((e=>Promise.reject(e)))}this.brtcStream&&(t||(yield this.brtcStream.muteVideo()),e||(yield this.brtcStream.muteAudio()),i&&(yield this.brtcStream.replaceTrack(i).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}))),yield this.room.publish(this.brtcStream).catch((e=>{var t,r;return null===(t=this.brtcStream)||void 0===t||t.destroy(),null===(r=this.localModel)||void 0===r||r.updateBloudStream(void 0,this),Promise.reject(e)})),this.brtcStream.on("video-track-mute"+namespace,this.muteHandler.bind(this,"video")),this.brtcStream.on("video-track-ended"+namespace,this.muteHandler.bind(this,"video")),this.brtcStream.on("audio-track-mute"+namespace,this.muteHandler.bind(this,"audio")),this.brtcStream.on("audio-track-ended"+namespace,this.muteHandler.bind(this,"audio")),yield this.publishBloudStream(e,t))}))}publishBloudStream(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){const i=this.localModel.userId;this.bloudStream=this.room.boomCore.creteBloudLocalStream({audio_enable:e,video_enable:t},i),yield this.bloudStream.publish({video_enable:t,audio_enable:e}),null===(r=this.localModel)||void 0===r||r.updateBloudStream({video:t,audio:e,isScreen:!1},this)}))}muteHandler(e){const t=()=>__awaiter(this,void 0,void 0,(function*(){var e,t,r,i,n,s,o,a,c;(null===(e=this.localModel)||void 0===e?void 0:e.stream)&&(yield null===(t=this.room)||void 0===t?void 0:t.boomCore.unpublish(this.localModel.stream).catch((e=>{error$1("brtc local stream has problem and unpublish failed","","",[String(e)])}))),null===(i=null===(r=this.localModel)||void 0===r?void 0:r.stream)||void 0===i||i.destroy(),null===(n=this.audioStream)||void 0===n||n.destroy(),null===(s=this.videoStream)||void 0===s||s.destroy(),null===(o=this.brtcStream)||void 0===o||o.destroy(),this.brtcStream=void 0,this.audioStream=null,this.videoStream=null,null===(a=this.localModel)||void 0===a||a.updateStream(void 0,!0,this),yield this.bloudStream.unpublish(),this.bloudStream=null,null===(c=this.localModel)||void 0===c||c.updateBloudStream(void 0,this)}));setTimeout((()=>__awaiter(this,void 0,void 0,(function*(){var r,i,n,s,o,a,c,u,d,l,h,p,m,f,g,v,y;if(null===(r=this.localModel)||void 0===r?void 0:r.stream){const r=null===(i=this.localModel)||void 0===i?void 0:i.videoEnable,_=null===(n=this.localModel)||void 0===n?void 0:n.audioEnable;if("video"===e){const i=null===(s=this.localModel.stream.getVideoTrack())||void 0===s?void 0:s.muted,n=null===(o=this.localModel.stream.getVideoTrack())||void 0===o?void 0:o.label,v=null===(a=this.localModel.stream.getVideoTrack())||void 0===a?void 0:a.enabled,y=null===(c=this.localModel.stream.getVideoTrack())||void 0===c?void 0:c.readyState,b="ended"===y;if(info("brtc video track status","","",[i,v,y,n]),!b&&!i&&v)return;info("video track has problem, now try recreate and publish"),error$1("brtc本地流出现异常,需要重新推流处理","","",["videoEnable",r,"audioEnable",_,"type",e]),this.localStreamConnectErrorWatcher.next(require$$0.BMStreamDisconnectedError("摄像头")),(null===(u=this.localModel)||void 0===u?void 0:u.stream)&&(yield null===(d=this.room)||void 0===d?void 0:d.boomCore.unpublish(this.localModel.stream).catch((e=>{error$1("brtc local stream has problem and unpublish failed","","",[String(e)])})),null===(l=this.localModel)||void 0===l||l.updateStream(void 0,!0,this),null===(p=null===(h=this.localModel)||void 0===h?void 0:h.stream)||void 0===p||p.destroy(),null===(m=this.audioStream)||void 0===m||m.destroy(),null===(f=this.brtcStream)||void 0===f||f.destroy(),this.brtcStream=void 0,null===(g=this.videoStream)||void 0===g||g.destroy(),this.audioStream=null,this.videoStream=null),yield this.createStreamAndPublish(_,r,this.localModel).catch((e=>__awaiter(this,void 0,void 0,(function*(){error$1("brtc video stream has problem and republish stream failed","","",[JSON.stringify(e)]),yield t(),this.localStreamConnectErrorWatcher.next(require$$0.BmSyncStreamFailError())}))))}else{error$1("brtc本地流出现异常,需要重新推流处理","","",["videoEnable",r,"audioEnable",_,"type",e]),this.localStreamConnectErrorWatcher.next(require$$0.BMStreamDisconnectedError("麦克风")),null===(v=this.audioStream)||void 0===v||v.destroy(),this.audioStream=null,this.audioStream=yield this.room.createPBSingleLocalStream({video:!1,audio:!0});const i=null===(y=this.audioStream)||void 0===y?void 0:y.getAudioTrack();i&&!i.muted?this.localModel.stream&&(yield this.localModel.stream.replaceTrack(i).catch((e=>{error$1("本地流出现异常, 重新创建audio stream replace 失败","本地流出现异常","",[JSON.stringify(e)]),this.localStreamConnectErrorWatcher.next(require$$0.BmSyncStreamFailError()),t()}))):(error$1("recreate audio stream failed, now unpub"),this.localStreamConnectErrorWatcher.next(require$$0.BmSyncStreamFailError()),t())}}this.localStreamErrorWatcher.next(e)}))),1e3)}unpublishStream(){var e,t,r,i;return __awaiter(this,void 0,void 0,(function*(){info("unpublish stream");const n=this.getLocalStreamModel();if(n){const s=n.stream;s&&(yield null===(e=this.room)||void 0===e?void 0:e.unpublish(s).catch((e=>{error$1("brtc 取消发布失败","取消推流",n.userId,[JSON.stringify(e)])})));try{this.removeFromRecorder(s),null==s||s.destroy(),null===(t=this.videoStream)||void 0===t||t.destroy(),null===(r=this.audioStream)||void 0===r||r.destroy(),null===(i=this.brtcStream)||void 0===i||i.destroy(),this.videoStream=null,this.audioStream=null,this.brtcStream=void 0,n.updateStream(void 0,!0,this),yield this.bloudStream.unpublish().catch((e=>{error$1("bloud unpublish stream failed","bloud unpublish stream",n.userId,[JSON.stringify(e),null==e?void 0:e.code,null==e?void 0:e.message])})),n.updateBloudStream(void 0,this),this.bloudStream=null}catch(e){error$1("stream destroy failed","取消推流",n.userId,[JSON.stringify(e)])}}}))}muteOrUnpublishStream(e,t,r){var i;return __awaiter(this,void 0,void 0,(function*(){const t=r.stream;let n=!0;if("audio"===e?n=t.getVideoOn():"video"===e&&(n=t.getAudioOn()),n){if("audio"===e){(yield t.muteAudio())||error$1("brtc muteAudio失败","关闭本地音频","本地"),yield this.bloudStream.setAudioEnabled(!1).catch((e=>{error$1("bloud setAudioEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({audio:!1,video:!0,isScreen:!1},this)}else if("video"===e){const e=BMStreamModelVM.getCanvasStream().getVideoTracks()[0];try{yield t.replaceTrack(e),yield t.muteVideo()}catch(e){error$1("关闭本地视频失败","关闭本地视频","本地",[JSON.stringify(e)])}try{null===(i=this.videoStream)||void 0===i||i.destroy(),this.videoStream=null}catch(e){error$1("this.videoStream destroy failed")}yield this.bloudStream.setVideoEnabled(!1).catch((e=>{error$1("bloud setVideoEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({video:!1,audio:!0,isScreen:!1},this)}}else yield this.unpublishStream()}))}toggleShareScreen(e,t,r){var i,n,s,o,a;return __awaiter(this,void 0,void 0,(function*(){info("开关共享屏幕","","开关共享屏幕",["stats => ",e]),!e&&(null===(i=this.room)||void 0===i?void 0:i.boomCore.shareScreenStream)&&this.removeFromRecorder(null===(n=this.room)||void 0===n?void 0:n.boomCore.shareScreenStream);const c=null===(s=this.room)||void 0===s?void 0:s.voiceMode;return yield this.room.boomCore.toggleShareScreen(e,{audioHint:c},r).then((()=>{if(info("bmStreamVm toggleShareScreen success","切换共享屏幕","",["enable =>",e,"options =>",JSON.stringify(t)]),e){const e=this.room.boomCore.shareScreenStream;e&&this.remoteStreamPublished(e)}else this.localModel.getUser().removeStream(`${this.localModel.userId}_screen`),this.localModel.getUser().updateSortNum(!0)})).catch((r=>(error$1("bmStreamVm toggleShareScreen error","切换共享屏幕","",["enable =>",e,"options =>",t]),Promise.reject(r)))),e&&(null===(o=this.room)||void 0===o?void 0:o.boomCore.shareScreenStream)&&this.addToRecorder(null===(a=this.room)||void 0===a?void 0:a.boomCore.shareScreenStream),this.localIsShare=e,this.isShareWatcher.next(e),Promise.resolve(!0)}))}setShareScreenContentHint(e){var t;null===(t=this.room)||void 0===t||t.boomCore.setShareScreenContentHint(e)}createCanvas(){const e=document.createElement("canvas");e.id="tarCanvas",e.style.width="1px",e.style.height="1px",e.style.position="absolute",e.style.bottom="0",document.body.appendChild(e)}canvasDisplay(){let e=document.getElementById("tarCanvas");if(e){e.width=640,e.height=360;let t=e.getContext("2d");t.fill(),t.beginPath(),t.fillStyle="rgb(0,0,0)",t.fillRect(0,0,e.width,e.height),this.canvasTimer&&clearTimeout(this.canvasTimer),this.canvasTimer=setTimeout((()=>{this.canvasDisplay()}),1e3)}}static getCanvasStream(){return document.getElementById("tarCanvas").captureStream()}createVideoStream(){var e;return __awaiter(this,void 0,void 0,(function*(){return yield this.room.initDevices(),null===(e=this.videoStream)||void 0===e||e.destroy(),this.videoStream=yield this.room.createPBSingleLocalStream({video:!0,audio:!1},this.localModel.userId).catch((e=>Promise.reject(require$$0.BMCreateStreamError("视频")))),this.videoStream.getVideoTrack()}))}startRecord(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(this._recorder)return;this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(e),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended")})),this._recorder.on("started",(()=>{info("record started.")}));let r=!0;try{yield this._recorder.start(),this._isRecording=!0,this.isRecordingWatcher.next(!0),this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),r=!1,yield t.stop()}return r}))}addToRecorder(e){this._isRecording&&!this._slicingRecord&&(e.on("audio-track-ended",(()=>{this.removeFromRecorder(e)})),this._recorder.addStream(e))}removeFromRecorder(e){this._isRecording&&!this._slicingRecord&&this._recorder.removeStream(e)}stopRecord(){return __awaiter(this,void 0,void 0,(function*(){this._recorder&&(this._isRecording=!1,this.isRecordingWatcher.next(!1),yield this._recorder.stop(),this._recorder=void 0)}))}sliceRecord(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(!this._isRecording)return;let r=this._recorder._opts;this._slicingRecord=!0;try{yield this._recorder.stop()}catch(e){error$1("stop record exception","","",[JSON.stringify(e)])}r.filename=e,this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(r),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended.")})),this._recorder.on("started",(()=>{info("record started.")}));let i=!0;try{yield this._recorder.start(),this._slicingRecord=!1,this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),this._slicingRecord=!1,i=!1,yield t.stop()}return i}))}startSpeakerDetector(){var e;this._speaker=null,this._speakerDetector=null===(e=this.room)||void 0===e?void 0:e.boomCore.createSpeakerDetector(),this._speakerDetector.on("speaker",(e=>{var t,r,i;let n=!0;e?((null===(t=this._speaker)||void 0===t?void 0:t.getUserInfo().userId)===e.getUser().userId&&(n=!1),this._speaker=e.getUser()):(this._speaker||(n=!1),this._speaker=null),n&&(info("当前讲话人","语音激励",null===(r=this._speaker)||void 0===r?void 0:r.userId,["nickname => ",null===(i=this._speaker)||void 0===i?void 0:i.nickname]),this.speakerWatcher.next(this._speaker))}))}addToDetector(e){this._speakers.set(e.getID(),e),this._speakerDetector&&this._speakerDetector.addStream(e)}removeFromDetector(e){let t=this._speakers.get(e);this._speakerDetector&&t&&(this._speakers.delete(e),this._speakerDetector.removeStream(t))}clearDetector(){const e=[];this._speakers.forEach(((t,r)=>{e.push(r)})),e.forEach((e=>{this.removeFromDetector(e)}))}shareCustomMedia(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){return null===(r=this.room)||void 0===r?void 0:r.boomCore.shareHTMLMedia(e,t)}))}updateBloudStreamCustomStats(e,t,r){var i;return null===(i=this.room)||void 0===i?void 0:i.boomCore.updateStream(e,t,r)}checkStreamStats(e){info("check stream stats","","",[e]),this.streamModels.size<100&&this.streamModels.forEach((e=>{e.checkStreamIsPlaying()}))}clearCache(){var e,t,r,i,n;try{null===(t=null===(e=this.localModel)||void 0===e?void 0:e.stream)||void 0===t||t.destroy(),null===(r=this.videoStream)||void 0===r||r.destroy(),null===(i=this.audioStream)||void 0===i||i.destroy()}catch(e){}this.streamModels.clear(),this.shareStreamModels.clear(),null===(n=this.room)||void 0===n||n.userVM.clearUsers(),this.shareBloudStateMap.clear()}}class BMRoomInfo{constructor(){this.room=null,this._roomName="",this.msgSeq="",this.roomID="",this.audioOff=!1,this.selfopenaudio=!1,this.lock=!1,this.leaveNotice=!1,this.openSelf=!1,this.chatNotice="",this.chatNoticeRich="",this.raiseHandsList=new Map,this.raiseHandsWatcher=new BehaviorSubject(Array.from(this.raiseHandsList.values())),this.raiseVideoHandsList=new Map,this.raiseVideoHandsWatcher=new BehaviorSubject(Array.from(this.raiseVideoHandsList.values())),this.raiseSimpleHandsList=new Map,this.raiseSimpleHandsWatcher=new BehaviorSubject(Array.from(this.raiseSimpleHandsList.values())),this.operationPermissionWatcher=new Subject,this.chatNoticeWatcher=new Subject,this.totalUserWatcher=new BehaviorSubject(0),this.totalWaitRoomUserWatcher=new BehaviorSubject(0),this.isOpenWaitRoom=new Subject,this.audioOffWatcher=new Subject,this.lockWatcher=new BehaviorSubject(this.lock),this.leaveNoticeWatcher=new BehaviorSubject(this.leaveNotice),this.openSelfWatcher=new BehaviorSubject(this.openSelf),this.setRaiseHandsWatcherValue=debounce((()=>{this.raiseHandsWatcher.next(Array.from(this.raiseHandsList.values()))}),1e3),this.setVideoRaiseHandsWatcherValue=debounce((()=>{this.raiseVideoHandsWatcher.next(Array.from(this.raiseVideoHandsList.values()))}),1e3),this.setSimpleRaiseHandsWatcherValue=debounce((()=>{this.raiseSimpleHandsWatcher.next(Array.from(this.raiseSimpleHandsList.values()))}),1e3),BoomEmitter.emitter.on(RAISE_HAND,(e=>{"raiseHandsAudio"===e.status?e.user.raiseAudioHands?this.addRaiseHandUser(e.user):this.removeRaiseHandUser(e.user.userId):"raiseHandsVideo"===e.status?e.user.raiseVideoHands?this.addVideoRaiseHandUser(e.user):this.removeVideoRaiseHandUser(e.user.userId):"raiseHand"===e.status&&(e.user.raiseHand?this.addSimpleRaiseHandUser(e.user):this.removeSimpleRaiseHandUser(e.user.userId))}))}get roomName(){return this._roomName||(this._roomName=this.room.getName()),this._roomName}get isBigRoom(){return this.room.isBig}setup(e){this.roomID=e.room,this.handleInitParams()}bindRoom(e){this.room=e}initCustomStats(e){this.operationPermission=e,void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}updateOperationPermission(e){this.operationPermission=Object.assign(Object.assign({},this.operationPermission),e),void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}handleInitParams(){const e=this.room.boomCore.getAudioOff(),t=this.room.boomCore.getSelfOpenAudio();this.setAudioOff(e,t)}setAudioOff(e,t){this.audioOff=e,this.selfopenaudio=t,this.audioOffWatcher.next({audioOff:e,selfopenaudio:t})}setlock(e){this.lock=e,this.lockWatcher.next(e)}setLeaveNotice(e){this.leaveNotice=e,this.leaveNoticeWatcher.next(e)}setRaiseHandsList(e){e.forEach((e=>{e.raiseAudioHands&&this.raiseHandsList.set(e.getID(),e),e.raiseVideoHands&&this.raiseVideoHandsList.set(e.getID(),e),e.raiseHand&&this.raiseSimpleHandsList.set(e.getID(),e)})),this.setRaiseHandsWatcherValue(),this.setVideoRaiseHandsWatcherValue(),this.setSimpleRaiseHandsWatcherValue()}addRaiseHandUser(e){this.raiseHandsList.set(e.getID(),e),this.setRaiseHandsWatcherValue()}removeRaiseHandUser(e){this.raiseHandsList.delete(e),this.setRaiseHandsWatcherValue()}addVideoRaiseHandUser(e){this.raiseVideoHandsList.set(e.getID(),e),this.setVideoRaiseHandsWatcherValue()}removeVideoRaiseHandUser(e){this.raiseVideoHandsList.delete(e),this.setVideoRaiseHandsWatcherValue()}addSimpleRaiseHandUser(e){this.raiseSimpleHandsList.set(e.getID(),e),this.setSimpleRaiseHandsWatcherValue()}removeSimpleRaiseHandUser(e){this.raiseSimpleHandsList.delete(e),this.setSimpleRaiseHandsWatcherValue()}}var name="@hysc/meeting",version="10.0.9",description="boom meeting",main="./umd/index.js",module$1="./dist/index.js",types="./dist/index.d.ts",files=["dist","umd"],scripts={build:"tsup ./src/index.ts --format cjs,esm --dts --minify",dev:"tsup ./src/index.ts --format esm,cjs --watch --dts"},author="yangliye",license="MIT",dependencies={"@hysc/bloud":"workspace:*","@hysc/core":"workspace:*","lodash-es":"^4.17.21",mitt:"^3.0.0","@hysc/p-queue":"6.3.0",rxjs:"^7.5.5",typescript:"^4.6.3","@hysc/utils":"workspace:*"},peerDependencies={"@hysc/core":"workspace:*"},devDependencies={"@types/lodash-es":"^4.17.6","@hysc/brtc":"workspace:*"},PackageJson={name:name,version:version,description:description,private:!1,main:main,module:module$1,types:types,files:files,scripts:scripts,author:author,license:license,dependencies:dependencies,peerDependencies:peerDependencies,devDependencies:devDependencies};class BMLiveVM{constructor(e){this.room=e}get localBMUser(){return this.room.getLocalParticipant()}get localIsAudience(){return this.room.getLocalParticipant().isAudience}handlePull(e){return __awaiter(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePull(e)):yield this.room.handlePull(e)}))}handleChangeStreamType(e){return __awaiter(this,void 0,void 0,(function*(){yield this.room.handleChangeStreamType(e)}))}handlePlay(e,t){return __awaiter(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePlay(e,t,!1)):yield this.room.handlePlay(e,t,!0)}))}handleAudienceDisable(){return __awaiter(this,void 0,void 0,(function*(){this.room.bmStreamVm.getStreamModels().forEach((e=>{var t;(null===(t=null==e?void 0:e.stream)||void 0===t?void 0:t.isSubscribed())&&e.hasPulled&&(e.hasPulled=!1,e.pulledStreamType="small",this.room.unsubscribe(e.stream).then((()=>{console.log("观众取消订阅这股流",e.userId,e.nickname,e.isDisplay,e.isCurrentDisplay)})))}));const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1))}))}handleAudienceEnable(){return __awaiter(this,void 0,void 0,(function*(){const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1)),this.room.bmStreamVm.getStreamModels().forEach((e=>{streamPullQueue.addQueue(this.room.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}))}))}}function addBrtcNetEvent(e){var t,r;null===(t=e.brtcClient.client)||void 0===t||t.signal.channel.on("reconnecting",(()=>e.fire(require$$0.BrtcEvents.BRTC_ROOM_ROCONNECTING))),null===(r=e.brtcClient.client)||void 0===r||r.signal.channel.on("reconnected",(()=>e.fire(require$$0.BrtcEvents.BRTC_ROOM_RECONNECTED)))}class SingletonQueue{constructor(){return this.pullMap=new Map,SingletonQueue.instance?SingletonQueue.instance:(SingletonQueue.instance=this,this)}addUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.set(`${e.id}_screen`,e):this.pullMap.set(e.id,e)})),this._callback&&this._callback(this.pullMap)}removeUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.delete(`${e.id}_screen`):this.pullMap.delete(e.id)}))}restart(){if(!this._callback)throw error$1("no callback exists in streamQueue please setQueueProcessor first!"),new Error("no callback");this._callback(this.pullMap)}setQueueProcessor(e){this._callback=e}removeQueueProcessor(){this._callback=void 0}}class AudioPlay{constructor(e,t){this.playMap=new WeakSet,this.playerMap=new Map,this.muted=!1,this.playStateChangeWatcher=new Subject;const r=document.getElementById(e);if(!r)throw new Error("no container found, play failed");this.container=r,this.room=t}addStream(e,t=!1){this.room.shouldPlayAudio&&this.room.autoPlayAudio&&e.isSubscribed()&&(this.playMap.has(e)&&!t||(info("add stream to player","",e.getUserId(),["streamId ",e.getStreamId()]),this.playMap.add(e),this.play(e)))}removeStream(e){const t=e.getStreamId();let r=this.playerMap.get(t);r&&(r.off(),r.destroy()),info("remove audio player","","",["streamId =>",t]),this.playerMap.delete(t),this.playMap.delete(e)}removeStreamByUid(e){let t=new Map;this.playerMap.forEach((r=>{isShareStream(r.stream)||r.stream.getUserId()===e&&t.set(r.stream.getStreamId(),r)})),t.forEach(((e,t)=>{e.off(),e.destroy(),this.playerMap.delete(t),this.playMap.delete(e.stream)})),t.clear()}play(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(e.hasAudio()&&this.container){const r=new dist$1.AudioPlayer(this.container,{});if(this.addPlayerEvent(r),yield r.play(e),this.deviceId&&(yield r.setSinkId(this.deviceId)),this.muted)r.setVolume(0);else{let i;const n=transShareScreen2User(e.getUserId().toString());if(i=isShareStream(e)?this.room.bmStreamVm.shareStreamModels.get(n):this.room.bmStreamVm.streamModels.get(n),i){const e=null===(t=i.bloudStream)||void 0===t?void 0:t.customInfo;e&&e.volume&&(r.audioLevel=e.volume,r.setVolume(e.volume))}}this.playerMap.set(e.getStreamId(),r)}}))}mute(e){this.muted=e,e?this.playerMap.forEach((e=>e.setVolume(0))):this.playerMap.forEach((e=>{e.audioLevel>0?e.setVolume(e.audioLevel):e.setVolume(1)}))}setVolume(e,t){const r=this.playerMap.get(e);if(r){if(r.audioLevel=t,this.muted)return;r.setVolume(t)}else error$1("设置了流的音量,但是没有找到对应的播放器",e)}setDevice(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){this.deviceId=e,t&&(yield sleep(2e3)),this.playerMap.forEach((t=>__awaiter(this,void 0,void 0,(function*(){yield t.setSinkId(e)}))))}))}addPlayerEvent(e){e.on("player-state-changed",(t=>{e.stream&&(info("audio player state change","","",[JSON.stringify(t)]),"error"===t.type&&t.reason&&"NotAllowedError"===t.reason.name&&this.playStateChangeWatcher.next(e),"PAUSED"===t.state&&e.resume())}))}clear(){info("audio play clear"),this.playerMap.forEach((e=>e.destroy())),this.playerMap.clear(),this.playMap=new WeakSet}destroy(){info("audio play destroy"),this.playerMap.forEach((e=>e.destroy())),this.playerMap.clear(),this.playMap=new WeakSet}}let _selfSortType=1;const subscribeOptions={audio:!0,video:!0,streamType:"small",videoEnable:!0,audioEnable:!0};let autoPlayAudio=!0;class BMRoom{constructor({initDevices:e}={initDevices:!0}){this.roomVM=null,this.videoDevices=[],this.audioDevices=[],this.audioOutputDevices=[],this.selectVideoDevice=null,this.selectAudioDevice=null,this.selectAudioOutputDevice=null,this.streamQueue=new SingletonQueue,this.userListColumns=1,this.sortType=1,this.BRTCConnectFailed=!1,this.pubFailedNum=0,this.streamConnectedErrorQueue=[],this.conferenceMode=1,this.isBig=!1,this.selectVideoDeviceWatcher=new BehaviorSubject(this.selectVideoDevice),this.selectAudioDeviceWatcher=new BehaviorSubject(this.selectAudioDevice),this.selectAudioOutputDeviceWatcher=new BehaviorSubject(this.selectAudioOutputDevice),this.audioDevicesWatcher=new Subject,this.videoDevicesWatcher=new Subject,this.audioOutputDevicesWatcher=new Subject,this.raiseHandleRespWatcher=new Subject,this.enableAudienceSpeakingWatcher=new Subject,this.mediaPermission={microphone:!0,camera:!0,screen:!0},this.videoProfile="360p",this.audioProfile=null,this.voiceMode="",this.streamWSReconnectWatcher=new Subject,this.bloudWSReconnectWatcher=new Subject,this.netConnecting=!0,this.netConnectingWatcher=new Subject,this.hasSyncPermission=!0,this.meetingControlOptions={cancelAutoPull:!1},this.forceId="",this.networkState={bloud:!0,brtc:!0},this.brtcNetEnableWatcher=new Subject,this.autoPlayAudio=!0,this.pubFailedTimer=null,this.messageWatcher=new BehaviorSubject({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),this.isInWaitRoom=!1,this.shouldPlayAudio=!0,this.handleReprocessStreamError=()=>{this.netConnecting&&this.networkState.brtc&&this.networkState.bloud&&this.streamConnectedErrorQueue.length&&(info("brtc 网络恢复正常,处理重推逻辑","","",this.streamConnectedErrorQueue),this.streamConnectedErrorQueue.forEach((e=>{this.handleStreamConnectError(e)})),this.streamConnectedErrorQueue=[])},this.handleMediaDevicesChange=debounce((()=>__awaiter(this,void 0,void 0,(function*(){const e=this.filterDevice(this.audioDevices);yield this.bmStreamVm.changeAudioInput(e);const t=this.filterDevice(this.audioOutputDevices);yield this.bmStreamVm.changeSpeaker(t,!0)}))),1e3),this.enumVideoDevices=dist$1.enumVideoDevices,this.enumAudioInputDevices=dist$1.enumAudioInputDevices,this.enumAudioOutputDevices=dist$1.enumAudioOutputDevices,this.getPermissions=dist$1.getPermissions,this.checkSystemSupport=dist$1.checkSystemSupport,this.createStream=dist$1.createStream,this.participantNotice=!1,this.handleQueueTask=(e,t=!1)=>__awaiter(this,void 0,void 0,(function*(){this.BRTCConnectFailed||(e.isLocal||!this.meetingControlOptions.cancelAutoPull||e.shouldPull)&&(this.streamModelExits(e)?yield this.handleStreamTask(e,t):warn(`streamModel is not exits, userId: ${e.userId}, isShare: ${e.isShare}, ignore`))})),this.republishLocalStream=debounce((e=>__awaiter(this,void 0,void 0,(function*(){const t=e.getAudioOn()||!1,r=e.getVideoOn()||!1;info("republish local stream ","","",[t,r]),(t||r)&&(yield this.publish(e).then((()=>__awaiter(this,void 0,void 0,(function*(){this.bmStreamVm.bloudStream=null,yield this.bmStreamVm.publishBloudStream(t,r),info("local stream connect error, and republish success, bloud stream republish success","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(require$$0.BMStreamReconnectSuccess(t,r))})))).catch((()=>{info("local stream connect error, and republish failed","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(require$$0.BMStreamReconnectFailed())})))}))),1e3),this.processUser=e=>__awaiter(this,void 0,void 0,(function*(){const t=new Set;if(e.forEach((e=>{if(e.isScreen){const r=this.bmStreamVm.getShareStreamModelByUId(e.id);r&&r.stream||(e.isWeb?t.add(`${e.id}_screen`):t.add(e.id))}else{let r=this.bmStreamVm.streamModels.get(e.id);r&&!r.stream&&t.add(e.id)}})),info("brtc query streams","","",["queryIds => ",JSON.stringify(Array.from(t))]),t.size)try{const e=yield this.queryBrtcStreams(Array.from(t));if(e&&e.length){const t=e.map((e=>[e.getUserId(),e.getStreamId()]));info("brtc query streams result","","",["streamInfo =>",JSON.stringify(t)]),e&&this.handleAddStreams(e)}}catch(e){error$1("query stream error","","",[JSON.stringify(e)])}})),this.queueProcessor=debounce(this.processUser,500,{maxWait:1e3}),require$$0.Logger.setLogLevel(require$$0.LOGLEVEL.INFO),info(`\n******************************************************************************\n* 欢迎使用 BoomCore(${PackageJson.version})\n******************************************************************************\n `),require$$0.Logger.info("this is formatted by hysc/logger module");const t=BoomEmitter.getInstance();this.localUser=new BMUser({},!0),this.roomInfo=new BMRoomInfo,this.roomInfo.bindRoom(this),this.bmLiveVM=new BMLiveVM(this),this.bmStreamVm=(new BMStreamModelVM).initWithRoom(this),this.boomCore=new dist$1({}),t.on(RECEIVE_SUBSCRIBE_MESSAGE,(e=>{this.handleSubMessage(e)})),t.on(HANDLE_STREAM_CONNECT_ERROR,(e=>{this.handleStreamConnectError(e)})),t.on(ADD_PULL_USER,(e=>{this.addUser2Queue(e)})),t.on(MANUAL_SUBSCRIPTION,(e=>{this.manualSubscribeStreamModel(e.stream)})),t.on(UNSUBSCRIBE_STREAM,(e=>{this.handleUnsubscribe(e.stream)})),t.on(BIND_ELEMENT,(e=>{this.handleStreamBindElement(e.stream)})),t.on(BIND_BIG_ELEMENT,(e=>{this.handleStreamBindBigElement(e.stream)})),t.on(SET_VOLUME,(e=>{var t;null===(t=this.audioPlayer)||void 0===t||t.setVolume(e.streamId,e.volume)})),t.on(ADD_AUDIO_PLAY,(e=>{const t=e.stream.stream;t&&!t.isLocalStream()&&(this.audioPlayer.playMap.has(t)||this.audioPlayer.addStream(t))})),window.addEventListener("offline",(()=>{this.netConnecting=!1,this.netConnectingWatcher.next(!1)})),window.addEventListener("online",(()=>{this.netConnecting=!0,this.netConnectingWatcher.next(!0),NETWORK_ERROR_QUEUE.forEach((e=>{e()})),NETWORK_ERROR_QUEUE.clear(),this.handleReprocessStreamError()})),window.navigator.mediaDevices&&e&&(window.navigator.mediaDevices.ondevicechange=e=>__awaiter(this,void 0,void 0,(function*(){info("media devices change","","",[JSON.stringify(e)]),yield this.initDevices(),yield this.handleMediaDevicesChange()})),this.initDevices()),this.streamQueue.setQueueProcessor(this.queueProcessor),this.brtcNetEnableWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()})),this.bloudWSReconnectWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()}))}setVoiceMode(e){this.voiceMode=e}get isSingleColumns(){return 1===this.userListColumns}setAutoPlayAudio(e){this.autoPlayAudio=e,autoPlayAudio=e}setMediaPermission(e){this.mediaPermission=Object.assign(Object.assign({},this.mediaPermission),e),info("current media permission is ","","",[JSON.stringify(this.mediaPermission)])}setShouldPlayAudio(e){this.shouldPlayAudio=e}initAudioPlayer(e){info("init audio player"),this.audioPlayer=new AudioPlay(e,this)}setupMeetingControlOptions(e){e&&(this.meetingControlOptions=Object.assign(Object.assign({},this.meetingControlOptions),e))}handleSubMessage(e){streamPullQueue.addQueue(this.handleQueueTask.bind(this,e.stream),`${e.stream.streamId} - 订阅流 - display ${e.stream.isDisplay} - currentDisplay - ${e.stream.isCurrentDisplay}`,0,e.stream.nickname)}setVideoProfile(e){e&&(info(`set video profile ${e} `),this.videoProfile=e)}setUserListColumns(e){const t=toNumber(e);if(!isNumber(t))throw new Error("参数必须是数字");this.userListColumns=t}setSortType(e){const t=toNumber(e);if(t>2||t<1)throw new Error("排序映射只能为 2 或者 1");this.sortType=t,_selfSortType=this.sortType}setAudioProfile(e){this.audioProfile=e}setSig(e){this.boomCore.setShareSig(e)}initDevices(){return __awaiter(this,void 0,void 0,(function*(){return Promise.all([this.enumVideoDevices().then((e=>{this.videoDevices=e,this.videoDevicesWatcher.next(e)})),this.enumAudioInputDevices().then((e=>{this.audioDevices=e,this.audioDevicesWatcher.next(e)})),this.enumAudioOutputDevices().then((e=>{this.audioOutputDevices=e,this.audioOutputDevicesWatcher.next(e)}))]).then((()=>{let e=this.videoDevices.filter((e=>{var t;return e.name==(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.name)}));const t=e[0]?e[0]:this.filterDevice(this.videoDevices);t&&this.setSelectVideoDevice(t);let r=this.audioDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.name)}));const i=r[0]?r[0]:this.filterDevice(this.audioDevices);i&&this.setSelectAudioDevice(i);let n=this.audioOutputDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.name)}));const s=n[0]?n[0]:this.filterDevice(this.audioOutputDevices);return s&&this.setSelectSpeakerDevice(s),{videoDevices:this.videoDevices,audioDevices:this.audioDevices,audioOutputDevices:this.audioOutputDevices,selectVideoDevice:this.selectVideoDevice,selectAudioDevice:this.selectAudioDevice,selectAudioOutputDevice:this.selectAudioOutputDevice}}))}))}filterDevice(e){const t=e.filter((e=>e.default))[0];return t||e[0]}setSelectAudioDevice(e){var t;(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectAudioDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioDevice=e,this.selectAudioDeviceWatcher.next(e))}setSelectVideoDevice(e){var t;(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectVideoDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectVideoDevice=e,this.selectVideoDeviceWatcher.next(e))}setSelectSpeakerDevice(e){var t;(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectSpeakerDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioOutputDevice=e,this.selectAudioOutputDeviceWatcher.next(e))}observe(e,t){return this.observes[e].subscribe(t)}join(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.brtc_host;t&&this.setCustomUrl(t);try{if(this.boomCore.client)return error$1("重复 join,请先调用 destroy"),Promise.reject(require$$0.RepeatJoinError);this.conferenceMode=e.roomType,this.isBig=e.is_big,info("========================","join info",e.userId,["roomId: ",e.room," roomType: ",e.roomType," roomName: ",e.name]),this.localUser.setup(e.userId,e.userinfo,e.nickname),this.bmStreamVm.createStreamModel(this.localUser),this.userVM=new BMUserVM(this.boomCore,this.localUser,this),this.isBig&&(this.userVM.commTimer=1e3),this.roomVM=new BMRoomVM(this.boomCore,this.userVM,this.roomInfo),this.roomVM.initWithRoom(this),this.chatVM=new BMChatVM(this.boomCore,this.userVM,this),this._attachEvents(),yield this.boomCore.join(e).catch((e=>Promise.reject(e))),this.roomInfo.setup(this.boomCore.getRoomInfo());for(let e in this.observes)this.observe(e,(()=>{}));this.bmStreamVm.startSpeakerDetector(),this.roomInfo.setlock(this.boomCore.client.lock),addBrtcNetEvent(this.boomCore)}catch(e){return error$1("join room error","","",[JSON.stringify(e)]),Promise.reject(e)}}))}leave(){var e,t;return __awaiter(this,void 0,void 0,(function*(){try{this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedNum=0,BoomEmitter.removeEmitter(),autoPlayAudio=!0,null===(e=this.audioPlayer)||void 0===e||e.destroy(),this.bmStreamVm.clearCache(),this.bmStreamVm.canvasTimer&&clearTimeout(this.bmStreamVm.canvasTimer);const r=yield this.boomCore.leave().catch((()=>{error$1("bloud离会失败")}));for(let e in this.observes)null===(t=this.observes[e])||void 0===t||t.unsubscribe();return this.observes={},r}catch(e){return error$1("leave room error","","",[JSON.stringify(e)]),Promise.reject(require$$0.BmLeaveError(JSON.stringify(e)))}}))}releaseRoom(){return __awaiter(this,void 0,void 0,(function*(){yield this.boomCore.releaseRoom()}))}startRecord(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.bmStreamVm.startRecord(e)}))}stopRecord(){return __awaiter(this,void 0,void 0,(function*(){return yield this.bmStreamVm.stopRecord()}))}sliceRecord(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.bmStreamVm.sliceRecord(e)}))}close(){this.bmStreamVm.clearCache(),this.boomCore.close()}setRemoteVideoEnable(e,t){return __awaiter(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setRemoteAudioEnable(e,t,r){return __awaiter(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteAudioEnable(e,t,r).catch((e=>Promise.reject(e)))}))}setLocalVideoEnable(e,t){return __awaiter(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setLocalAudioEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalAudioEnable(e).catch((e=>Promise.reject(e)))}))}setLocalSpeakerEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.bmStreamVm.muteSpeaker(e).catch((e=>Promise.reject(e)))}))}_attachEvents(){this.observes=attachEvents(this.boomCore,this.userVM,this.bmStreamVm,this.chatVM,this)}createSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId,sourceType:"camera"};e.videoSource&&(n.videoSource=e.videoSource),e.audioSource&&(n.audioSource=e.audioSource),n.echoCancellation=!0,n.noiseSuppression=!0,n.autoGainControl=!0,this.voiceMode&&(n.audioHint=this.voiceMode,n.noiseSuppression=!1);const s=yield this.boomCore.createLocalStream(n,t).catch((t=>(error$1("create brtc stream error","","",[JSON.stringify(t),null==t?void 0:t.message]),Promise.reject(require$$0.getStreamError(e.video?"摄像头":"麦克风")))));e.video&&("720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile));try{yield s.init()}catch(t){if(error$1("brtc init stream failed","","",[null==t?void 0:t.message]),String(t).includes("Permission denied by system")){if(e.video)return Promise.reject(require$$0.BMCameraNotAuthError());if(e.audio)return Promise.reject(require$$0.BMMicNotAuthError())}else{if(String(t).includes("Could not start video source"))return Promise.reject(require$$0.BMCameraOccupyError());if(String(t).includes("Could not start audio source"))return Promise.reject(require$$0.BMMicOccupyError())}return Promise.reject(require$$0.BMCreateStreamError(e.video?"摄像头":"麦克风"))}return s}))}createPBSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId,sourceType:"camera",echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};this.voiceMode&&(n.audioHint=this.voiceMode,n.noiseSuppression=!1);const s=yield this.boomCore.createPBLocalStream(n,t).catch((e=>Promise.reject(e)));return"720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile),yield s.init(),s}))}subscribe(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.boomCore.subscribe(e,t)}))}unsubscribe(e){return this.boomCore.unsubscribe(e).catch((e=>Promise.reject(e)))}publish(e){return new Promise(((t,r)=>{this.boomCore.publish(e).then((()=>{info("brtc stream publish success"),t(!0)})).catch((()=>__awaiter(this,void 0,void 0,(function*(){this.pubFailedNum<=3?(this.pubFailedNum+=1,this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedTimer=setTimeout((()=>(error$1(`local publish stream failed, retry failed num: ${this.pubFailedNum}`),this.publish(e).then(t).catch(r))),3e3)):(error$1("retry publish local stream failed, ubpublish now"),yield this.bmStreamVm.unpublishStream(),r(!1))}))))}))}unpublish(e){return this.boomCore.unpublish(e).catch((e=>Promise.reject(e)))}getUser(e){return this.userVM.getUser(e)}changeMaster(e,t=!1){var r;return __awaiter(this,void 0,void 0,(function*(){return null===(r=this.roomVM)||void 0===r?void 0:r.changeMaster(e,t).catch((e=>e))}))}updateManager(e,t,r=!0){return __awaiter(this,void 0,void 0,(function*(){return this.roomVM.updateManager(e,t,r).catch((e=>e))}))}getMaster(){return this.boomCore.getMaster()}getCreator(){return this.boomCore.getCreator()}getName(){return this.boomCore.getName()}evictUser(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.evictUser(e,t).catch((e=>e))}))}updateUser(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){null===(r=this.roomVM)||void 0===r||r.updateUser(e,t).catch((e=>e))}))}getMsgSeq(){return this.boomCore.getMsgSeq()}getLimits(){return this.boomCore.getLimits()}getSwitch(){return this.boomCore.getSwitch()}syncRoom(){return this.boomCore.syncRoom()}update(e){return this.boomCore.update(e)}getUsers(){return this.userVM.userList}getTotalUsers(){return this.userVM.userList.size}sendMessage(e,t){return this.boomCore.sendMessage(e,t)}customMessage(e,t){return this.boomCore.customMessage(e,t)}getMessages(e,t){return this.boomCore.getMessages(e,t)}getLocalParticipant(){var e;let t=null===(e=this.userVM)||void 0===e?void 0:e.getLocalUser();return t||(t=this.localUser),t}getAudioOff(){return this.boomCore.getAudioOff()}getSelfOpenAudio(){return this.boomCore.getSelfOpenAudio()}getVideoOff(){return this.boomCore.getVideoOff()}getMsgOff(){return this.boomCore.getMsgOff()}getLock(){return this.boomCore.getLock()}getRoomInfo(){return this.roomInfo}setAudioOff(e,t){return __awaiter(this,void 0,void 0,(function*(){return yield this.boomCore.setAudioOff(e,t).catch((e=>Promise.reject(require$$0.BmSetAudioOffError(`boomCore.setAudioOff error ${JSON.stringify(e)}`))))}))}updateRoom(e){return __awaiter(this,void 0,void 0,(function*(){return this.boomCore.client.update(e)}))}setVideoOff(e){return this.boomCore.setVideoOff(e).catch((e=>Promise.reject(require$$0.BmSetVideoOffError(`boomCore.setVideoOff error ${JSON.stringify(e)}`))))}setMsgOff(e){return this.boomCore.setMsgOff(e).catch((e=>Promise.reject(require$$0.BmSetMsgOffError(`boomCore.setMsgOff error ${JSON.stringify(e)}`))))}setSwitch(e){return this.boomCore.setSwitch(e)}setLock(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.boomCore.setLock(e),this.boomCore.getLock()}))}sendChatMessage(e,t,r){if(!this.chatVM)throw new BoomError(INVALID_OPERATION,"未初始化chatVM, 无法发送聊天信息");return this.chatVM.sendMessage(e,t,r)}getChatMessage(){if(!this.chatVM)throw new BoomError(INVALID_OPERATION,"未初始化chatVM, 无法获取聊天室消息");return this.chatVM.messageList}getHistoryMessage(){return __awaiter(this,void 0,void 0,(function*(){return this.chatVM.getHistoryMessage()}))}updateCustomStats(e){return info("updateCustomStats","","",[JSON.stringify(e)]),this.boomCore.updateCustomStats(Object.assign(Object.assign({},e),{pos:"web"})).catch((e=>Promise.reject(require$$0.BmUpdateCustomStatsError(`.boomCore.updateCustomStats ${JSON.stringify(e)}`))))}getCustomStats(){return this.boomCore.getCustomStats()}getDuration(){return this.boomCore.getDuration()}checkUserHasMaster(e){return this.userVM.checkUserHasMaster(e)}changeNickName(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.changeNickName(e,t)}))}streamModelExits(e){const t=e.userId;return e.isShare?this.bmStreamVm.shareStreamModels.has(t):this.bmStreamVm.streamModels.has(t)}handleStreamTask(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){this.streamModelExits(e)?e.stream?1===this.conferenceMode?(yield this.handlePull(e),yield this.handlePlay(e,t),yield this.handleChangeStreamType(e)):(yield this.bmLiveVM.handlePull(e),yield this.bmLiveVM.handleChangeStreamType(e),yield this.bmLiveVM.handlePlay(e,t)):((e.isDisplay||e.isInBig)&&e.bloudStream||e.audioEnable)&&(yield this.addUser2Queue({id:e.userId,isScreen:e.isShare,isWeb:e.isWeb})):warn(`streamModel is not exits, userId: ${e.userId}, isShare: ${e.isShare}, ignore`)}))}handlePull(e){var t,r,i;return __awaiter(this,void 0,void 0,(function*(){e.isLocal||(e.isMixer&&(yield this.handleSubscribeSteam(e)),(e.isDisplay!==e.isCurrentDisplay||e.isInBig&&e.pulledStreamType!==e.pulledStreamGoal||!e.hasPulled)&&(info(" 订阅流 => ","订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(r=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===r?void 0:r.call(t)]),e.isCurrentDisplay=e.isDisplay,e.checkCount=0,e.isDisplay||e.isInBig||!e.isDisplay&&(e.audioEnable||(null===(i=e.stream)||void 0===i?void 0:i.getAudioOn()))?yield this.handleSubscribeSteam(e):yield this.handleUnsubscribeStream(e)))}))}manualSubscribeStreamModel(e){streamPullQueue.addQueue(this.handleStreamTask.bind(this,e),e.streamId,0,e.nickname)}handleUnsubscribe(e){streamPullQueue.addQueue(this.handleUnsubscribeStream.bind(this,e),e.streamId,0,e.nickname)}handleStreamBindElement(e){streamPullQueue.addQueue(this.handlePlay.bind(this,e,!1,!1),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleStreamBindBigElement(e){streamPullQueue.addQueue(this.handlePlayInBIg.bind(this,e),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleUnsubscribeStream(e){var t,r,i,n,s;return __awaiter(this,void 0,void 0,(function*(){if(e.stream&&((null===(r=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===r?void 0:r.call(t))||e.hasPulled)){info("取消订阅流 => ","取消订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)]),e.hasPulled=!1,e.pulledStreamType="small",e.isInBig=!1;try{null===(s=e.stream)||void 0===s||s.stop()}catch(e){}yield this.unsubscribe(e.stream).then((()=>{var t,r;e.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(e.stream)),e.isSubScribedWatcher.next(!1),info("取消订阅流成功","",e.userId,[e.nickname,e.isDisplay,e.isCurrentDisplay,null===(r=e.stream)||void 0===r?void 0:r.getStreamId()])})).catch((()=>{error$1("unsubscribe error")}))}}))}handleSubscribeSteam(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){try{e.hasPulled&&e.stream.isSubscribed()?e.isDisplay?null===(t=e.stream)||void 0===t||t.unmuteVideo().then((()=>{info("stream unmute video success","unmute-video",e.userId,["streamId => ",e.streamId])})):null===(r=e.stream)||void 0===r||r.muteVideo().then((()=>{info("stream mute video success","mute-video",e.userId,["streamId => ",e.streamId])})):(info("开始订阅"),e.hasPulled=!0,yield this.subscribe(e.stream,subscribeOptions).then((()=>{var t,r;info("订阅流结束","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId,"display =>",e.isDisplay]),e.isDisplay||null===(t=e.stream)||void 0===t||t.muteVideo(),e.stream&&e.audioEnable&&(null===(r=this.audioPlayer)||void 0===r||r.addStream(e.stream,!0)),e.pullFailedNum=0,e.isSubScribedWatcher.next(!0),this.bmStreamVm.addToRecorder(e.stream),e.isDisplay&&e.videoEnable&&checkStreamIsNormal(e)})).catch((t=>{var r,i;if(error$1("订阅流失败","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId," error => ",JSON.stringify(t)]),e.hasPulled=!1,e.pulledStreamType="small",e.pullFailedNum+=1,null===(r=e.player)||void 0===r||r.destroy(),e.pullFailedNum<=3)this.handlePulledFailed(e);else{e.pullFailedNum=0;const r=e.isShare;try{null===(i=e.stream)||void 0===i||i.destroy()}catch(t){}e.updateStream(void 0,!1,this.bmStreamVm),info("subscribe stream failed, need to reQuery stream","",e.userId,["streamId =>",e.streamId,"hasStream => ",!!e.stream,"isWeb => ",e.isWeb,"isScreen => ",r,"bloudStreamState =>",JSON.stringify(e.bloudStream)]),e.bloudStream&&this.addUser2Queue({id:e.userId,isWeb:e.isWeb,isScreen:r})}})))}catch(t){e.hasPulled=!1,e.pulledStreamType="small",console.error("订阅流失败","",e.userId,e.nickname,"错误 =>",t)}}))}handleChangeStreamType(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){e.isLocal||e.pulledStreamType!==e.pulledStreamGoal&&(null===(t=e.stream)||void 0===t?void 0:t.isSubscribed())&&((null===(r=e.stream)||void 0===r?void 0:r.isSubscribed())||e.hasPulled)&&(info("大小流切换 => ","切换大小流",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," pulledStreamType =>",e.pulledStreamType," pulledStreamGoal =>",e.pulledStreamGoal]),e.pulledStreamType=e.pulledStreamGoal,yield this.boomCore.brtcClient.setRemoteVideoStreamType(e.stream,e.pulledStreamGoal).catch((t=>{error$1("大小流切换失败","",e.userId,["error => ",JSON.stringify(t)])})),info("大小流切换结束","",e.userId,["nickname =>",e.nickname," isInBig => ",e.isInBig," pulledStreamGoal => ",e.pulledStreamGoal,"pulledStreamType => ",e.pulledStreamType]))}))}handlePlay(e,t,r=!0){var i,n,s;return __awaiter(this,void 0,void 0,(function*(){this.streamModelExits(e)&&(e.isLocal?e.isShare||t||(yield e.play(),yield e.playInBig()):(e.hasPulled||(null===(i=null==e?void 0:e.stream)||void 0===i?void 0:i.isSubscribed()))&&(t&&!e.isShare||(yield e.play()),e.stream&&e.audioEnable&&((null===(n=this.audioPlayer)||void 0===n?void 0:n.playMap.has(e.stream))||null===(s=this.audioPlayer)||void 0===s||s.addStream(e.stream)),r&&(yield this.handlePlayInBIg(e))))}))}handlePlayInBIg(e){return __awaiter(this,void 0,void 0,(function*(){this.streamModelExits(e)&&(yield e.playInBig())}))}handlePulledFailed(e){const t=e.userId;(e.isShare?this.bmStreamVm.shareStreamModels.has(t):this.bmStreamVm.streamModels.has(t))&&streamPullQueue.addQueue(this.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}handleStreamConnectError(e){var t;return __awaiter(this,void 0,void 0,(function*(){const{stream:r,isLocal:i}=e;info("handleStreamConnectError","","",["nickname =>",r.nickname,"streamId => ",r.streamId,"isShare =>",r.isShare,"isLocal => ",i]),r.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(r.stream)),i?r.stream&&(r.isShare?this.bmStreamVm.localShareError.next(require$$0.BMShareStreamConnectError()):this.bmStreamVm.localStreamConnectErrorWatcher.next(require$$0.BMStreamConnectError()),this.netConnecting&&this.networkState.brtc&&this.networkState.bloud?r.isShare?(info("Local share stream has problem, now ,republish"),handleShareStreamFailed(this,this.bmStreamVm)):(info("brtc 网络正常,重新推流"),r.stream&&(yield this.republishLocalStream(r.stream))):(error$1("brtc 网络还没恢复,等恢复了在重新推流 ","",r.userId,["nickname =>",r.nickname,"streamId => ",r.streamId,"isShare =>",r.isShare]),this.streamConnectedErrorQueue.push(e))):this.netConnecting&&this.networkState.brtc?(r.hasPulled=!1,r.pulledStreamType="small",streamPullQueue.addQueue(this.handleQueueTask.bind(this,r),r.streamId,0,r.nickname)):(error$1("brtc 网络还没恢复,等恢复了在重新拉流 ","",r.userId,["nickname =>",r.nickname]),this.streamConnectedErrorQueue.push(e))}))}toggleAudienceSpeaking(e,t){e.permission.setAudio(t),this.updateUser(e.userId,{permission:e.permission.get()})}updateUserIsGuest(e,t){return __awaiter(this,void 0,void 0,(function*(){e.permission.setSubscribe(t),yield this.updateUser(e.userId,{permission:e.permission.get()})}))}managerChangeToGuest(e){this.userVM.managerChangeToGuest(e)}moveUserRoom(e,t=!1,r=!1){return this.boomCore.client.moveUserRoom(e,t,r)}getParticipantNotice(e){this.participantNotice=e}setCustomUrl(e){this.boomCore.setCustomUrl(e)}handleRePushSelf(){var e,t;return __awaiter(this,void 0,void 0,(function*(){const r=null===(t=null===(e=this.getLocalParticipant())||void 0===e?void 0:e.getMainStreamModel())||void 0===t?void 0:t.stream;r&&(yield this.republishLocalStream(r))}))}handleResetOtherStreamStatus(){info("brtc sync-room-completed"),this.audioPlayer.clear(),this.bmStreamVm.streamModels.forEach((e=>{var t;if(!e.isLocal){e.hasPulled=!1,e.pulledStreamType="small";try{e.stream&&e.stream.stop(),null===(t=e.stream)||void 0===t||t.destroy()}catch(e){}e.updateStream(void 0,!1,this.bmStreamVm)}})),this.bmStreamVm.shareStreamModels.forEach((e=>{var t,r;if(!e.isLocal){e.hasPulled=!1,e.pulledStreamType="small";const i=e.getUser();try{null===(t=e.stream)||void 0===t||t.stop(),null===(r=e.stream)||void 0===r||r.destroy()}catch(e){}i.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`)}})),this.bmStreamVm.shareStreamModels.clear(),this.bmStreamVm.shareStreamModelsWatcher.next(Array.from(this.bmStreamVm.shareStreamModels.values())),this.networkState.brtc=!0,setTimeout((()=>{this.brtcNetEnableWatcher.next(!0),this.streamWSReconnectWatcher.next(!0)}),2e3),handleReconnectedStream(this)}addUser2Queue(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(e.force&&this.processUser(new Map([[e.id,e]])),e.isScreen)this.streamQueue.addUsers([e]);else{const r=this.bmStreamVm.streamModels.get(e.id);r&&!r.isLocal&&(r.stream||r&&((null===(t=r.bloudStream)||void 0===t?void 0:t.audio)||r.bloudStream&&r.isDisplay)&&this.streamQueue.addUsers([e]))}}))}queryBrtcStreams(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.boomCore.brtcClient.queryUsers(e)}))}handleAddStreams(e){e.forEach((e=>{if(isShareStream(e)){const t=this.bmStreamVm.shareStreamModels.get(transShareScreen2User(e.getUserId().toString()));(!t||t&&!t.stream)&&this.bmStreamVm.remoteStreamPublished(e)}else{const t=this.bmStreamVm.streamModels.get(e.getUserId().toString());t&&!t.stream&&this.bmStreamVm.remoteStreamPublished(e)}}))}getForceUser(e){return __awaiter(this,void 0,void 0,(function*(){const{users:t}=yield this.boomCore.queryUsers([e]);this.userVM.addBcUsersMap(t,!0),this.userVM.getForceUserWatcher.next(!0)}))}getVersion(){return PackageJson.version}}window.BoomMeeting=BMRoom,window.BoomError=require$$0.BoomError,window.BOOMLogger=require$$0.Logger,Object.defineProperty(exports,"Logger",{enumerable:!0,get:function(){return require$$0.Logger}}),exports.default=BMRoom,Object.defineProperty(exports,"__esModule",{value:!0})}));
7
+ */class Bowser{static getParser(e,t=!1){if("string"!=typeof e)throw new Error("UserAgent should be a string");return new Parser(e,t)}static parse(e){return new Parser(e).getResult()}static get BROWSER_MAP(){return BROWSER_MAP}static get ENGINE_MAP(){return ENGINE_MAP}static get OS_MAP(){return OS_MAP}static get PLATFORMS_MAP(){return PLATFORMS_MAP}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},specialChar="~",safeSpecialChar="\\x"+("0"+specialChar.charCodeAt(0).toString(16)).slice(-2),escapedSafeSpecialChar="\\"+safeSpecialChar,specialCharRG=new RegExp(safeSpecialChar,"g"),safeSpecialCharRG=new RegExp(escapedSafeSpecialChar,"g"),safeStartWithSpecialCharRG=new RegExp("(?:^|([^\\\\]))"+escapedSafeSpecialChar),indexOf$1=[].indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},$String=String;
8
+ /*!
9
+ Copyright (C) 2013-2017 by Andrea Giammarchi - @WebReflection
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in
19
+ all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
+ THE SOFTWARE.
28
+
29
+ */function generateReplacer(e,t,r){var i,s,o=!1,n=!!t,a=[],d=[e],u=[e],l=[r?specialChar:"[Circular]"],c=e,h=1;return n&&(s="object"==typeof t?function(e,r){return""!==e&&t.indexOf(e)<0?void 0:r}:t),function(e,t){return n&&(t=s.call(this,e,t)),o?(c!==this&&(i=h-indexOf$1.call(d,this)-1,h-=i,d.splice(h,d.length),a.splice(h-1,a.length),c=this),"object"==typeof t&&t?(indexOf$1.call(d,t)<0&&d.push(c=t),h=d.length,(i=indexOf$1.call(u,t))<0?(i=u.push(t)-1,r?(a.push((""+e).replace(specialCharRG,safeSpecialChar)),l[i]=specialChar+a.join(specialChar)):l[i]=l[0]):t=l[i]):"string"==typeof t&&r&&(t=t.replace(safeSpecialChar,escapedSafeSpecialChar).replace(specialChar,safeSpecialChar))):o=!0,t}}function retrieveFromPath(e,t){for(var r=0,i=t.length;r<i;e=e[t[r++].replace(safeSpecialCharRG,specialChar)]);return e}function generateReviver(e){return function(t,r){var i="string"==typeof r;return i&&r.charAt(0)===specialChar?new $String(r.slice(1)):(""===t&&(r=regenerate(r,r,{})),i&&(r=r.replace(safeStartWithSpecialCharRG,"$1"+specialChar).replace(escapedSafeSpecialChar,safeSpecialChar)),e?e.call(this,t,r):r)}}function regenerateArray(e,t,r){for(var i=0,s=t.length;i<s;i++)t[i]=regenerate(e,t[i],r);return t}function regenerateObject(e,t,r){for(var i in t)t.hasOwnProperty(i)&&(t[i]=regenerate(e,t[i],r));return t}function regenerate(e,t,r){return t instanceof Array?regenerateArray(e,t,r):t instanceof $String?t.length?r.hasOwnProperty(t)?r[t]:r[t]=retrieveFromPath(e,t.split(specialChar)):e:t instanceof Object?regenerateObject(e,t,r):t}var CircularJSON={stringify:function(e,t,r,i){return CircularJSON.parser.stringify(e,generateReplacer(e,t,!i),r)},parse:function(e,t){return CircularJSON.parser.parse(e,generateReviver(t))},parser:JSON},circularJson_node=CircularJSON;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex<t;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,t=queue.length}currentQueue=null,draining=!1,runClearTimeout(e)}}function nextTick(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];queue.push(new Item(e,t)),1!==queue.length||draining||runTimeout(drainQueue)}function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)};var title="browser",platform="browser",browser=!0,env={},argv=[],version$1="",versions={},release={},config$1={};function noop$1(){}var on=noop$1,addListener=noop$1,once=noop$1,off=noop$1,removeListener=noop$1,removeAllListeners=noop$1,emit=noop$1;function binding(e){throw new Error("process.binding is not supported")}function cwd(){return"/"}function chdir(e){throw new Error("process.chdir is not supported")}function umask(){return 0}var performance=global$1.performance||{},performanceNow=performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()};function hrtime(e){var t=.001*performanceNow.call(performance),r=Math.floor(t),i=Math.floor(t%1*1e9);return e&&(r-=e[0],(i-=e[1])<0&&(r--,i+=1e9)),[r,i]}var startTime=new Date;function uptime(){return(new Date-startTime)/1e3}var process$1={nextTick:nextTick,title:title,browser:browser,env:env,argv:argv,version:version$1,versions:versions,on:on,addListener:addListener,once:once,off:off,removeListener:removeListener,removeAllListeners:removeAllListeners,emit:emit,binding:binding,cwd:cwd,chdir:chdir,umask:umask,hrtime:hrtime,platform:platform,release:release,config:config$1,uptime:uptime},md5={exports:{}};(function(module){(function(){var ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self,NODE_JS=!root.JS_MD5_NO_NODE_JS&&"object"==typeof process$1&&process$1.versions&&process$1.versions.node;NODE_JS?root=commonjsGlobal:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&module.exports,ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}!root.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!ARRAY_BUFFER||!root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var createOutputMethod=function(e){return function(t){return new Md5(!0).update(t)[e]()}},createMethod=function(){var e=createOutputMethod("hex");NODE_JS&&(e=nodeWrap(e)),e.create=function(){return new Md5},e.update=function(t){return e.create().update(t)};for(var t=0;t<OUTPUT_TYPES.length;++t){var r=OUTPUT_TYPES[t];e[r]=createOutputMethod(r)}return e},nodeWrap=function(method){var crypto=eval("require('crypto')"),Buffer=eval("require('buffer').Buffer"),nodeMethod=function(e){if("string"==typeof e)return crypto.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw ERROR;return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),Array.isArray(e)||ArrayBuffer.isView(e)||e.constructor===Buffer?crypto.createHash("md5").update(new Buffer(e)).digest("hex"):method(e)};return nodeMethod};function Md5(e){if(e)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Md5.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if("string"!==r){if("object"!==r)throw ERROR;if(null===e)throw ERROR;if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||ARRAY_BUFFER&&ArrayBuffer.isView(e)))throw ERROR;t=!0}for(var i,s,o=0,n=e.length,a=this.blocks,d=this.buffer8;o<n;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),t)if(ARRAY_BUFFER)for(s=this.start;o<n&&s<64;++o)d[s++]=e[o];else for(s=this.start;o<n&&s<64;++o)a[s>>2]|=e[o]<<SHIFT[3&s++];else if(ARRAY_BUFFER)for(s=this.start;o<n&&s<64;++o)(i=e.charCodeAt(o))<128?d[s++]=i:i<2048?(d[s++]=192|i>>6,d[s++]=128|63&i):i<55296||i>=57344?(d[s++]=224|i>>12,d[s++]=128|i>>6&63,d[s++]=128|63&i):(i=65536+((1023&i)<<10|1023&e.charCodeAt(++o)),d[s++]=240|i>>18,d[s++]=128|i>>12&63,d[s++]=128|i>>6&63,d[s++]=128|63&i);else for(s=this.start;o<n&&s<64;++o)(i=e.charCodeAt(o))<128?a[s>>2]|=i<<SHIFT[3&s++]:i<2048?(a[s>>2]|=(192|i>>6)<<SHIFT[3&s++],a[s>>2]|=(128|63&i)<<SHIFT[3&s++]):i<55296||i>=57344?(a[s>>2]|=(224|i>>12)<<SHIFT[3&s++],a[s>>2]|=(128|i>>6&63)<<SHIFT[3&s++],a[s>>2]|=(128|63&i)<<SHIFT[3&s++]):(i=65536+((1023&i)<<10|1023&e.charCodeAt(++o)),a[s>>2]|=(240|i>>18)<<SHIFT[3&s++],a[s>>2]|=(128|i>>12&63)<<SHIFT[3&s++],a[s>>2]|=(128|i>>6&63)<<SHIFT[3&s++],a[s>>2]|=(128|63&i)<<SHIFT[3&s++]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>2]|=EXTRA[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var e,t,r,i,s,o,n=this.blocks;this.first?t=((t=((e=((e=n[0]-680876937)<<7|e>>>25)-271733879<<0)^(r=((r=(-271733879^(i=((i=(-1732584194^2004318071&e)+n[1]-117830708)<<12|i>>>20)+e<<0)&(-271733879^e))+n[2]-1126478375)<<17|r>>>15)+i<<0)&(i^e))+n[3]-1316259209)<<22|t>>>10)+r<<0:(e=this.h0,t=this.h1,r=this.h2,t=((t+=((e=((e+=((i=this.h3)^t&(r^i))+n[0]-680876936)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+n[1]-389564586)<<12|i>>>20)+e<<0)&(e^t))+n[2]+606105819)<<17|r>>>15)+i<<0)&(i^e))+n[3]-1044525330)<<22|t>>>10)+r<<0),t=((t+=((e=((e+=(i^t&(r^i))+n[4]-176418897)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+n[5]+1200080426)<<12|i>>>20)+e<<0)&(e^t))+n[6]-1473231341)<<17|r>>>15)+i<<0)&(i^e))+n[7]-45705983)<<22|t>>>10)+r<<0,t=((t+=((e=((e+=(i^t&(r^i))+n[8]+1770035416)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+n[9]-1958414417)<<12|i>>>20)+e<<0)&(e^t))+n[10]-42063)<<17|r>>>15)+i<<0)&(i^e))+n[11]-1990404162)<<22|t>>>10)+r<<0,t=((t+=((e=((e+=(i^t&(r^i))+n[12]+1804603682)<<7|e>>>25)+t<<0)^(r=((r+=(t^(i=((i+=(r^e&(t^r))+n[13]-40341101)<<12|i>>>20)+e<<0)&(e^t))+n[14]-1502002290)<<17|r>>>15)+i<<0)&(i^e))+n[15]+1236535329)<<22|t>>>10)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+n[1]-165796510)<<5|e>>>27)+t<<0)^t))+n[6]-1069501632)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+n[11]+643717713)<<14|r>>>18)+i<<0)^i))+n[0]-373897302)<<20|t>>>12)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+n[5]-701558691)<<5|e>>>27)+t<<0)^t))+n[10]+38016083)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+n[15]-660478335)<<14|r>>>18)+i<<0)^i))+n[4]-405537848)<<20|t>>>12)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+n[9]+568446438)<<5|e>>>27)+t<<0)^t))+n[14]-1019803690)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+n[3]-187363961)<<14|r>>>18)+i<<0)^i))+n[8]+1163531501)<<20|t>>>12)+r<<0,t=((t+=((i=((i+=(t^r&((e=((e+=(r^i&(t^r))+n[13]-1444681467)<<5|e>>>27)+t<<0)^t))+n[2]-51403784)<<9|i>>>23)+e<<0)^e&((r=((r+=(e^t&(i^e))+n[7]+1735328473)<<14|r>>>18)+i<<0)^i))+n[12]-1926607734)<<20|t>>>12)+r<<0,t=((t+=((o=(i=((i+=((s=t^r)^(e=((e+=(s^i)+n[5]-378558)<<4|e>>>28)+t<<0))+n[8]-2022574463)<<11|i>>>21)+e<<0)^e)^(r=((r+=(o^t)+n[11]+1839030562)<<16|r>>>16)+i<<0))+n[14]-35309556)<<23|t>>>9)+r<<0,t=((t+=((o=(i=((i+=((s=t^r)^(e=((e+=(s^i)+n[1]-1530992060)<<4|e>>>28)+t<<0))+n[4]+1272893353)<<11|i>>>21)+e<<0)^e)^(r=((r+=(o^t)+n[7]-155497632)<<16|r>>>16)+i<<0))+n[10]-1094730640)<<23|t>>>9)+r<<0,t=((t+=((o=(i=((i+=((s=t^r)^(e=((e+=(s^i)+n[13]+681279174)<<4|e>>>28)+t<<0))+n[0]-358537222)<<11|i>>>21)+e<<0)^e)^(r=((r+=(o^t)+n[3]-722521979)<<16|r>>>16)+i<<0))+n[6]+76029189)<<23|t>>>9)+r<<0,t=((t+=((o=(i=((i+=((s=t^r)^(e=((e+=(s^i)+n[9]-640364487)<<4|e>>>28)+t<<0))+n[12]-421815835)<<11|i>>>21)+e<<0)^e)^(r=((r+=(o^t)+n[15]+530742520)<<16|r>>>16)+i<<0))+n[2]-995338651)<<23|t>>>9)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+n[0]-198630844)<<6|e>>>26)+t<<0)|~r))+n[7]+1126891415)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+n[14]-1416354905)<<15|r>>>17)+i<<0)|~e))+n[5]-57434055)<<21|t>>>11)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+n[12]+1700485571)<<6|e>>>26)+t<<0)|~r))+n[3]-1894986606)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+n[10]-1051523)<<15|r>>>17)+i<<0)|~e))+n[1]-2054922799)<<21|t>>>11)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+n[8]+1873313359)<<6|e>>>26)+t<<0)|~r))+n[15]-30611744)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+n[6]-1560198380)<<15|r>>>17)+i<<0)|~e))+n[13]+1309151649)<<21|t>>>11)+r<<0,t=((t+=((i=((i+=(t^((e=((e+=(r^(t|~i))+n[4]-145523070)<<6|e>>>26)+t<<0)|~r))+n[11]-1120210379)<<10|i>>>22)+e<<0)^((r=((r+=(e^(i|~t))+n[2]+718787259)<<15|r>>>17)+i<<0)|~e))+n[9]-343485551)<<21|t>>>11)+r<<0,this.first?(this.h0=e+1732584193<<0,this.h1=t-271733879<<0,this.h2=r-1732584194<<0,this.h3=i+271733878<<0,this.first=!1):(this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+i<<0)},Md5.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,i=this.h3;return HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[15&r]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]+HEX_CHARS[i>>4&15]+HEX_CHARS[15&i]+HEX_CHARS[i>>12&15]+HEX_CHARS[i>>8&15]+HEX_CHARS[i>>20&15]+HEX_CHARS[i>>16&15]+HEX_CHARS[i>>28&15]+HEX_CHARS[i>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,i=this.h3;return[255&e,e>>8&255,e>>16&255,e>>24&255,255&t,t>>8&255,t>>16&255,t>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var e,t,r,i="",s=this.array(),o=0;o<15;)e=s[o++],t=s[o++],r=s[o++],i+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[63&(e<<4|t>>>4)]+BASE64_ENCODE_CHAR[63&(t<<2|r>>>6)]+BASE64_ENCODE_CHAR[63&r];return e=s[o],i+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[e<<4&63]+"=="};var exports=createMethod();COMMON_JS?module.exports=exports:root.md5=exports})()})(md5);var At=md5.exports,st=Object.defineProperty,rt=Object.getOwnPropertySymbols,Ut=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty,Pt=Object.prototype.propertyIsEnumerable,$t=Reflect.get,it=(e,t,r)=>t in e?st(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,nt=(e,t)=>{for(var r in t||(t={}))qt.call(t,r)&&it(e,r,t[r]);if(rt)for(var r of rt(t))Pt.call(t,r)&&it(e,r,t[r]);return e},be=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)((function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})),Bt=(e,t)=>{for(var r in t)st(e,r,{get:t[r],enumerable:!0})},ot=(e,t,r)=>$t(Ut(e),r,t),d=(e,t,r)=>new Promise(((i,s)=>{var o=e=>{try{a(r.next(e))}catch(e){s(e)}},n=e=>{try{a(r.throw(e))}catch(e){s(e)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(o,n);a((r=r.apply(e,t)).next())})),oe=class{constructor(e,t,r){this.task=e,this.timeout=t,this.interval=r}start(){let e=this;e.stop();let t=e.timeout,r=e.interval,i=function(){!1!==e.task()&&e.timer?e.timer=setTimeout(i,e.interval):e.stop()};null==t&&(t=r),e.timer=setTimeout(i,t)}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null)}updateInterval(e){this.interval=e}isStarted(){return!!this.timer}destroy(){this.stop(),this.task=this.timeout=this.interval=null}},at="onsend",ct="onreceive",O$1="reconnected",P$1="connected",$="close",_$1="error",E$1="timeout",B="reconnecting",ae="binary",k$1="notify",W="request",F=0,x$1=1,C$1=2,w$1=3,X$1=4,j$1=5,G$1="boom-bloud ",le=typeof console!==g.RAW_UNDEFINED?console:g.NULL,Ft=/bjy/.test(C$2(g.EMPTY_FUNCTION))?C$1:w$1,qe=g.WINDOW&&/edge|msie|trident/i.test(g.WINDOW.navigator.userAgent)?g.EMPTY_STRING:"%c",Z$1=le?qe?function(e,t,r,i){i?le.log(qe+e,r,t,i):le.log(qe+e,r,t)}:function(e,t,r){r?le.log(e,t,r):le.log(e,t)}:g.EMPTY_FUNCTION;function J(){if(g.GLOBAL){let e=g.GLOBAL.BJY_LOG_LEVEL;if(e>=F&&e<=j$1)return e}return Ft}function ee$1(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function lt(e,t){J()<=F&&Z$1(`${t||G$1} trace`,e,ee$1("#999"))}function ut(e,t){J()<=x$1&&Z$1(`${t||G$1} debug`,e,ee$1("#999"))}function ht(e,t){J()<=C$1&&Z$1(`${t||G$1} info`,e,ee$1("#2db7f5"))}function dt(e,t,r){J()<=C$1&&Z$1(`${t||G$1} info`,e,ee$1("#66cdaa"),r)}function mt$1(e,t){J()<=w$1&&Z$1(`${t||G$1} warn`,e,ee$1("#f90"))}function pt$1(e,t){J()<=X$1&&Z$1(`${t||G$1} error`,e,ee$1("#ed4014"))}function ft$1(e,t){if(J()<=j$1)throw new Error(`[${t||G$1} fatal]: ${e}`)}var jt=!0,Gt=w$1;function N$1(){return jt}function gt$1(){return Gt}var m=class e{constructor(e={}){this.TRACE=F,this.DEBUG=x$1,this.INFO=C$1,this.WARN=w$1,this.ERROR=X$1,this.FATAL=j$1,this.options=X$2.extend({uploadLevel:gt$1()},e),this.canUpload=!0}static Log(){return this.instance||(this.instance=new e),this.instance}enableUploadLog(){this.canUpload=!0}disableUploadLog(){this.canUpload=!1}setUploadLevel(e){this.options.uploadLevel=e}fatal(e,t,r=!1){(j$1>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&N$1()&&this.options.onUpload(e,j$1,t),ft$1(e,t)}error(e,t,r=!1){pt$1(e,t),(X$1>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&N$1()&&this.options.onUpload(e,X$1,t)}warn(e,t,r=!1){mt$1(e,t),(w$1>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&N$1()&&this.options.onUpload(e,w$1,t)}info(e,t,r=!1){ht(e,t),(C$1>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&N$1()&&this.options.onUpload(e,C$1,t)}call(e,t,r=!1){dt(e,t),(C$1>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&N$1()&&this.options.onUpload(e,C$1,t)}debug(e,t,r=!1,i=!1){ut(e,t),!i&&(x$1>=this.options.uploadLevel||r)&&this.canUpload&&this.options.onUpload&&N$1()&&this.options.onUpload(e,x$1,t)}trace(e,t,r=!1){lt(e,t),F>=this.options.uploadLevel&&r&&this.canUpload&&this.options.onUpload&&N$1()&&this.options.onUpload(e,F,t)}log(e,t,r,i=!1){switch(t){case F:this.trace(e,r,i);break;case x$1:this.debug(e,r,i);break;case C$1:this.info(e,r,i);break;case w$1:this.warn(e,r,i);break;case X$1:this.error(e,r,i);break;case j$1:this.fatal(e,r,i);break;default:this.debug(e,r,i)}}},{extend:Qt}=X$2,{func:D$1,string:Yt}=O$2,yt$1="RpcBuilder",Xt={maxRetry:0,requestTimeout:5e3,responseTimeout:5e3,duplicatesTimeout:5e3};function te$1(...e){let t="";for(let r=0;r<e.length;r++)e[r]&&(t+=e[r]);return t}var ue=class extends q$1{constructor(e,t,r={},i){super(!1),this.packer=e,this.options=Qt({},Xt,r),this.requestID=0,this.notifyId=0,this.reqMap=new Map,this.resMap=new Map,this.reqKeyMap=new Map,this.logger=i||new m,this.onmessageHandler=e=>{this.onmessage(e)},t&&this.handlTransport(t)}handlTransport(e){this.transport&&(D$1(this.transport.removeListener)?this.transport.removeListener(this.onmessageHandler):D$1(this.transport.removeEventListener)?this.transport.removeEventListener(this.onmessageHandler):D$1(this.transport.onmessage)&&(this.transport.onmessage=null)),e&&(D$1(e.addListener)?e.addListener("onmessage",this.onmessageHandler):D$1(e.addEventListener)?e.addEventListener("onmessage",this.onmessageHandler):e.onmessage=this.onmessageHandler,this.transport=e)}send(e){D$1(this.transport.send)?this.transport.send(e):D$1(this.transport.write)?this.transport.write(e):D$1(this.transport.postMessage)&&this.transport.postMessage(e)}request(e){return d(this,arguments,(function*(e,t={},r={}){if(!this.transport)throw new Error(`request ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);return new Promise(((i,s)=>{var o,n;if(r.key&&this.reqKeyMap.has(r.key)){let i=this.reqKeyMap.get(r.key);clearTimeout(i.timer),this.logger.warn(`request ${e}, params: ${JSON.stringify(t)} canceled because there is call new request whoes key is same as before`),i.reject(new Error("request canceled because there is call new request which key is same as before")),this.reqMap.delete(te$1(i.id)),this.reqKeyMap.delete(r.key)}let a=this.requestID++;r.dest&&(t.dest=r.dest),this.options.peerId&&(t.from=this.options.peerId);let d={resolve:i,reject:s,id:a,dest:r.dest,timer:null,retryCount:0,maxRetry:null!=(o=r.maxRetry)?o:this.options.maxRetry,errorRetry:null!=(n=r.errorRetry)&&n,method:e,params:t,message:this.packer.pack({method:e,params:t},a),timestamp:te$2(),key:r.key,timeout:r.timeout,timeoutFn:()=>{if(d.retryCount>=d.maxRetry){if(this.reqMap.delete(te$1(d.id)),d.key&&this.reqKeyMap.has(d.key)&&this.reqKeyMap.delete(d.key),this.logger.error(`request ${e}, params: ${JSON.stringify(t)} timeout`),this.sessionId!==t.sessionId)return void this.logger.warn(`sessionId is not same, ignore this time out fn: ${this.sessionId}`);s(new Error("request timeout"))}else d.retryCount++,d.timer=setTimeout(d.timeoutFn,r.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${e}, params: ${JSON.stringify(t)}, count: ${d.retryCount}`),this.send(d.message)},needRetry:r.needRetry};d.timer=setTimeout(d.timeoutFn,r.timeout||this.options.requestTimeout*(d.retryCount+1)),this.reqMap.set(te$1(d.id),d),d.key&&this.reqKeyMap.set(d.key,d),this.send(d.message)}))}))}reply(e,t,r){var i;this.options.peerId&&(t&&(t.from=this.options.peerId),r&&(r.from=this.options.peerId));let s=this.packer.pack({result:t,error:r},e.id),o={id:e.id,message:s,timer:null},n=te$1(e.id,null==(i=e.params)?void 0:i.from);this.options.responseTimeout&&(o.timer=setTimeout((()=>{this.resMap.delete(n)}),this.options.responseTimeout),this.resMap.set(n,o)),this.send(o.message)}notify(e,t={},r){if(!this.transport)throw new Error(`notify ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);let i=this.notifyId++;r&&(t.dest=r),this.options.peerId&&(t.from=this.options.peerId),this.send(this.packer.pack({method:e,params:t,seq:i}))}onmessage(e){var t;if(this.transport)if(It$1(e))if(Yt(e)){let r;try{r=this.packer.unpack(e)}catch(t){return void this.logger.error(`unpack message error, message: ${e}, error: ${Vt(t)}`,yt$1)}let i=r.id,s=r.method,o=null!=(t=r.params)?t:{},n=o.dest;if(o.dest,It$1(this.options.peerId)&&this.options.peerId===n)return void this.logger.warn(`ignored the message which send from me, message: ${e}`);if(It$1(i))if(s){let t=this.resMap.get(te$1(i,n));t?(this.logger.warn(`request: ${e} has replyed in ${this.options.responseTimeout}ms, send same again`),this.send(t.message)):this.fire(W,[r])}else{let t=r.error,n=r.result;if((null==t?void 0:t.dest)!==this.options.peerId||(null==n?void 0:n.dest)!==this.options.peerId)return void this.logger.warn(`ignored the message which not sent for me, message: ${e}`);let a=te$1(i),d=this.reqMap.get(a);if(d){if(clearTimeout(d.timer),t){if(this.logger.error(`[request error] request: ${d.message}, response: ${e}, consume: ${te$2()-d.timestamp}`),d.errorRetry&&d.retryCount<d.maxRetry&&(!d.needRetry||d.needRetry(t)))return d.retryCount++,d.timer=setTimeout(d.timeoutFn,d.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${d.method}, params: ${JSON.stringify(d.params)}, count: ${d.retryCount}`),d.id=this.requestID++,d.message=this.packer.pack({method:s,params:o},d.id),void this.send(d.message);d.reject(t)}else this.logger.debug(`[request success] method: ${d.method}, id: ${d.id}, consume: ${te$2()-d.timestamp}`),d.resolve(n);this.reqMap.delete(a),d.key&&this.reqKeyMap.has(d.key)&&this.reqKeyMap.delete(d.key)}else this.logger.warn(`no request for the response: ${e}`)}else this.fire(k$1,[s,o,r.seq])}else this.fire(ae,[e]);else this.logger.warn("message is not defined",yt$1)}destroy(){this.off(),this.handlTransport(),this.reqMap&&(this.reqMap.forEach((e=>{clearTimeout(e.timer),e.reject("transport closed")})),this.reqMap.clear(),this.reqMap=null),this.reqKeyMap&&(this.reqKeyMap.clear(),this.reqKeyMap=null),this.resMap&&(this.resMap.forEach((e=>{clearTimeout(e.timer)})),this.resMap.clear(),this.resMap=null),this.packer=null,this.transport=null}getPacker(){return this.packer}getTransport(){return this.transport}setTransport(e){this.handlTransport(e)}resetRequest(){this.reqMap&&this.reqMap.forEach((e=>{clearTimeout(e.timer),e.timer=setTimeout(e.timeoutFn,e.timeout||this.options.requestTimeout*(e.retryCount+1)),this.send(e.message)}))}},M={OPEN:"open",CLOSE:"close",ERROR:"error",SEND:"send",MESSAGE:"message",TIMEOUT:"timeout",RECONNECTING:"reconnecting"},Be=class extends q$1{constructor(e){var t;super(!0),X$2.extend(this,e),this.status=0,this.queue=[],this.isReconnect=!1,e.retryCount&&e.retryCount>0&&(this.retryIndex=0),this.logger=m.Log(),this.logLevel=null!=(t=this.logLevel)?t:this.logger.TRACE,this.connectCount=0}isOpen(){return 1===this.status}isConnecting(){return 6===this.status}getStatus(){return this.status}connect(e,t){let r=this;if(this.server=e,this.proxys=t,this.connectCount=0,1===r.status||6===r.status||4===r.status)return;let i=[e];t&&t.length&&(i=i.concat(t));let s=-1,o=function(){r.nextStartTimer=null,6===r.status?function(e,t){r.connectCount++;let i=r.nativeOptions;r.native===WebSocket&&(i=r.nativeOptions.protocols),r.logger.debug(`${r.tag||"Transport"} connecting url: ${e.url}`);let s,o=te$2(),n=new r.native(e.url,i),a=function(r){s&&clearTimeout(s),n.onopen=n.onerror=null,t(n,e,r)};n.onopen=function(e){var t;r.consume=null!=(t=null==e?void 0:e.consume)?t:te$2()-o,a(1)},n.onerror=function(){a(2)},r.timeout>0&&(s=setTimeout((function(){s=null,n.onerror=null,n.onopen=null,O$2.func(n.close)&&n.close(),a(5)}),r.timeout))}(i[++s],(function(e,o,a){if(6===r.status)if(1===a){if(r.url=o.url,r.socket=e,r.status=1,e.onmessage=function(e){1===r.status&&(r.logger.log(`${r.tag||"Transport"} Received: ${O$2.string(e.data)?e.data:"binary"}`,r.logLevel),r.onReceive&&O$2.string(e.data)&&r.onReceive(JSON.parse(e.data)),r.onmessage&&r.onmessage(e.data),r.fire(M.MESSAGE,[e.data]))},e.onclose=function(i){if(r.logger.error("bloud socket closed"),kt$1.error("bloud socket closed"),1===r.status)if(r.connectOnClose&&r.retryCount>0){if(r.status=0,r.onReconnecting&&(r.onReconnecting(),4===r.status||3===r.status))return;r.fire(M.RECONNECTING),r.isReconnect=!0,r.logger.warn(`${r.tag||"Transport"} reconnecting`),kt$1.warn(`${r.tag||"Transport"} reconnecting`),e.clear&&e.clear(),r.connect(o,t)}else r.onClose&&r.onClose(i),r.fire(M.CLOSE,[i])},r.retryCount>0&&(r.retryIndex=0),r.onOpen&&(r.logger.debug(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} success`),kt$1.info(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} success`),r.onOpen({server:o,reconnect:r.isReconnect})),r.fire(M.OPEN,[{server:o,reconnect:r.isReconnect}]),r.queue.length)for(;r.queue.length;){let t=r.queue.shift(),i=O$2.string(t)||O$2.arrayBuffer(t)?t:JSON.stringify(t);e.send(i),r.logger.log(`${r.tag||"Transport"} Sent: ${O$2.arrayBuffer(t)?"binary":i}`,r.logLevel),r.onSend&&r.onSend(i),r.fire(M.SEND,[i])}}else if(s===i.length-1){if(r.retryCount>0&&r.retryIndex++<r.retryCount-1)return s=-1,void n();switch(r.status=a){case 2:r.logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} error`),kt$1.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} error`),r.onError&&r.onError({server:o}),r.fire(M.ERROR,[{server:o}]);break;case 5:r.logger.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} timeout`),kt$1.error(`${r.tag||"Transport"} ${r.isReconnect?"reconnect":"connect"} timeout`),r.onTimeout&&r.onTimeout({server:o}),r.fire(M.TIMEOUT,[{server:o}])}}else n();else if(4===r.status){let t=!1;if(1===a&&r.refreshQueueOnClose&&r.queue.length){for(;r.queue.length;){let t=r.queue.shift(),i=O$2.string(t)||O$2.arrayBuffer(t)?t:JSON.stringify(t);e.send(i),r.logger.log(`${r.tag||"Transport"} Sent: ${O$2.arrayBuffer(t)?"binary":i}`,r.logLevel),r.onSend&&r.onSend(i),r.fire(M.SEND,[i])}t=!0}t?setTimeout((()=>{e.close(),r.status=3}),1e3):(e.close(),r.status=3)}})):4===r.status&&(r.status=3)},n=function(){r.interval>0?r.nextStartTimer=setTimeout(o,r.interval):o()};r.status=6,o()}send(e){if(1!==this.status&&4!==this.status)return this.queueMax>0&&this.queue.length===this.queueMax&&this.queue.shift(),void this.queue.push(e);let t=this.socket;if(t){let r=O$2.string(e)||O$2.arrayBuffer(e)?e:JSON.stringify(e);t.send(r),this.logger.log(`${this.tag||"Transport"} Sent: ${O$2.arrayBuffer(e)?"binary":r}`,this.logLevel),this.onSend&&this.onSend(r),this.fire(M.SEND,[r])}}close(){let e=this.socket;if(this.socket=null,this.status=4,e){let t=!1;if(this.refreshQueueOnClose&&this.queue.length){for(;this.queue.length;)this.send(this.queue.shift());t=!0}e.onmessage=e.onclose=null,t?setTimeout((()=>{e.close(),this.status=3}),1e3):(e.close(),this.status=3)}this.nextStartTimer&&(clearTimeout(this.nextStartTimer),this.nextStartTimer=null)}reconnect(){6!==this.status&&(this.close(),4===this.status?setTimeout((()=>{this.status=3,this.connect(this.server,this.proxys)}),1e3):this.connect(this.server,this.proxys))}getSocket(){return this.socket}getConsume(){return Math.max(this.consume||0,0)}getConnectCount(){return this.connectCount}},St$1=Be,de=class{constructor(){}},me=class extends de{constructor(){super()}pack(e,t){let r={jsonrpc:"2.0"};if(e.method)r.method=e.method,e.params&&(r.params=e.params),It$1(t)&&(r.id=t),e.seq&&(r.seq=e.seq);else if(It$1(t)){if(e.error){if(e.result)throw new TypeError("Both result and error are defined");r.error=e.error}else{if(!e.result)throw new TypeError("No result or error is defined");r.result=e.result}r.id=t}return JSON.stringify(r)}unpack(e){let t=JSON.parse(e);if("2.0"!==t.jsonrpc)throw new TypeError(`Invalid JsonRPC version ${t.jsonrpc}: ${e}`);if(!It$1(t.method)){if(!It$1(t.id))throw new TypeError(`Invalid message: ${e}`);let r=It$1(t.error),i=It$1(t.result);if(i&&r)throw new TypeError(`Both result and error are defined: ${e}`);if(!i&&!r)throw new TypeError(`No result or error is defined: ${e}`)}return t}},{extend:sr}=X$2,nr={heartbeat:15e3,requestTimeout:15e3,maxRetry:3,packer:me,retryInterval:500,connectTimeout:1e4,connectOnClose:!0,requestMaxRetry:0},pe=class extends q$1{constructor(e,t,r,i){var s,o;super(!0),this.server=e,this.proxys=r,this.options=sr({},nr,t),this.logger=m.Log(),this.heartbeatTimer=new oe((()=>{this.heartbeat()}),this.options.heartbeat,this.options.heartbeat),this.packer=new this.options.packer,this.transport=new St$1({native:null!=(s=this.options.transport)?s:WebSocket,onSend:e=>{this.fire(at,[e])},onReceive:e=>{this.fire(ct,[e])},onOpen:e=>{this.fire(e.reconnect?O$1:P$1),this.heartbeatTimer&&this.heartbeatTimer.start()},onClose:()=>{this.fire($),this.heartbeatTimer&&this.heartbeatTimer.stop()},onError:()=>{this.fire(_$1),this.heartbeatTimer&&this.heartbeatTimer.stop()},onTimeout:()=>{this.fire(E$1),this.heartbeatTimer&&this.heartbeatTimer.stop()},onReconnecting:()=>{this.fire(B),this.heartbeatTimer&&this.heartbeatTimer.stop()},connectOnClose:this.options.connectOnClose,retryCount:this.options.maxRetry,nativeOptions:null!=(o=this.options.transportOptions)?o:{},tag:this.options.tag,interval:this.options.retryInterval,timeout:this.options.connectTimeout,logLevel:this.options.logLevel}),this.rpc=new ue(this.packer,this.transport,{requestTimeout:this.options.requestTimeout,responseTimeout:this.options.requestTimeout,peerId:this.options.peerId,maxRetry:this.options.requestMaxRetry},this.logger),this.rpc.on(ae,(e=>{this.fire(ae,[e])})),this.rpc.on(k$1,((e,t,r)=>{this.fire(k$1,[e,t,r])})),this.rpc.on(W,(e=>{this.fire(W,[e])})),hn((()=>{this.transport&&this.transport.connect(this.server,this.proxys)}))}setRPCSessionId(e){this.rpc.sessionId=e}request(e){return d(this,arguments,(function*(e,t={},r){return this.rpc.request(e,t,r)}))}reply(e,t,r){return this.rpc.reply(e,t,r)}notify(e,t={}){return this.rpc.notify(e,t)}sendBinary(e){let t=this.transport.getSocket();t&&t.send(e)}getConsume(){return this.transport?this.transport.getConsume():0}getTransportConnectCount(){return this.transport?this.transport.getConnectCount():0}getTransportStatus(){return this.transport?this.transport.getStatus():0}destroy(){this.off(),this.rpc&&this.rpc.destroy(),this.transport&&this.transport.close(),this.transport=null,this.rpc=null,this.packer=null,this.heartbeatTimer&&this.heartbeatTimer.destroy(),this.heartbeatTimer=null}resetRequest(){this.rpc&&this.rpc.resetRequest()}},ie=class e extends pe{constructor(e,t,r,i){super({url:e},t,void 0,i),this.notified=-1,this.seq=0,this.sessionId=null,this.syncRoomLock=!1,this.retryQueue=[],this.proxy=r}resetTimeout(){this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout((()=>{this.resetTimer=void 0,this.fire(E$1),this.destroy()}),4*this.options.heartbeat)}syncNotify(){return d(this,null,(function*(){}))}request(t,r,i){return d(this,null,(function*(){let s=this.seq++;return this.syncRoomLock&&"syncRoom"!==t?(this.logger.warn(`session closed, waiting for sync room, method: ${t}, params: ${JSON.stringify(r)}`),new Promise(((e,i)=>{this.retryQueue.push({method:t,params:r,resolve:e,reject:i,id:s})}))):(!this.syncRoomLock&&"syncRoom"===t&&(this.syncRoomLock=!0),r&&"syncRoom"!==t&&!r.sessinId&&(r.sessionId=this.sessionId),r&&"syncRoom"===t&&(r.sid=this.sessionId),ot(e.prototype,this,"request").call(this,t,r,i).then((e=>(this.resetTimeout(),(!this.sessionId&&e.sessionId||this.sessionId!==e.sessionId)&&e.sessionId&&(this.sessionId=e.sessionId,this.setRPCSessionId(this.sessionId)),"syncRoom"===t&&(this.syncRoomLock=!1,this.retryQueue.length&&(this.retryQueue=this.retryQueue.filter((e=>"recover"!==e.method)),this.retryQueue.sort(((e,t)=>e.id-t.id)),J$1.each(this.retryQueue,(e=>{e.params.sessionId=this.sessionId,this.logger.info(`retry the retryQueue request, ${e.method}, params: ${JSON.stringify(e.params)}`),this.request(e.method,e.params).then((t=>{e.resolve(t)})).catch((t=>{e.reject(t)}))})),this.retryQueue=[])),e))).catch((e=>{var i;if("request timeout"!==Vt(e)&&this.resetTimeout(),99===(null==e?void 0:e.code))return this.sessionId&&this.sessionId!==r.sessionId?(this.logger.warn(`the request session has closed but the seesion is update after sync room, retry request again, ${t}, params: ${JSON.stringify(r)}`),r.sessionId=this.sessionId,this.request(t,r)):(this.syncRoomLock||(this.sessionId=null,this.syncRoomLock=!0,this.fire(H$1.SESSION_CLOED)),this.logger.warn(`the session has closed, push the request into retry queue, ${t}, params: ${JSON.stringify(r)}`),kt$1.warn("session closed, close socket to retry reconnect ws, and sync room"),null==(i=this.transport.socket)||i.close(),new Promise(((e,i)=>{this.retryQueue.push({method:t,params:r,resolve:e,reject:i,id:s})})));throw e})))}))}heartbeat(){this.request("ping",{sessionId:this.sessionId}).then((e=>{this.resetTimeout()})).catch((e=>{this.logger.error(`channel heartbeat error: ${JSON.stringify(e)}`)}))}destroy(){this.seq=null,this.notified=null,this.sessionId=null,this.retryQueue=null,this.syncRoomLock=null,this.resetTimer&&(clearTimeout(this.resetTimer),this.resetTimer=null),super.destroy()}getProxy(){return this.proxy}},mr={enableRace:!0,forceWS:!1,forceDC:!1,forceWT:!1},fe=class extends q$1{constructor(e,t,r={},i){super(!1),this.options=X$2.extend({},mr,t),this.closed=!1,this.icefull=!1,this.isConnecting=!1,this.connectCount=0,this.isLeaving=!1,this.rpc=r,this.proxies=e,this.logger=i||new m}getUrl(e){return e.activeUrl=e.url||e.dcurl||e.wturl,this.options.token&&(e.activeUrl+=`?token=${this.options.token}`),e.activeUrl}raceConnect(){return d(this,null,(function*(){let e=this.proxies;if(this.options.forceWS){let t=e.filter((e=>!!e.url));t.length&&(e=t)}this.connectingTimers={};let t=`.connecting${Math.random()}`;return new Promise(((r,i)=>{let s=!1;this.connectCount=0;let o=(e,o)=>{s?e.destroy():this.closed?(X$2.each(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.warn("signal open after call close function, reject"),i("signal has already closed")):(s=!0,X$2.each(this.connectingTimers,((e,t)=>{clearTimeout(e.timer),e.channel&&t!=o&&e.channel.destroy()})),this.connectingTimers={},e.off(t),this.connectCount=e.getTransportConnectCount(),r(e))},n=0,a=()=>{++n===e.length&&(X$2.each(this.connectingTimers,(e=>{e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.error("connect all proxies failed"),i("connect all proxies failed"))},d=(e,r)=>{let i=new ie(e,{maxRetry:5,transport:void 0,transportOptions:{},tag:"Client",logLevel:x$1},r,this.logger);i.one(P$1+t,(()=>{r.consume=i.getConsume(),this.connectCount=i.getTransportConnectCount(),o(i,e)})).one(O$1+t,(()=>{r.consume=i.getConsume(),this.connectCount=i.getTransportConnectCount(),o(i,e)})).one(_$1+t,(()=>{this.connectCount=i.getTransportConnectCount(),a()})).one(E$1+t,(()=>{this.connectCount=i.getTransportConnectCount(),a()})),this.connectingTimers[e].channel=i};J$1.each(e,(e=>{let t=e.delay?Tn(e.delay):0,r=this.getUrl(e);r&&(this.connectingTimers[r]={timer:setTimeout((()=>{d(r,e)}),t)})}))}))}))}queueConnect(){return d(this,null,(function*(){let e=this.proxies;if(this.options.forceWS){let t=e.filter((e=>!!e.url));t.length&&(e=t)}let t=`.connecting${Math.random()}`;return new Promise(((r,i)=>{let s=0;this.connectCount=0;let o=()=>{this.closed&&i("signal has closed");let n=e[s],a=this.getUrl(n);a||i("url can not be empty!");let d=this.connectingChannel=new ie(a,{maxRetry:3,transport:void 0,transportOptions:{},tag:"Client",logLevel:x$1},n,this.logger);d.one(P$1+t,(()=>{d.off(t),this.connectingChannel=void 0,n.consume=d.getConsume(),this.connectCount+=d.getTransportConnectCount(),r(d)})).one(O$1+t,(()=>{d.off(t),this.connectingChannel=void 0,n.consume=d.getConsume(),this.connectCount+=d.getTransportConnectCount(),r(d)})).one(_$1+t,(()=>{this.connectCount+=d.getTransportConnectCount(),d.destroy(),this.connectingChannel=void 0,this.logger.error(`queue connect proxy: ${s} ${a} error`),this.fire(H$1.STATE_NOTIFY,[{level:this.logger.ERROR,msg:`queue connect proxy: ${s} ${a} error`}]),s++,s>=e.length?(this.logger.error("connect all proxies failed"),s=0,i("connect all proxies failed")):setTimeout((()=>{o()}),1e3)})).one(E$1+t,(()=>{this.connectCount+=d.getTransportConnectCount(),d.destroy(),this.connectingChannel=void 0,this.logger.error(`queue connect proxy: ${s} ${a} timeout`),this.fire(H$1.STATE_NOTIFY,[{level:this.logger.ERROR,msg:`queue connect proxy: ${s} ${a} timeout`}]),s++,s>=e.length?(this.logger.error("connect all proxies failed"),s=0,i("connect all proxies failed")):setTimeout((()=>{o()}),1e3)}))};o()}))}))}connect(){return d(this,null,(function*(){if(!this.proxies.length)return new Error("not has any proxy to connect");this.isConnecting=!0,this.options.enableRace?this.channel=yield this.raceConnect():this.channel=yield this.queueConnect(),this.channel.on(_$1,(()=>{this.logger.error(`proxy connect error, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(_$1)})).on($,(()=>{this.logger.error(`proxy connect close, proxy: ${JSON.stringify(this.getProxy())}`),this.fire($)})).on(E$1,(()=>{this.logger.error(`proxy connect timeout, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(E$1)})).on(P$1,(()=>{this.fire(P$1)})).on(B,(()=>{this.fire(B)})).on(O$1,(()=>{if(this.isLeaving)return;this.fire(O$1),this.channel.syncNotify();let e=this.channel.getProxy();e&&(e.consume=this.channel.getConsume())})).on(k$1,((e,t,r)=>{this.channel.notified=r,this.channel.resetTimeout(),xe$1[e]?this.fire(xe$1[e],[t]):this.fire(k$1,[{method:e,params:t}])})).on(W,(e=>d(this,null,(function*(){if(e.method&&this.rpc[e.method]){this.channel.resetTimeout();let{error:t,result:r}=yield this.rpc[e.method](e);this.channel.reply(e,r,t)}})))).on(H$1.SESSION_CLOED,(()=>{this.fire(H$1.SESSION_CLOED)})),this.isConnecting=!1,this.logger.info(`connect proxy success, proxy: ${JSON.stringify(this.channel.getProxy())}`)}))}request(e,t){return d(this,null,(function*(){return this.channel.request(e,t)}))}join(e){return d(this,null,(function*(){return this.channel.request("joinRoom",e).then((e=>(this.channel.resetTimeout(),this.isLeaving=!1,e)))}))}leave(e){return d(this,null,(function*(){return this.isLeaving=!0,this.channel.request("leaveRoom",e,{timeout:3e3}).then((e=>(this.isLeaving=!1,e)))}))}syncRoom(e,t,r){return d(this,null,(function*(){return this.channel.request("syncRoom",{roomId:e,userId:t,info:r})}))}updateCustomStats(e,t,r,i){return d(this,null,(function*(){return this.channel.request("updateCustomStats",{roomId:e,userId:t,options:r.customStats,replace:i})}))}updateStream(e,t,r){return d(this,null,(function*(){return this.channel.request("updateStream",nt({userId:e,streamId:t},r))}))}releaseRoom(e,t){return d(this,null,(function*(){return this.channel.request("releaseRoom",{roomId:e,userId:t})}))}updateRoom(e,t,r){return d(this,null,(function*(){return this.channel.request("updateRoom",{roomId:e,userId:t,options:r})}))}updateUser(e,t,r){return d(this,null,(function*(){return this.channel.request("updateUser",{roomId:e,userId:t,info:r})}))}evictUser(e,t,r,i){return d(this,null,(function*(){return this.channel.request("evictUser",{roomId:e,userId:t,evictId:r,withoutBlack:i})}))}changeMaster(e,t,r,i){return d(this,null,(function*(){return this.channel.request("changeMaster",{roomId:e,userId:t,master:r,isKeep:i})}))}leaveRoom(e,t,r){return d(this,null,(function*(){return this.channel.request("leaveRoom",{roomId:e,userId:t,desc:r})}))}getUsers(e,t,r,i,s,o){return d(this,null,(function*(){return this.channel.request("getUsers",{roomId:e,userId:t,pagesize:r,index:i,permission:s,waitRoom:o})}))}getUsersList(e,t,r,i){return d(this,null,(function*(){return this.channel.request("getUserList",{pagesize:t,index:e,permission:r,waitRoom:i})}))}queryUsers(e){return d(this,null,(function*(){return this.channel.request("queryUsers",{userIds:e})}))}publishStream(e,t,r,i){return d(this,null,(function*(){return this.channel.request("publishStream",{roomId:e,userId:t,streamId:r,options:i})}))}controlStream(e,t,r,i){return d(this,null,(function*(){return this.channel.request("controlStream",{roomId:e,userId:t,streamId:r,options:i})}))}resetStream(e,t,r,i){return d(this,null,(function*(){return this.channel.request("resetStream",{roomId:e,userId:t,streamId:r,options:i})}))}unpublishStream(e,t,r){return d(this,null,(function*(){return this.channel.request("unpublishStream",{roomId:e,userId:t,streamId:r})}))}getMessages(e,t,r){return d(this,null,(function*(){return this.channel.request("getMessages",{roomId:e,userId:t})}))}sendMessage(e,t,r,i){return d(this,null,(function*(){return this.channel.request("sendMessage",{roomId:e,userId:t,to:r,msg:i})}))}customMessage(e,t,r,i){return d(this,null,(function*(){return this.channel.request("customMessage",{roomId:e,userId:t,to:r,msg:i})}))}startRecord(e,t,r){return d(this,null,(function*(){return this.channel.request("startRecord",{roomId:e,streamId:t,options:r})}))}stopRecord(e,t){return d(this,null,(function*(){return this.channel.request("stopRecord",{roomId:e,streamId:t})}))}searchUsers(e,t,r){return d(this,null,(function*(){return this.channel.request("searchUsers",{nickname:e,pageSize:t,waitRoom:r})}))}syncUser(e){return d(this,null,(function*(){return this.channel.request("syncUser",{pageSize:e})}))}moveUserRoom(e,t,r){return d(this,null,(function*(){return this.channel.request("moveUserRoom",{target:e,toWait:t,autoJoin:r})}))}close(){this.connectingChannel&&this.connectingChannel.destroy(),X$2.keys(this.connectingTimers).length&&(X$2.each(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={}),this.channel&&this.channel.destroy(),this.closed=!0,this.off()}getSessionId(){var e;return null==(e=this.channel)?void 0:e.sessionId}getProxy(){var e;return null==(e=this.channel)?void 0:e.getProxy()}getConnectCount(){return this.connectCount}getConnectedProxyConsume(){var e;return null==(e=this.channel)?void 0:e.getConsume()}},We=()=>{let e=Te(),t="none";return null!==e.match("fake")?t="fake":null!==e.match("ios")?t="ios":null!==e.match("android")?t="android":null!==e.match("Firefox")?t="mozilla":null!==e.match("Chrome")?(t="chrome-stable",null!==e.match("Electron")&&(t="electron")):(null!==e.match("Safari")||null!==e.match("AppleWebKit"))&&(t="safari"),t},Te=()=>window.navigator.userAgent,Re=class e{constructor(t){this.permission=t||e.default}getRead(){return this.permission.indexOf("R")>=0}getWrite(){return this.permission.indexOf("W")>=0}getPublish(){return this.permission.indexOf("P")>=0}getSubscribe(){return this.permission.indexOf("S")>=0}getManage(){return this.permission.indexOf("M")>=0}getAudio(){return this.permission.indexOf("A")>=0}getVideo(){return this.permission.indexOf("V")>=0}getOwn(){return this.permission.indexOf("O")>=0}setManage(e){this._update("M",e)}setSubscribe(e){this._update("S",e)}setPublish(e){this._update("P",e)}setWrite(e){this._update("W",e)}setRead(e){this._update("R",e)}setAudio(e){this._update("A",e)}setVideo(e){this._update("V",e)}setOwn(e){this._update("O",e)}set(e){this.permission=e}get(){return this.permission}_update(e,t){t?this.permission.indexOf(e)<0&&(this.permission+=e):this.permission=this.permission.replace(e,"")}};Re.default="RWPSAV";var Fe=Re,A$1=class{constructor(e,t,r){this.streams=new Map,this.local=e,this.userId=t,this.params=r;let i=r.permission;!i&&r.info&&(i=r.info.permission),i||(i=Fe.default),this.permission=new Fe(i)}setID(e){this.userId=e}getID(){return this.userId}getPermission(){return this.permission}getUserInfo(){var e,t;return null!=(t=null!=(e=this.params.userinfo)?e:this.params.info.userinfo)?t:{}}update(e){e.permission&&this.permission.set(e.permission),this.params=pr(e,this.params)}getNickName(){var e,t;return null!=(t=null!=(e=this.params.nickname)?e:this.params.info.nickname)?t:""}getStreams(){return this.streams}getStream(e){return this.streams.get(e)}addStream(e){this.streams.set(e.getID(),e)}removeStream(e){this.streams.delete(e)}},fr=()=>{let e;try{e=be("react-native").Platform}catch(e){}let t="none";return"undefined"!=typeof module&&module.exports?e?"ios"===e.OS?t="ios":"android"===e.OS&&(t="android"):t="fake":t=window.navigator.userAgent,t},gr=()=>{let e;try{e=be("react-native").Platform}catch(e){}let t=!1;return"undefined"!=typeof module&&module.exports&&e&&("ios"===e.OS||"android"===e.OS)&&(t=!0),t},vr=()=>!1,yr={userAgent:fr,isMobile:gr,isElectron:vr},T$1=yr,je={};Bt(je,{CHROME:()=>V$1,ELECTRON:()=>Le,FIREFOX:()=>Ie,INTERNET_EXPLORER:()=>Ce,NWJS:()=>_e,OPERA:()=>Ee,REACT_NATIVE:()=>xe,SAFARI:()=>Oe,UNKNOWN:()=>ge,WECHAT:()=>Me});var V$1="chrome",Ee="opera",Ie="firefox",Ce="iexplorer",Oe="safari",_e="nwjs",Le="electron",xe="react-native",ge="unknown",Me="wechat",ke={Chrome:V$1,Chromium:V$1,Opera:Ee,Firefox:Ie,"Internet Explorer":Ce,Safari:Oe,WeChat:Me},K$1=navigator.userAgent;function Sr(){let e=K$1,t={name:ge,version:void 0};if(e.match(/Chrome/)&&!e.match(/Edge/))if(e.match(/Edg/)){let r=e.match(/Edg\/([\d.]+)/)[1];Number.parseInt(r,10)>72&&(t.name=V$1,t.version=r)}else t.name=V$1,t.version=e.match(/Chrome\/([\d.]+)/)[1];return t}function Tr(){let e=K$1;if(e.match(/Electron/)){let t=e.match(/Electron\/([\d.]+)/)[1];return{name:Le,version:t}}}function Rr(){let e=K$1;if(e.match(/JitsiMeetNW/)){let t=e.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:_e,version:t}}}function Er(){let e=K$1;if(e.match(/MicroMessenger/)){let t=e.match(/MicroMessenger\/([\d.]+)/)[1];return{name:Me,version:t}}}function Ir(){let e,t=K$1.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);if(t||"ReactNative"===navigator.product)return t&&t.length>2&&(e=t[2]),e||(e="unknown"),{name:xe,version:e}}function Cr(e){let t,r=[Ir,Tr,Rr,Er];for(let e=0;e<r.length;e++)if(t=r[e](),t)return t;let i=e.getBrowserName();return i in ke?{name:ke[i],version:e.getBrowserVersion()}:(t=Sr(),t||{name:ge,version:void 0})}navigator.userAgent||(K$1=navigator.product);var H=class{constructor(e){let t,r;if(this.browsers=je,this._bowser=Bowser.getParser(K$1),void 0===e){let e=Cr(this._bowser);t=e.name,r=e.version}else e.name in ke?(t=ke[e.name],r=e.version):(t=ge,r=void 0);this._name=t,this._version=r}getName(){return this._name}isChrome(){return this._name===V$1}isOpera(){return this._name===Ee}isFirefox(){return this._name===Ie}isIExplorer(){return this._name===Ce}isSafari(){return this._name===Oe}isNWJS(){return this._name===_e}isElectron(){return this._name===Le}isReactNative(){return this._name===xe}getVersion(){return this._version}_checkCondition(e){if(this._version)return this._bowser.satisfies(e)}isVersionGreaterThan(e){return this._checkCondition({[this._name]:`>${e}`})}isVersionLessThan(e){return this._checkCondition({[this._name]:`<${e}`})}isVersionEqualTo(e){return this._checkCondition({[this._name]:`~${e}`})}},Or=()=>{let e;try{e=be("react-native-webrtc").mediaDevices}catch(t){e=navigator.mediaDevices}return e},_r=()=>{let e;try{e=be("react-native-webrtc").RTCPeerConnection}catch(t){e=RTCPeerConnection}return e},Lr={mediaDevices:Or,PRTCPeerConnection:_r},Rt=Lr,R=m.Log(),Et=()=>{let e="none";return null!==T$1.userAgent().match("fake")?e="fake":null!==T$1.userAgent().match("ios")?e="ios":null!==T$1.userAgent().match("android")?e="android":null!==T$1.userAgent().match("Firefox")?e="mozilla":null!==T$1.userAgent().match("Chrome")?(e="chrome-stable",null!==T$1.userAgent().match("Electron")&&(e="electron")):(null!==T$1.userAgent().match("Safari")||null!==T$1.userAgent().match("AppleWebKit"))&&(e="safari"),e},xr=()=>window.navigator.userAgent,Mr=(e,t=(()=>{}),r=(()=>{}))=>{let i,s=Rt.mediaDevices(),o=(e,t,r)=>{s.getUserMedia(e).then(t).catch(r)};e.screen?(()=>{switch(R.debug("Screen access requested"),Et()){case"electron":R.debug("Screen sharing in Electron"),i={},i.video=e.video||{},i.video.mandatory=e.video.mandatory||{},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=e.desktopStreamId,o(i,t,r);break;case"mozilla":case"mozilla":R.debug("Screen sharing in Firefox"),i={},void 0!==e.video?(i.video=e.video,i.video.mediaSource||(i.video.mediaSource="window")):i={audio:e.audio,video:{mediaSource:"window"}},o(i,t,r);break;case"chrome-stable":R.debug("Screen sharing in Chrome"),i={},e.desktopStreamId&&(i.video=e.video||{mandatory:{}},i.video.mandatory=i.video.mandatory||{},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=e.desktopStreamId,o(i,t,r));break;case"chrome-stable":if(R.debug("Screen sharing in Chrome"),i={},e.desktopStreamId)i.video=e.video||{mandatory:{}},i.video.mandatory=i.video.mandatory||{},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=e.desktopStreamId,o(i,t,r);else{let s="jbglfdfehfdcpnbhfnciaiokkfocjcjk";e.extensionId&&(R.debug(`extensionId supplied, using ${e.extensionId}`),s=e.extensionId),R.debug("Screen access on chrome stable, looking for extension");try{chrome.runtime.sendMessage(s,{getStream:!0},(s=>{if(void 0===s)return R.error("Access to screen denied"),void r({code:"Access to screen denied"});let n=s.streamId;void 0!==e.video.mandatory?(i.video=e.video||{mandatory:{}},i.video.mandatory.chromeMediaSource="desktop",i.video.mandatory.chromeMediaSourceId=n):i={video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n}}},o(i,t,r)}))}catch(e){R.debug("Screensharing plugin is not accessible "),r({code:"no_plugin_present"})}}break;default:R.error("This browser does not support ScreenSharing")}})():(R.debug("Calling getUserMedia with config",e),o(e,t,r))};function kr(e,t){if(!t)return e;let r=e.getVideoTracks()[0];if(!r||"function"!=typeof r.getCapabilities)return e;let i=r.getConstraints(),s=e.clone();return r=s.getVideoTracks()[0],r?(e.getTracks().forEach((e=>e.stop())),i.width,i.height,i.frameRate=t||i.frameRate,r.applyConstraints(i),s):(s.getTracks().forEach((e=>e.stop())),e)}var wr=e=>new Promise(((t,r)=>{Mr(e,(r=>{(new H).isReactNative()&&t(r),e.fps&&r.clone?t(kr(r,e.fps)):t(r)}),(e=>{r(e)}))})),Nr={GetUserMedia:wr,getBrowser:Et,getUserAgent:xr},It=Nr,Dr={ERR_NOT_INSTALLED:1,ERR_NOT_FOUND:10,ERR_TIMEOUT:11,ERR_STATS:12,ERR_NO_SERVICE:13,ERR_AUTH:14,ERR_INVALID_REQUEST:15,ERR_METHOD:16,ERR_NOT_STARTUP:17,ERR_CUSTOM_AUTH_FAILED:18,ERR_USER_LIMIT:19,ERR_QDTLS:20,ERR_OVEVLOAD:21,ERR_EVICTED:22,ERR_PERMISSION:23,ERR_SENSITIVE_WORD:24,ERR_NOT_AT_ROOM:25,ERR_MEDIA_PIPELINE:26,ERR_NO_STREAM:27,ERR_LOCKED:28,ERR_UNKNOWN:33},we=Dr,Ge=class{constructor(){this._stream=null,this.avaliable=!0}check(){return new Promise(((e,t)=>{chrome.runtime.sendMessage({check:!0},(r=>{""!=r.id&&null!=r.id?e(r.id):t("not plugin")}))}))}detect(e){return new Promise(((t,r)=>{var i=document.createElement("img");i.src="chrome-extension://"+e+"/icon.png",i.onload=function(){t()},i.onerror=function(){r({code:we.ERR_NOT_INSTALLED,error:"not-installed"})}}))}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this,r=e.extensionId||"jbglfdfehfdcpnbhfnciaiokkfocjcjk";return this.detect(r).then((()=>new Promise(((i,s)=>{chrome.runtime.sendMessage(r,{getStream:!0},(r=>{if(void 0===r){return m.Log().error("Access to screen denied"),void error({code:"Access to screen denied"})}let o=t._toConstraints(e,r.streamId);It.GetUserMedia(o).then((e=>{t._stream=e,i(t._stream)})).catch((e=>{s(e)}))}))})))).catch((e=>{m.Log().warn("onerror plugin"),reject(e)}))}stop(){this._stream instanceof MediaStream&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return this.avaliable}needExtension(){return!this.avaliable}_toConstraints(e,t){let r={video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t},optional:[{googTemporalLayeredScreencast:!0}]},audio:!1};return isFinite(e.width)&&(r.video.mandatory.maxWidth=e.width,r.video.mandatory.minWidth=e.width),isFinite(e.height)&&(r.video.mandatory.maxHeight=e.height,r.video.mandatory.minHeight=e.height),isFinite(e.frameRate)&&(r.video.mandatory.maxFrameRate=e.frameRate,r.video.mandatory.minFrameRate=e.frameRate),r}},Je=class{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this._toConstraints(e);return navigator.mediaDevices.getDisplayMedia(t).then((e=>(this._stream=e,Promise.resolve(this._stream))))}stop(){this._stream instanceof MediaStream&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){return{video:{frameRate:e.fps},audio:e.audio||!1}}},Ve=class{constructor(){this._stream=null}start(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=this._toConstraints(t),i="boolean"==typeof t.audio&&t.audio;"boolean"==typeof t.isRecord&&t.isRecord,"boolean"==typeof t.isLocalProjection&&t.isLocalProjection;try{e=window.require("electron")}catch(t){e=window.parent.require("electron")}let s,o={types:["window","screen"]};if(e)s=e.desktopCapturer?e.desktopCapturer.getSources(o):e.ipcRenderer.invoke("desktopCapturer:getSources",o);else{let e;e=window.electronAPI?window.electronAPI.desktopCapturerGetSources(o):window.parent.electronAPI.desktopCapturerGetSources(o),s=e}let n=e=>{e.id.startsWith("window");let t=!!i&&{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id,echoCancellation:!0}};return navigator.mediaDevices.getUserMedia({audio:t,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id,minWidth:r.video.mandatory.minWidth,maxWidth:r.video.mandatory.maxWidth,minHeight:r.video.mandatory.minHeight,maxHeight:r.video.mandatory.maxHeight,minFrameRate:r.video.mandatory.minFrameRate,maxFrameRate:r.video.mandatory.maxFrameRate}}}).then((t=>(console.log("ElectronScreenShare:",e.id),this._stream=t,t)))};return s.then((e=>d(this,null,(function*(){console.log("---share name selected:"+t.source_name,t.chromeMediaSourceId);let r=e.find((e=>e.id===t.chromeMediaSourceId));if(r)return n(r);for(let r of e)if(t.source_name===r.name){try{return n(r)}catch(e){console.log("ElectronScreenShare.start.error:",e)}break}if(t.chromeMediaSourceId){let e={id:t.chromeMediaSourceId};return n(e)}return null})))).catch((e=>(console.error("ElectronScreenShare:error",e),Promise.reject(e))))}stop(){this._stream instanceof MediaStream&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){let t={video:{frameRate:e.fps,mandatory:{maxWidth:e.width,minWidth:e.width,maxHeight:e.height,minHeight:e.height}},audio:!1};return m.Log().log("====fps:",e.fps),isFinite(e.width)&&(t.video.mandatory.maxWidth=e.width,t.video.mandatory.minWidth=e.width),isFinite(e.height)&&(t.video.mandatory.minHeight=e.height,t.video.mandatory.maxHeight=e.height),isFinite(e.fps)&&(t.video.mandatory.minFrameRate=e.fps,t.video.mandatory.maxFrameRate=e.fps),void 0===e.width&&(t.video.mandatory.maxWidth=1920,t.video.mandatory.minWidth=1920),void 0===e.height&&(t.video.mandatory.maxHeight=1080,t.video.mandatory.minHeight=1080),void 0===e.fps&&(t.video.mandatory.minFrameRate=15,t.video.mandatory.maxFrameRate=15),t}},z$1,He=class{static create(){if(z$1)return z$1;let e;e=T$1.isMobile()?T$1.userAgent():navigator.userAgent;let t,r=e,i=Bowser.getParser(r),s=i.getEngine();try{t=s.name.toLowerCase()}catch(e){}return(new H).isElectron()?(console.log("===========Client============="),z$1=new Ve):(console.log("===========Browser============="),i.satisfies({chrome:">=72",chromium:">=72"})?z$1=new Je:i.satisfies({chrome:">=55",chromium:">=55"})&&(z$1=new Ge),z$1)}},Ne=He,Ur=Ne.create();m.Log();var U=class{constructor(e,t,r,i,s){this.published=!1,this.audio=s.audio,this.video=s.video,this.audio_enable=s.audio_enable,this.video_enable=s.video_enable,this.screen=s.screen,this.client=e,this.room=t,this.participant=r,this.local=i,this.options=s,this.id=s.id,this.customInfo=s.customInfo,this.roomId=t.getID(),this.userId=r.getID()}audioEnabled(){return this.audio_enable}videoEnabled(){return this.video_enable}setAudioEnabled(e){return this.client.controlStream(this.roomId,this.userId,this.id,{audio_enable:e}).then((()=>{this.audio_enable=e}))}setVideoEnabled(e){return this.client.controlStream(this.roomId,this.userId,this.id,{video_enable:e}).then((()=>{this.video_enable=e}))}isLocal(){return this.local}getID(){return this.id}getParticipant(){return this.participant}publish(e){return d(this,null,(function*(){var t,r;this.audio_enable=null!=(t=e.audio_enable)?t:this.audio_enable,this.video_enable=null!=(r=e.video_enable)?r:this.video_enable,yield this.client.publishStream(this.roomId,this.userId,this.id,{audio_enable:this.audio_enable,video_enable:this.video_enable,video:this.video,audio:this.audio}),this.participant.addStream(this),this.published=!0}))}unpublish(){return d(this,null,(function*(){yield this.client.unpublishStream(this.roomId,this.userId,this.id),this.participant.removeStream(this.getID()),this.published=!1}))}static sharing(){return Ur}},Pr=2,Ct=1,$r=0,Ot=400,Br=15e3,_t=400,Ke=1,Wr=2,Q$1=127,b$1=0,Fr=75,ve=1e-10,jr=10,Gr=3,Ye=15,Lt=(Q$1-b$1+Ye-1)/Ye,xt=5,ze=5,Jr=36e5,Mt=2e3,kt=`.speakerDetector${Math.random()}`;function Vr(e,t){let r=e-t;t<r&&(t=r);let i=1;for(let r=e,s=1;r>t;r--,s++)i=Math.floor(i*r/s);return i}function wt(e,t,r){let i=t.length,s=Math.floor(e.length/i),o=!1;for(let n=0,a=0;n<i;n++){let i=0;for(let t=a+s;a<t;a++)e[a]>r&&i++;t[n]!=i&&(t[n]=i,o=!0)}return o}function Qe(e,t,r,i){let s=Math.log(Vr(t,e))+e*Math.log(r)+(t-e)*Math.log(1-r)-Math.log(i)+i*e;return s<ve&&(s=ve),s}var Xe=class{constructor(e){this.stream=e,this.immediates=new Array(Ke*ze*xt),this.immediateSpeechActivityScore=ve,this.lastLevelChangedTime=(new Date).getTime(),this.levels=new Array(this.immediates.length),this.longs=new Array(Ke),this.longSpeechActivityScore=ve,this.mediums=new Array(Ke*ze),this.mediumSpeechActivityScore=ve,this.minLevel=b$1,this.nextMinLevel=b$1,this.nextMinLevelWindowLength=void 0,this.lastActiveTime=this.lastLevelChangedTime-Mt-1}getStream(){return this.stream}getID(){return this.stream.getID()}computeImmediates(){let e=this.immediates,t=this.levels,r=Math.floor(this.minLevel+Lt),i=!1;for(let s=0;s<e.length;++s){let o=t[s];o<r&&(o=b$1);let n=Math.floor(o/Lt);e[s]!=n&&(e[s]=n,i=!0)}return i}computeLongs(){return wt(this.mediums,this.longs,Wr)}computeMediums(){return wt(this.immediates,this.mediums,Gr)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=Qe(this.immediates[0],Ye,.5,.78)}evaluateLongSpeechActivityScore(){this.longSpeechActivityScore=Qe(this.longs[0],ze,.5,47)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=Qe(this.mediums[0],xt,.5,24)}evaluateSpeechActivityScores(){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore()))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){let e=this.levels,t=new Array(e.length);for(let r=e.length-1,i=0;i<t.length;--r,++i)t[i]=e[r];return t}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;default:return this.longSpeechActivityScore}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){let r;this.lastLevelChangedTime=t,r=e<b$1?b$1:e>Q$1?Q$1:e;for(let e=this.levels.length-1;e>0;--e)this.levels[e]=this.levels[e-1];this.levels[0]=r,this.updateMinLevel(r)}e>jr&&(this.lastActiveTime=(new Date).getTime())}levelTimeout(){this.levelChanged(b$1,this.lastLevelChangedTime)}updateMinLevel(e){if(e!=b$1){if(this.minLevel==b$1||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=b$1,void(this.nextMinLevelWindowLength=0);if(this.nextMinLevel==b$1)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=Fr){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<b$1?e=b$1:e>Q$1&&(e=Q$1),this.minLevel=e,this.nextMinLevel=b$1,this.nextMinLevelWindowLength=0}}}getSilent(){return(new Date).getTime()-this.lastActiveTime>Mt}},Ze=class{constructor(e){this.algorithm=e}run(){let e=this.algorithm.runInDecisionMaker(this);e<0?this.algorithm.decisionMakerExited(this):setTimeout((()=>{this.run()}),e)}},et=class extends events.EventEmitter{constructor(){super(),this.decisionMaker=void 0,this.dominant=void 0,this.lastDecisionTime=0,this.lastLevelChangedTime=0,this.lastLevelIdleTime=0,this.relativeSpeechActivities=[0,0,0],this.speakers=new Map}addStream(e){e&&e.stream?e.stream.on("audio-level"+kt,this.levelChanged.bind(this,e)):console.warn("add stream error")}removeStream(e){e&&e.stream&&e.stream.off(kt),this.speakers.delete(e.getID())}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new Ze(this),this.decisionMaker.run())}decisionMakerExited(e){e==this.decisionMaker&&(this.decisionMaker=void 0)}getDominantSpeaker(){let e=this.speakers.get(this.dominant);if(e)return e.getStream()}getOrCreateSpeaker(e){let t=e.getID(),r=this.speakers.get(t);return r||(r=new Xe(e),this.speakers.set(t,r),this.maybeStartDecisionMaker()),r}levelChanged(e,t){t=Math.min(t*Q$1*2,Q$1);let r=this.getOrCreateSpeaker(e),i=(new Date).getTime();this.lastLevelChangedTime<i&&(this.lastLevelChangedTime=i,this.maybeStartDecisionMaker()),r.levelChanged(t,i)}decisionChoice(){let e=this.speakers.get(this.dominant),t="";e||(e=this.speakers.entries().next().value[1],t=e.getID()),e.evaluateSpeechActivityScores();let r=this.relativeSpeechActivities,i=Ct;for(let[s,o]of this.speakers){if(o==e)continue;o.evaluateSpeechActivityScores();for(let t=0;t<r.length;++t)r[t]=Math.log(o.getSpeechActivityScore(t)/e.getSpeechActivityScore(t));let n=r[0],a=r[1],d=r[2];n>Pr&&a>Ct&&d>$r&&a>i&&(i=a,t=s)}return t}makeDecision(){let e;if(0!=this.speakers.size&&(e=this.decisionChoice()),e&&e!=this.dominant){this.dominant=e;let t=this.speakers.get(this.dominant);t&&!t.getSilent()?this.emit("speaker",t.getStream()):(this.emit("speaker"),this.dominant=void 0)}else if(this.dominant){let e=this.speakers.get(this.dominant);(e&&e.getSilent()||!e)&&(this.dominant=void 0,this.emit("speaker"))}}runInDecisionMaker(e){if(e&&e!=this.decisionMaker||0<this.lastDecisionTime&&this.lastDecisionTime-this.lastLevelChangedTime>=Br)return-1;let t=(new Date).getTime(),r=_t-(t-this.lastLevelIdleTime),i=0;r<=0?(0!=this.lastLevelIdleTime&&this.timeoutIdleLevels(t),this.lastLevelIdleTime=t):i=r;let s=Ot-(t-this.lastDecisionTime);return s<=0&&(this.lastDecisionTime=t,this.makeDecision(),s=Ot-((new Date).getTime()-t)),s>0&&i>s&&(i=s),i}timeoutIdleLevels(e){for(let[t,r]of this.speakers){let i=e-r.getLastLevelChangedTime();Jr<i&&(!this.dominant||r.getID()!=this.dominant)?this.speakers.delete(t):_t<i&&r.levelTimeout()}}},Nt=et,De=class extends events.EventEmitter{constructor(){super(),this._recording=!1}start(e,t){}stop(){}exportRecordedData(){}setMuted(e){}setMicDevice(e){}_getAudioStream(){return navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}isRecording(){return this._recording}},zr=Ne.create(),ye=class extends De{constructor(){super(),this._trackSources=new Map,this._stream=null,this._recordedData=[]}start(e,t){return this._createDesktopStream(t.capture).then((r=>d(this,null,(function*(){try{return this._getMixedAudioTrack(e).then((e=>{e&&(r.addTrack(e),this._stream=r,this._mediaRecorder=this._newMediaRecorder(r,t.record),this._mediaRecorder.ondataavailable=e=>this._saveMediaData(e.data),this._mediaRecorder.start(1e3),this._recording=!0,this.emit("started"))}))}catch(e){throw m.Log().error(circularJson_node.stringify(e)),this._localAudioTrack&&this._localAudioTrack.stop(),r.getTracks().forEach((e=>e.stop())),e}}))))}stop(){return new Promise(((e,t)=>{this._mediaRecorder?(this._mediaRecorder.onstop=e,this._mediaRecorder.stop(),this._mediaRecorder=null,this._localAudioTrack&&(this._localAudioTrack.stop(),this._localAudioStream=null),this._stream&&this._stream.getTracks().forEach((e=>e.stop())),this._trackSources&&(this._trackSources.forEach((e=>e.disconnect(this._audioContextDest))),this._trackSources.clear()),this._recording=!1,this.emit("stopped")):t()}))}exportRecordedData(){return this._recordedData?Promise.resolve({data:this._recordedData,format:"mp4"}):Promise.reject("No video data recorded.")}setMuted(e){this._localAudioTrack&&(this._localAudioTrack.enabled=!e)}setMicDevice(e){return d(this,null,(function*(){if(this._localAudioTrack)try{return this.disconnectTrack(this._localAudioTrack),this._localAudioTrack.stop(),this._getLocalAudioTrack(e).then((e=>{this.connectTrack(e)}))}catch(e){return Promise.reject()}return Promise.reject()}))}_saveMediaData(e){console.log("save media data..., size:",e.size),this._recordedData.push(e)}_createDesktopStream(e){return zr.start(e).then((e=>{let t=e.getVideoTracks()[0];return t&&(t.onended=()=>{this.emit("track-ended")}),e}))}_newMediaRecorder(e,t){let r={bitsPerSecond:(t=t||{}).bitrate?t.bitrate:3e6};if(MediaRecorder.isTypeSupported(t.format))r.mimeType=t.format;else{let e=["video/mp4;codecs=h264","video/mp4;codecs=vp9","video/mp4;codecs=vp8"];for(let t of e)if(MediaRecorder.isTypeSupported(t)){r.mimeType=t;break}}return new MediaRecorder(e,r)}_getLocalAudioTrack(e){return this._getAudioStream().then((e=>{this._localAudioStream=e;let t=this._localAudioStream.getAudioTracks()[0];return this._localAudioTrack=t,t}))}_getMixedAudioTrack(e){return this._getLocalAudioTrack(e).then((()=>{if(this._localAudioStream){let e=new AudioContext,t=e.createMediaStreamSource(this._localAudioStream),r=e.createMediaStreamDestination();return t.connect(r),this._audioContext=e,this._audioContextDest=r,this._trackSources.set(this._localAudioTrack,t),r.stream.getAudioTracks()[0]}}))}connectTrack(e){let t=this._audioContext.createMediaStreamSource(new MediaStream([e]));null==t||t.connect(this._audioContextDest),this._trackSources.set(e,t)}disconnectTrack(e){let t=this._trackSources.get(e);t&&(t.disconnect(this._audioContextDest),this._trackSources.delete(e))}},tt=class extends events.EventEmitter{constructor(e){super(),this._opts=e,this._filename=e.filename,this._adapter=new ye,this._adapter.on("started",this.emit.bind(this,"started")),this._adapter.on("stopped",this.emit.bind(this,"stopped")),this._adapter.on("track-ended",this.emit.bind(this,"track-ended"))}downloadBlob(e,t="recording.webm"){let r=new Blob(e),i=window.URL.createObjectURL(r),s=document.createElement("a");s.style.display="none",s.href=i,s.download=t,document.body.appendChild(s),console.log("a tag to save recorded data..."),s.click(),setTimeout((function(){document.body.removeChild(s),window.URL.revokeObjectURL(i)}),1e3)}start(){return this._adapter.start("0",this._opts)}stop(){return this._adapter.stop().then((()=>(console.log("export recorded data..."),this._adapter.exportRecordedData()))).then((e=>{let{data:t,format:r}=e;console.log("download recorded data..."),this.downloadBlob(t,this._filename)}))}muteAudio(e){this._adapter.isRecording()&&this._adapter.setMuted(e)}addStream(e){let t=e&&e.getAudioTrack();t&&this._adapter.isRecording()&&this._adapter.connectTrack(t)}removeStream(e){let t=e.getAudioTrack();t&&this._adapter.isRecording()&&this._adapter.disconnectTrack(t)}addEventListener(e,t){this.addListener(e,t)}on(e,t){return this.addListener(e,t),this}},Dt=tt,ei={enableRace:!1},Ae=class extends q$1{constructor(e){var t;super(!0),this.switch=!1,this.audiooff=!1,this.selfopenaudio=!0,this.videooff=!1,this.msgoff=!1,this.creator="",this.master="",this.lock=!1,this.getUsersList=(e,t,r,i)=>this.client.getUsersList(e,t,r,i).then((e=>{let t=e.value;return{participants:this.parseGetUser(t),total:e.total,pageIndex:e.index}})),this.searchUsers=(e,t,r)=>this.client.searchUsers(e,t,r).then((e=>{let t=e.value;return{participants:this.parseGetUser(t)}})),this.queryUsers=e=>this.client.queryUsers(e).then((e=>{let t=e.value;return{participants:this.parseGetUser(t)}})),this.options=X$2.extend({},ei,e),this.joined=!1,this.logger=m.Log(),this.roomId=e.room,this.userId=e.user,this.hasSecret=!!this.options.secret,this.connectopts={nickname:this.options.nickname,custom_token:this.options.custom_token,userinfo:this.options.userinfo},this.create=null==(t=e.create)||t,this.nickname=e.nickname,this.localParticipant=new A$1(!0,this.userId,e)}connect(){return d(this,null,(function*(){this.client=new fe(this.options.proxies,{forceWS:this.options.forceWS,enableRace:this.options.enableRace,token:this.options.token},this.getRpc(),this.logger),this.handleEvents(),yield this.client.connect();try{let e=yield this.client.join({roomId:this.roomId,userId:this.userId,info:this.getJoinUserInfo(this.options.userinfo)});this.joined=!0,this.logger.info(`joined: sessionId: ${e.sessionId}, callId: ${e.raw.callId}`);let t=this.parseJoinResponse(e);this.fire(H$1.ROOM_CONNECTED,[t])}catch(e){throw this.logger.error(`join room failed: ${Vt(e)}, proxy: ${JSON.stringify(this.getActiveProxy())}`),this.client.close(),e}}))}leave(){return d(this,null,(function*(){var e;this.client&&(this.logger.info(`leaved: sessionId: ${(null==(e=this.client)?void 0:e.getSessionId())||""}`),yield this.client.leave({roomId:this.roomId,userId:this.userId,sessionId:this.client.getSessionId()||""}),this.client.close(),this.client=void 0,this.joined=!1)}))}request(e,t){return d(this,null,(function*(){var r;return null==(r=this.client)?void 0:r.request(e,t)}))}handleEvents(){this.client.on(_$1,(()=>{this.logger.error("client error"),this.fire(H$1.ERROR)})).on($,(()=>{this.logger.error("client close"),this.fire(H$1.ERROR)})).on(E$1,(()=>{this.logger.error("client timeout"),this.fire(H$1.TIMEOUT,[{msg:"timeout"}])})).on(O$1,(()=>{this.logger.info("client reconnected"),this.fire(H$1.RECONNECTED)})).on(B,(()=>{this.fire(H$1.RECONNECTING)})).on(xe$1.joinUser,(e=>{this.logger.debug("participant joined");let t=new A$1(!1,e.userId,e);this.fire(xe$1.joinUser,[{participant:t,mode:e.mode,data:e}])})).on(xe$1.leaveUser,(e=>{e.userId!==this.userId&&this.fire(xe$1.leaveUser,[{userId:e.userId,mode:e.mode,data:e}])})).on(xe$1.leaveUsers,(e=>{this.fire(xe$1.leaveUsers,[e])})).on(xe$1.roomClosed,(e=>{this.logger.error("room closed"),this.fire(xe$1.roomClosed,[e]),this.destroy()})).on(xe$1.roomError,(()=>{this.logger.error("room error"),this.fire(xe$1.roomError),this.destroy()})).on(xe$1.publishStream,(e=>{if(e.userId===this.userId)return;let t=e.userId,r=e.streamId,i=r.endsWith("_screen"),s=e.customInfo;this.fire(xe$1.publishStream,[{userId:t,streamId:r,video:e.params.video_enable,audio:e.params.audio_enable,isScreen:i,customInfo:s}])})).on(xe$1.updateStream,(e=>{this.fire(xe$1.updateStream,[e])})).on(xe$1.streamUpdate,(e=>{if(e.userId===this.userId)return;let t=e.userId,r=e.streamId,i=r.endsWith("_screen");this.fire(xe$1.streamUpdate,[{userId:t,streamId:r,video:e.params.video_enable,audio:e.params.audio_enable,isScreen:i}])})).on(xe$1.unpublishStream,(e=>{if(e.userId===this.userId)return;let t=e.userId,r=e.streams[0],i=r.endsWith("_screen");this.fire(xe$1.unpublishStream,[{userId:t,streamId:r,isScreen:i}])})).on(xe$1.sendMessage,(e=>{let t={room:e.roomId,user:e.userId,message:e.msg,to:e.to,seq:e.seq};this.fire(xe$1.sendMessage,[t])})).on(xe$1.customMessage,(e=>{let t={room:e.roomId,user:e.userId,message:e.msg,to:e.to};this.fire(xe$1.customMessage,[t])})).on(xe$1.moveUserRoom,(e=>{var t,r;null!=(t=e.info)&&t.master&&(this.master=e.info.master),null!=(r=e.info)&&r.customStats&&(this.customStats=e.info.customStats),this.fire(xe$1.moveUserRoom,[e])})).on(xe$1.evicted,(e=>{this.fire(xe$1.evicted,[{userId:e.userId}])})).on(xe$1.updateStats,(e=>{this.switch=e.stats.switch,this.hasSecret=e.stats.secret,this.audiooff=e.stats.audiooff,this.selfopenaudio=e.stats.selfopenaudio,this.videooff=e.stats.videooff,this.msgoff=e.stats.msgoff,this.lock=e.stats.lock,this.creator=e.stats.creator,this.master=e.stats.master;let t=e.stats.updates,r=Object.keys(t);this.fire(xe$1.updateStats,[{room:this,options:r,stats:e.stats}])})).on(xe$1.updateCustomStats,(e=>{this.customStats=e.customStats||{},this.fire(xe$1.updateCustomStats,[{room:this,customStats:this.customStats,updateKeys:e.updateKeys}])})).on(xe$1.changeMaster,(e=>{this.master=e.master,this.fire(xe$1.changeMaster,[{master:this.master,oldMaster:e.oldmaster,isKeep:e.isKeep,type:e.type,data:e}])})).on(xe$1.updateUser,(e=>{if(e.user===this.getLocalParticipant().getID())this.getLocalParticipant().update(e.info),this.fire(xe$1.updateUser,[{participant:this.getLocalParticipant()}]);else{let t=new A$1(!1,e.user,e.info);this.fire(xe$1.updateUser,[{participant:t}])}})).on(xe$1.userRejoined,(e=>{this.fire(xe$1.userRejoined,[{userId:e.userId,info:e.info}])}))}getRpc(){return{}}getActiveProxy(){return this.client.getProxy()}destroy(){this.client&&(this.client.close(),this.client=void 0),this.joined=!1,this.off()}getJoinUserInfo(e,t=!1){let r={};return r.ua=e.ua?e.ua:Te(),r.device=e.device?e.device:We(),r.platform=e.platform?e.platform:"Web",r.network=e.network?e.network:"unknown",r.role=e.role?e.role:"anchor",r.create=this.options.create,r.secret=this.options.secret?At(`${this.roomId}.${this.options.secret}`):void 0,r.nickname=this.options.nickname,r.userinfo=this.options.userinfo,r.hasWaitRoom=!0,r.permission=t?this.permission:this.options.permission,r.custom_token=this.options.custom_token,r.prefer=this.options.prefer,r.name=this.options.name,r.userinfo.jointime||(r.userinfo.jointime=Math.floor(Date.now()/1e3)),r}getLocalParticipant(){return this.localParticipant}getID(){return this.roomId}getAudioOff(){return this.audiooff}getSelfOpenAudio(){return this.selfopenaudio}getVideoOff(){return this.videooff}getMsgOff(){return this.msgoff}getLock(){return this.lock}setAudioOff(e,t){return this.update({audiooff:e,selfopenaudio:t})}setVideoOff(e){return this.update({videooff:e})}setMsgOff(e){return this.update({msgoff:e})}setSwitch(e){return this.update({switch:e})}setLock(e){return this.update({lock:e})}getSwitch(){return this.switch}setSecret(e){return this.update({secret:e})}getLimits(){return this.limit}getMaster(){return this.master}getCreator(){return this.creator}getName(){return this.name}getMsgSeq(){return this.msgSeq}changeMaster(e,t){if(e!=this.getMaster())return this.client.changeMaster(this.roomId,this.userId,e,t).then((()=>{this.master=e})).catch((e=>{m.Log().error(circularJson_node.stringify(e))}))}syncUser(e){return this.client.syncUser(e).then((e=>(m.Log().info("syncUser success"),e))).catch((e=>{m.Log().error("syncUser error",e)}))}evictUser(e){return this.client.evictUser(this.roomId,this.userId,e)}evictUser2(e,t,r){return e!=this.getMaster()?Promise.reject("not master."):this.client.evictUser(this.roomId,this.userId,t,r)}updateUser(e,t){return this.localParticipant.getID()==this.getMaster()||this.localParticipant.getPermission().getManage()||!t.permission&&e==this.localParticipant.getID()?this.client.updateUser(this.roomId,this.localParticipant.getID(),{info:t,target:e}).then((()=>{e==this.localParticipant.getID()&&this.localParticipant.update(t)})).catch((e=>{m.Log().error(e)})):Promise.reject({code:we.ERR_PERMISSION,error:"permission denied."})}parseStreams(e,t){let r=[];if(t.streams)for(let i=0;i<t.streams.length;i++){let s=t.streams[i].params,o=t.streams[i].streamId,n={id:o,audio:s.audio,video:s.video,audio_enable:s.audio_enable,video_enable:s.video_enable,screen:o.endsWith("_screen"),customInfo:s.customInfo},a=new U(this.client,this,e,!1,n);r.push(a)}return r}parseJoinResponse(e){return this.logger.log(`room-connect耗时: ${e.duration}`),this.total=e.total,this.pagesize=e.pagesize,this.index=e.index,this.startup=e.startup,this.duration=e.duration,this.limit=e.limit,this.switch=e.switch,this.audiooff=e.audiooff,this.selfopenaudio=e.selfopenaudio,this.videooff=e.videooff,this.msgoff=e.msgoff,this.lock=e.lock,this.master=e.master,this.creator=e.creator,this.name=e.name,this.limit=e.limit,this.msgSeq=e.msgSeq,this.sessionId=e.sessionId,this.permission=e.permission,this.customStats=e.customStats,this.getLocalParticipant().getPermission().set(this.permission),{total:this.total,sessionId:this.sessionId,customStats:this.customStats,joinwait:e.joinwait,waitroom:e.waitroom,permission:e.permission,audiooff:e.audiooff}}syncRoom(){let e=this.getJoinUserInfo(this.options.userinfo,!0);return this.client.syncRoom(this.options.room,this.options.user,e).then((e=>{m.Log().log("bloud syncRoom response : "+circularJson_node.stringify(e));let t=this.parseJoinResponse(e);this.fire(H$1.ROOM_SYNCED,[t])})).catch((e=>{throw m.Log().error(e),this.fire(H$1.SYNC_FAILED,[{error:e}]),e}))}update(e={}){return"string"==typeof e.secret&&(e.secret=At(`${this.roomId}.${e.secret}`)),this.client.updateRoom(this.roomId,this.userId,e).then((()=>{"boolean"==typeof e.audiooff&&(this.audiooff=e.audiooff),"boolean"==typeof e.videooff&&(this.videooff=e.videooff),"boolean"==typeof e.msgoff&&(this.msgoff=e.msgoff),"boolean"==typeof e.switch&&(this.switch=e.switch),"string"==typeof e.secret&&(this.secret=e.secret),"boolean"==typeof e.lock&&(this.lock=e.lock),"boolean"==typeof e.selfopenaudio&&(this.selfopenaudio=e.selfopenaudio),m.Log().info(e)})).catch((e=>{throw m.Log().error(e),e}))}updateCustomStats(e,t){return e=e||{},this.client.updateCustomStats(this.roomId,this.userId,e,t).then((()=>{m.Log().info("updateCustomStats:"+circularJson_node.stringify(e))})).catch((e=>{throw m.Log().error(e),e}))}updateStream(e,t,r){return this.client.updateStream(e,t,{customInfo:r})}getMessages(e,t){return this.client.getMessages(this.roomId,this.userId,{startSeq:e,endSeq:t})}parseGetUser(e){let t=[];for(let r=0;r<e.length;r++){if(e[r].userId===this.getLocalParticipant().getID()){t.push(this.getLocalParticipant());continue}let i=new A$1(!1,e[r].userId,e[r]);this.parseStreams(i,e[r]).forEach((e=>i.addStream(e))),t.push(i)}return t}getUsers(e,t,r,i=!1){return this.index=e,this.pagesize=r||this.pagesize,this.client.getUsers(this.roomId,this.userId,this.pagesize,this.index+1,t,i).then((e=>{let t=e.value;this.total=e.total,this.pagesize=e.pagesize,this.index=e.index;let r=this.parseGetUser(t);return this.fire("users-list",[{usersEvent:{participants:r}}]),{participants:r,total:this.total}}))}getTotalUsers(){return this.total}getInfo(e){return e.ua=e.ua?e.ua:Te(),e.device=e.device?e.device:We(),e.platform=e.platform?e.platform:"Web",e.network=e.network?e.network:"unknown",e.role=e.role?e.role:"anchor",e.create=this.create,e.secret=this.secret,e.nickname=this.nickname,e.userinfo=this.userinfo,e.permission=this.permission,e.custom_token=this.custom_token,e.name=this.name,this.create&&(e.limit=this.limit,e.limittime=this.limittime,e.stoptime=this.stoptime),e.pagesize=this.pagesize,e}getCustomStats(){return this.customStats}sendMessage(e,t){return this.client.sendMessage(this.roomId,this.userId,t,e).then((e=>(m.Log().log(circularJson_node.stringify(e)),e))).catch((e=>{throw m.Log().error(e),e}))}customMessage(e,t){return this.client.customMessage(this.roomId,this.userId,t,e).then((e=>(m.Log().log(circularJson_node.stringify(e)),e))).catch((e=>{throw m.Log().error(e),e}))}moveUserRoom(e,t,r){return this.client.moveUserRoom(e,t,r)}release(){return this.client.releaseRoom(this.roomId,this.userId).then((e=>(m.Log().log(circularJson_node.stringify(e)),e))).catch((e=>{throw m.Log().error(e),e}))}close(){this.client&&(this.client.close(),this.client=void 0)}SpeakerDetector(){return new Nt}Recorder(e){var t;let r=new Dt(e);return m.Log().info("create local recorder"),r.addEventListener("started",(()=>{m.Log().info("local recorder started.")})),r.addEventListener("stopped",(()=>{var e,t;m.Log().info("local recorder stopped");let i=null==(e=this.recorders)?void 0:e.indexOf(r);i&&i>=0&&(this.recorders=null==(t=this.recorders)?void 0:t.splice(i,1))})),r.addEventListener("track-ended",(()=>{m.Log().info("local recorder track ended")})),null==(t=this.recorders)||t.push(r),r}removeAllListeners(){this.off()}Stream(e){if(this.client)return new U(this.client,this,this.getLocalParticipant(),!0,e)}},q=Object.defineProperty,N=Object.getOwnPropertySymbols,X=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable,D=(e,t,r)=>t in e?q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,P=(e,t)=>{for(var r in t||(t={}))X.call(t,r)&&D(e,r,t[r]);if(N)for(var r of N(t))z.call(t,r)&&D(e,r,t[r]);return e},n=(e,t,r)=>new Promise(((i,s)=>{var o=e=>{try{a(r.next(e))}catch(e){s(e)}},n=e=>{try{a(r.throw(e))}catch(e){s(e)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(o,n);a((r=r.apply(e,t)).next())})),K={token:""},I=K;function k({url:e,method:t="get",data:r={},contentType:i="application/json",_header:s={},succCB:o,errCB:n,dataType:a,responseType:d}){let u=I.token;t=t.toUpperCase(),s.Authorization="Bearer "+u,-1==e.indexOf("/proxies")&&(s.checkdelay="570ed35e48494f1d6aa7d1bd20d0a2be",s.ch="web",s.os="web",s.p="3",s.delay=(new Date).getTime(),s.version="2.2.7",s.ver="2.2.7",s.lan="zh",s.osv="",s.wh="",s.apn="");let l={headers:s,method:t};if(d&&(l.responseType=d),"GET"===t){if(r){e+="?";for(let t in r)e+=`${t}=${r[t]}&`;e=e.substring(0,e.length-1)}l.cache="no-store"}else if("RESTFUL"===t){e+="/";for(let t of r)e+=t+"/";e=e.substring(0,e.length-1),t="GET",l.method=t,l.cache="no-store"}else l.body="multipart/form-data"===i?r:JSON.stringify(r);return console.log("\n############# getData host==\n"+e+"\n Header=",s,"\n optins=",l),fetch(e,l).then((t=>"blob"===a?t:Q(t,e,r,d))).then((t=>(console.log(`此接口【${e}】返回的data:`,t),"blob"!==a?(t.msg=t.message||t.msg,t):"200"===t.code||200===t.status?("function"==typeof o&&o(t),t):("function"==typeof n&&n(t),void Promise.reject(t))))).catch((t=>(console.log("\n############## err"+t.message,e),t.msg=t.message||t.msg,Promise.reject(t))))}function Q(e,t,r,i){return e.ok?"blob"===i?e.blob():e.json():500===e.status?Promise.reject({code:500,message:"连接服务器失败, 请检查网络重试!",url:t,param:r}):404===e.status?Promise.reject({code:404,message:"404",url:t,param:r}):502===e.status?Promise.reject({code:502,message:"连接服务器失败, 请检查网络重试!",url:t,param:r}):Promise.reject({code:e.status,message:e.status+"",url:t,param:r})}var p=class e{constructor(e){this.userinfo=e.userinfo,this.permission=e.permission,this.stream=e.stream,this.userId=e.userId,this.customInfo=e.customInfo,this.nickname=e.nickname}static toUser(t,r){var i,s;return new e({userinfo:P({},t.getUserInfo()),userId:t.getID(),stream:t.getStreams(),permission:t.getPermission(),customInfo:P({},null==(s=null==(i=t.params)?void 0:i.info)?void 0:s.customInfo),nickname:t.getNickName()})}},Z=e=>e;function ee(e){return e.participant&&(e.user=p.toUser(e.participant,this.type)),e}var te=[H$1.PARTICIPANT_JOINED,H$1.UPDATE_USER],C={};function j(){Object.values(H$1).forEach((e=>{C[e]||(te.includes(e)?C[e]=ee:C[e]=Z)}))}var re=function(){},y=void 0!==typeof console?console:null;function O(e,t,r,i){let s=[];return r&&s.push(r),i&&s.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${s.join("|")}] ${t}`}function v(e,t,r,i=[]){i.unshift(O("DEBUG",e,t,r)),y.log.apply(y.log,i)}function h(e,t,r,i=[]){i.unshift(O("INFO",e,t,r)),y.log.apply(y.log,i)}function G(e,t,r,i=[]){i.unshift(O("WARN",e,t,r)),y.warn.apply(y.warn,i)}function l(e,t,r,i=[]){i.unshift(O("ERROR",e,t,r)),y.error.apply(y.error,i)}/BRTC/.test(re.toString());var b=class{static singleModeJoin(e,t){return n(this,null,(function*(){try{let r,i;try{r=yield e._getBloudProxiesUrl(e.token)}catch(e){return l("_getBloudProxiesUrl error","","",[JSON.stringify(e)]),Promise.reject(e)}switch(e.identity){case"5":i="RWPSAVM";break;case"3":case"4":i="RWPS";break;case"6":i="RWPAV"}let s={room:e.roomId,user:e.userId.toString(),enableCollection:!1,enableRace:!0,proxies:r.proxies,nickname:e.userinfo.nickname,custom_token:e.customToken,userinfo:e.userinfo,token:e.token,secret:e.secret,forceWS:!0,name:e.name,create:e.tarCreate,disableMediaEngine:e.disableMediaEngine,permission:i};try{e.client&&e.client.destroy()}catch(e){}e.client=new Ae(s),t(),yield e.client.connect(),h("singleModeJoin==>单一模式加入会议成功",e.userId,1)}catch(t){return l("singleModeJoin==>单一模式加入会议失败",e.userId,1,[JSON.stringify(t)]),e.client=null,Promise.reject(t)}}))}static singleModeLeave(e){return n(this,null,(function*(){if(!e.client)throw new Error("没有 joined");try{yield e.client.leave(),console.log("client leave success",e.userId),e.clearObject()}catch(t){throw console.log("client leave fail",e.userId,[t]),e.clearObject(),new Error(t)}}))}};Object.freeze({}),Object.freeze([]);var Y="c",w=1,V=2,f=window.BRTC,T=class{constructor(e){this.emitters=[],this.name="",this.type=w,this.appId="",this.brtcAppId="",this.roomId="",this.tarCreate=!1,this.userinfo={},this.userId="",this.isJoining=!1,this.collection="",this.limit=0,this.token="",this.customToken="",this.create=!1,this.host="",this.getProxiesUrl="",this.secret="",this.enableRace=!1,this.disableMediaEngine=!1,this.roomType=1,this.brtcClient=null,this.shareBrtcClient=null,this.hasBloudJoined=!1,this.brtcSig="",this.brtcShareSig="",this.shareContentHint="detail",this.identity="",this.isBig="0",this.joinBrtc=()=>new Promise(((e,t)=>{this.brtcClient.join(this.roomId,this.userId,this.sig).then((()=>(h("join brtc succeed"),e(!0)))).catch((e=>(console.log("brtc入会失败01",e),this.isJoining=!1,t(Pn(e.message)))))})),this.joinBloud=()=>new Promise(((e,t)=>{b.singleModeJoin(this,(()=>this.addBloudEvent())).then((()=>(h("join bloud succeed"),this.hasBloudJoined=!0,e(!0)))).catch((e=>(l("bloud入会失败02","",[e]),this.isJoining=!1,t(e))))})),this.handleForceUnpublishBloudStream=()=>{l("bloud share stream unpublish failed, create bloud stream and unpub again"),this.client.client.unpublishStream(this.roomId,this.userId,`${this.userId}_screen`)},this.emitter=new q$1(!0),j()}setShareSig(e){this.brtcShareSig=e}clearObject(){this.client&&(this.client.close(),this.client.removeAllListeners()),this.client=null,this.collection&&(this.collection.close(),this.collection=null)}join(e){return n(this,null,(function*(){return new Promise(((t,r)=>n(this,null,(function*(){if(this.isJoining)return Promise.reject(vn);if(this.client)return Promise.reject(vn);if("string"!=typeof e.getProxiesUrl)return Promise.reject(_n);if(!e.userinfo||e.userinfo&&"object"!=typeof e.userinfo)return Promise.reject(In);if("number"!=typeof e.type||1!==e.type&&2!==e.type)return Promise.reject(wn);if(this.userId=e.userId,this.roomId=e.room,this.roomType=e.roomType,this.collection=e.collection,this.userinfo=e.userinfo,this.getProxiesUrl=e.getProxiesUrl,this.appId=e.appId,this.brtcAppId=e.brtcAppId,this.type=e.type,this.tarCreate=e.create,this.limit=e.limit,this.secret=e.secret,this.enableRace=e.enableRace,this.token=e.token,this.customToken=e.customToken,this.name=e.name,this.brtcSig=e.sig,this.identity=e.identity,this.isBig=e.is_big,this.sig=e.sig,I.token=e.token,this.isJoining=!0,this.type===w&&(yield b.singleModeJoin(this,(()=>this.addBloudEvent()))),this.type===V){this.disableMediaEngine=!0;try{this.brtcClient=f.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,audioLevelInterval:200,roomType:"big",silence:!0}),this.createShareBrtcClient(),this.addBrtcEvent(),this.fire("brtc-bound",!0),f.setVTRequestTimeout(5),yield this.joinRoom().then((()=>(this.isJoining=!1,this.fire(Nt$1.JOIN_READY),t(!0)))).catch((e=>(l("join room error","",this.userId,[JSON.stringify(e)]),r(e))))}catch(e){return this.isJoining=!1,l("join room error",Y,this.userId,[e]),r(e)}}}))))}))}joinRoom(){return new Promise(((e,t)=>{let r=!1,i=!1;this.joinBloud().then((()=>{if(r=!0,i)return e(!0)})).catch((e=>t(e))),this.joinBrtc().then((()=>{if(i=!0,r)return e(!0)})).catch((e=>t(e)))}))}createShareBrtcClient(){return this.shareBrtcClient||(this.shareBrtcClient=f.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,roomType:"big",silence:!0}),this.shareBrtcClient.on("error",(e=>{this.fire("share-brtc-error",e)}))),this.shareBrtcClient}_getBloudProxiesUrl(e){return new Promise(((t,r)=>{k({url:`${this.getProxiesUrl}/proxies?token=${e}`}).then((r=>{t({proxies:r.proxies,token:e})})).catch((e=>{r(Ln(e))}))}))}on(e,t){return this.emitter.on(e,{fn:t,ctx:this}),this}fire(e,t){this.emitter&&this.emitter.fire(e,t?[t]:void 0)}changeMaster(e,t=!1){return this.client.changeMaster(e,t)}getMaster(){return this.client.getMaster()}syncUser(e){return this.client.syncUser(e)}getCreator(){return this.client.getCreator()}getName(){return this.client.getName()}close(){return n(this,null,(function*(){var e;this.leaveBrtcRoom(),null==(e=this.client)||e.close(),this.leaveShare()}))}getMsgSeq(){return this.client.getMsgSeq()}evictUser(e,t){return this.client.evictUser2(this.getMaster(),e,t)}updateUser(e,t){return n(this,null,(function*(){yield this.client.updateUser(e,t)}))}getLimits(){return this.client.getLimits()}getSwitch(){return this.client.getSwitch()}syncRoom(){return this.client.syncRoom()}update(e){return this.client.update(e)}getUsers(e,t,r){return n(this,null,(function*(){let{participants:i,total:s}=yield this.client.getUsers(e,t,r),o=new Map;return i.forEach((e=>{let t=p.toUser(e,this.type);o.set(t.userId,t)})),{users:o,total:s}}))}updateStream(e,t,r){return this.client.updateStream(e,t,r)}getUsersList(e,t,r,i){return n(this,null,(function*(){let{participants:s,total:o,pageIndex:n}=yield this.client.getUsersList(e,r,t,i),a=new Map;return s.forEach((e=>{let t=p.toUser(e,this.type);a.set(t.userId,t)})),{users:a,total:o,pageIndex:n}}))}getTotalUsers(){return this.client.getTotalUsers()}sendMessage(e,t){return this.client.sendMessage(e,t)}customMessage(e,t){return this.client.customMessage(e,t)}getMessages(e,t){return this.client.getMessages(e,t)}getLocalParticipant(){var e;return null==(e=this.client)?void 0:e.getLocalParticipant()}getAudioOff(){return this.client.getAudioOff()}getSelfOpenAudio(){return this.client.getSelfOpenAudio()}getVideoOff(){return this.client.getVideoOff()}getMsgOff(){return this.client.getMsgOff()}getLock(){return this.client.getLock()}getRoomInfo(){let e=P({},this.client.options);return delete e.token,e}setAudioOff(e,t){return this.client.setAudioOff(e,t)}setVideoOff(e){return this.client.setVideoOff(e)}setMsgOff(e){return this.client.setMsgOff(e)}setSwitch(e){return this.client.setSwitch(e)}setLock(e){return this.client.setLock(e)}publish(e){return n(this,null,(function*(){return this.brtcClient.publish(e).catch((e=>Promise.reject(kn(JSON.stringify(e)))))}))}unpublish(e){return n(this,null,(function*(){return this.brtcClient.unpublish(e).catch((e=>Promise.reject(jn(JSON.stringify(e)))))}))}subscribe(e){return n(this,arguments,(function*(e,t={audio:!0,video:!0}){return this.brtcClient.subscribe(e,t).catch((e=>Promise.reject(e)))}))}unsubscribe(e){return n(this,null,(function*(){return this.brtcClient.unsubscribe(e).catch((e=>Promise.reject(Jn(JSON.stringify(e)))))}))}addBloudEvent(){let e=this,t=C;let r=Object.values(H$1);J$1.each(r,(r=>{!function(r,i){e.client.on(r,(function(){let r=k$2(t[i],e,J$1.toArray(arguments));e.fire(i,r)}))}(r,r)}))}addBrtcEvent(){let e=this;let t=Object.values(dt$1);J$1.each(t,(t=>{var r;r=t,e.brtcClient.on(r,(t=>{e.fire(r,t)}))}))}clearBrtcEvent(){var e;null==(e=this.brtcClient)||e.off()}leave(){return n(this,null,(function*(){return console.log("离开会议","userId =>",this.userId,"roomId =>",this.roomId,"userInfo =>",this.userinfo),yield b.singleModeLeave(this),this.leaveBrtcRoom()}))}leaveBrtcRoom(){return n(this,null,(function*(){if(console.log("离开brtc调用堆栈!!!!!"),this.brtcClient&&(this.brtcClient.off(),yield this.brtcClient.leave(),yield this.brtcClient.destroy(!0),this.brtcClient=null),this.shareBrtcClient){try{this.shareBrtcClient.off(),yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(!0),this.shareBrtcClient=null}}))}leaveShare(){return n(this,null,(function*(){if(this.shareBrtcClient){try{yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(!0),this.shareBrtcClient=null}}))}createRecorder(e){return this.client.Recorder(e)}createSpeakerDetector(){return this.client.SpeakerDetector()}createLocalStream(e,t){return n(this,null,(function*(){f.isSmallStreamSupported()?yield this.brtcClient.enableSmallStream():l("simulcast is not supported"),this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return f.createStream(e)}catch(e){return Promise.reject(e)}}))}createPBLocalStream(e,t){return n(this,null,(function*(){this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return f.createStream(e)}catch(e){return Promise.reject(Mn(JSON.stringify(e)))}}))}creteBloudLocalStream(e,t){return this.client.Stream({audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t,screen:!1})}createBloudScreenStream(e,t){return this.client.Stream({screen:!0,audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t})}updateCustomStats(e,t=!1){return h("updateCustomStats","updateCustomStats","",[" customstats => ",JSON.stringify(e),"replace => ",t]),this.client.updateCustomStats({customStats:e},t)}getCustomStats(){var e;return null==(e=this.client)?void 0:e.getCustomStats()}getDuration(){var e;return null==(e=this.client)?void 0:e.duration}toggleShareScreen(e,t,r){return n(this,null,(function*(){return new Promise(((i,s)=>n(this,null,(function*(){if(e){let e=t.audioHint;try{let t={screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail",sourceType:"screen"};e&&(t.audioHint=e),r&&(void 0!==r.video&&(t.video=r.video),void 0!==r.audio&&(t.audio=r.audio),t.videoSource=r.videoSource,t.audioSource=r.audioSource);let s=yield f.createStream(t),o="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};s.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:o.frameRate,bitrate:o.bitrate});try{yield s.init()}catch(e){throw l("brtc share stream init failed","","",[String(e)]),new Error(e)}yield this.publishShareStream(s),i(!0)}catch(e){String(e).includes("Permission denied by system")?(l("没有打开共享屏幕录制权限","","this.userId"),s(Rn)):String(e).includes("Permission denied")?(h("点击了取消共享屏幕","",this.userId,["nickname =>",this.name]),s(On)):(l("开启共享屏幕失败","","",[String(e)]),s(yn("开启共享屏幕失败,请重试")))}}else yield this.unpublishShareStream(),i(!0)}))))}))}shareHTMLMedia(e,t){return n(this,null,(function*(){if(e&&t)try{let e=f.createStream({screen:!0,audio:t.audio,video:t.video,videoSource:t.videoSource,audioSource:t.audioSource,videoHint:"motion",sourceType:"screen"}),r="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:r.frameRate,bitrate:r.bitrate}),yield e.init(),yield this.publishShareStream(e)}catch(e){return Promise.reject(Dn(JSON.stringify(e)))}e||(yield this.unpublishShareStream())}))}publishShareStream(e){return n(this,null,(function*(){if(this.shareBrtcClient||this.createShareBrtcClient(),!this.brtcShareSig)return console.error("brtcShareSig为空"),Promise.reject(Bn);{yield this.shareBrtcClient.join(this.roomId,`${this.userId}_screen`,this.brtcShareSig).catch((e=>(l("共享屏幕入会失败","","",[JSON.stringify(e),this.brtcShareSig]),Promise.reject(Un)))),e.on("video-track-ended",(()=>{this.handleShareStreamEnded()})),yield this.shareBrtcClient.publish(e).catch((t=>(l("共享屏幕流推流失败","","",["err =>",JSON.stringify(t)]),e.destroy(),Promise.reject(yn("共享屏幕流推流失败,请重试"))))),this.shareBrtcClient.on("sync-room-completed",(()=>{this.fire(Nt$1.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));let t=e.getAudioOn(),r=e.getVideoOn();this.shareScreenStream=e,this.createAndPubBloudShareStream(t,r),setTimeout((()=>{Promise.resolve(!0)}),200)}}))}createAndPubBloudShareStream(e,t,r=!0){this.bloudShareScreenStream=this.createBloudScreenStream({audio_enable:e,video_enable:t},`${this.userId}_screen`),r&&this.bloudShareScreenStream.publish({video_enable:t,audio_enable:e})}replaceShareStreamVideoTrack(e){this.shareScreenStream?this.shareScreenStream.replaceTrack(e):l("当前没有开启共享屏幕,无法替换track")}unpublishShareStream(){return n(this,null,(function*(){return new Promise((e=>n(this,null,(function*(){var t,r,i;try{G("unpublish share stream"),this.shareScreenStream&&(yield null==(t=this.shareBrtcClient)?void 0:t.unpublish(this.shareScreenStream).catch((e=>{l("取消共享屏幕出错","","",[JSON.stringify(e)])}))),yield null==(r=this.shareBrtcClient)?void 0:r.leave().catch((e=>{l("shareBrtcClient leave error","","",[JSON.stringify(e)])})),null==(i=this.shareScreenStream)||i.destroy(),this.shareScreenStream=void 0,this.bloudShareScreenStream?yield this.bloudShareScreenStream.unpublish().then((()=>{this.bloudShareScreenStream=void 0})).catch((e=>{l("bloud share stream unpublish failed"),this.handleForceUnpublishBloudStream()})):this.handleForceUnpublishBloudStream()}catch(e){console.log("取消共享兼容处理",e)}e(!0)}))))}))}setShareScreenContentHint(e){this.shareContentHint=e}releaseRoom(){return n(this,null,(function*(){yield this.client.release()}))}handleShareStreamEnded(){setTimeout((()=>{var e;(!this.shareScreenStream||"live"!==(null==(e=this.shareScreenStream.getVideoTrack())?void 0:e.readyState))&&(l("share stream video track ended"),this.fire("toggle-screen-share",!1))}),2e3)}setCustomUrl(e){f.setCustomUrl(e)}bloudReconnect(){return n(this,null,(function*(){yield this.client.leave(),yield b.singleModeJoin(this,(()=>this.addBloudEvent()))}))}searchUsers(e,t,r){return n(this,null,(function*(){let{participants:i}=yield this.client.searchUsers(e,t,r),s=new Map;return i.forEach((e=>{let t=p.toUser(e,this.type);s.set(t.userId,t)})),{users:s}}))}queryUsers(e){return n(this,null,(function*(){let{participants:t}=yield this.client.queryUsers(e),r=new Map;return t.forEach((e=>{let t=p.toUser(e,this.type);r.set(t.userId,t)})),{users:r}}))}handleBloudRejoin(){return n(this,null,(function*(){return b.singleModeJoin(this,(()=>this.addBloudEvent()))}))}},A="bp",x=class extends q$1{constructor(e,t){super(),this.playEvent=()=>{this.videoStatus="PLAYING",h("stream big video playing",A,this.stream.getUserId())},this.pauseEvent=()=>{this.videoStatus="PAUSED",this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"video",state:this.videoStatus,reason:"pause"}]),h("stream big video pause",A,this.stream.getUserId())},this.stalledEvent=()=>{this.videoStatus="PAUSED",this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"video",state:this.videoStatus,reason:"stalled"}]),h("stream big video stalled",A,this.stream.getUserId())},this.element=e,this.options=t,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.backgroundColor="#202020",this.container.style.overflow="hidden",e.appendChild(this.container)}playVideo(){if(!this.video){if(!this.stream.getVideoTrack())return;this.video=document.createElement("video"),this.video.autoplay=!0,this.video.playsInline=!0,this.video.muted=!!this.options.muted,this.video.style.width="100%",this.video.style.height="100%",this.video.style.position="absolute";let e="";this.options.rotateX&&(e=`rotateX(${this.options.rotateX}deg)`),this.options.rotateY&&(e=`${e} rotateY(${this.options.rotateY}deg)`),e&&(this.video.style.transform=e),this.options.fit&&(this.video.style.objectFit=this.options.fit),this.video.id=`video_${this.stream.getStreamId()}_big`,this.container.appendChild(this.video),this.video.addEventListener("playing",this.playEvent),this.video.addEventListener("pause",this.pauseEvent),this.video.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e,this.videoStatus="STOPPED"}play(e){return n(this,null,(function*(){this.stream=e,this.container.id=`player_${e.getStreamId()}_big_container`,this.stream.hasVideo()&&this.playVideo();try{this.video&&(yield this.video.play())}catch(e){l("big player play video failed","","",[JSON.stringify(e)]),this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return n(this,null,(function*(){this.stream=e;try{this.stream.hasVideo()&&t&&this.playVideo(),this.stream.hasVideo()&&t&&(yield this.video.play())}catch(e){l("big player replay video failed","","",[JSON.stringify(e)]),this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}muteVideo(){this.video&&(this.video.srcObject=void 0,this.videoStatus="STOPPED")}unmuteVideo(){if(this.video&&this.stream&&"STOPPED"===this.videoStatus){let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e}}destroy(){this.video&&(this.video.removeEventListener("playing",this.playEvent),this.video.removeEventListener("pause",this.pauseEvent),this.video.removeEventListener("stalled",this.stalledEvent),this.video.style.display="none",this.video=null);try{this.container.style.display="none",this.element.removeChild(this.container)}catch(e){}this.container=null,v("stream player destroy",A,this.stream.getUserId())}resume(){return n(this,null,(function*(){this.video&&(yield this.video.play()),v("stream player resume",A,this.stream.getUserId())}))}getVideoFrame(){if(this.video&&"STOPPED"!==this.videoStatus){let e=document.createElement("canvas");return e.width=this.video.videoWidth,e.height=this.video.videoHeight,e.getContext("2d").drawImage(this.video,0,0),e.toDataURL("image/png")}}},S="ap",_=class extends q$1{constructor(e,t){super(),this.sinkId="",this.audioLevel=1,this.playEvent=()=>{this.audioStatus="PLAYING",h("stream audio playing",S,this.stream.getUserId())},this.pauseEvent=()=>{this.audioStatus="PAUSED",this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"pause"}]),h("stream audio pause",S,this.stream.getUserId())},this.stalledEvent=()=>{this.audioStatus="PAUSED",this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"stalled"}]),h("stream audio stalled",S,this.stream.getUserId())},this.element=e,this.options=t}get streamId(){return this.stream.getStreamId()}playAudio(){if(!this.audio){if(!this.stream.getAudioTrack())return;this.audio=document.createElement("audio"),this.audio.autoplay=!0,this.audio.playsInline=!0,this.audio.muted=this.options.muted,this.audio.id=`audio_${this.stream.getStreamId()}_back`,this.element.appendChild(this.audio),this.sinkId&&this.setSinkId(this.sinkId),this.audio.volume=this.audioLevel,this.audio.addEventListener("playing",this.playEvent),this.audio.addEventListener("pause",this.pauseEvent),this.audio.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e,this.audioStatus="STOPPED"}setSinkId(e){return n(this,null,(function*(){this.sinkId=e,this.audio&&O$2.func(this.audio.setSinkId)&&(yield this.audio.setSinkId(e))}))}setVolume(e){this.audio&&(this.audioLevel=e,this.audio.volume=e)}play(e){return n(this,null,(function*(){this.stream=e,this.stream.hasAudio()&&this.playAudio();try{this.audio&&(yield this.audio.play())}catch(e){l("player play audio failed","","",[JSON.stringify(e)]),this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return n(this,null,(function*(){this.stream=e;try{this.stream.hasAudio()&&r&&this.playAudio(),this.stream.hasAudio()&&r&&(yield this.audio.play())}catch(e){l("player replay audio failed","","",[JSON.stringify(e)]),this.fire(ht$1.PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}v("audio stream replay",S,this.stream.getUserId())}))}muteAudio(){this.audio&&(this.audio.srcObject=void 0,this.audioStatus="STOPPED")}unmuteAudio(){if(this.audio&&this.stream&&"STOPPED"===this.audioStatus){let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e}}destroy(){var e,t,r;null==(e=this.audio)||e.removeEventListener("playing",this.playEvent),null==(t=this.audio)||t.removeEventListener("pause",this.pauseEvent),null==(r=this.audio)||r.removeEventListener("stalled",this.stalledEvent);try{this.element.removeChild(this.audio)}catch(e){}this.audio=null,v("stream player destroy",S,this.stream.getUserId())}resume(){return n(this,null,(function*(){this.audio?(yield this.audio.play(),h("stream player resume",S,this.stream.getUserId())):l("try resume audio play, but, audio not exits",S,this.stream.getUserId())}))}},E=window.BRTC,mt=E.enumAudioInputDevices,pt=E.enumAudioOutputDevices,gt=E.enumVideoDevices,bt=E.getPermissions,ft=E.checkSystemSupport,yt=E.createStream,St=T;class BoomError extends Error{constructor(e,t,r,i){super(),this.code=e,this.error=r,this.BoomErrorFlag=!0,this.eName=i,this.message=t}static instanceOf(e){return!(!e||!e.BoomErrorFlag)}getCode(){return this.code}}const LOCAL_ERROR=1e3,INVALID_PARAMETER=1001,INVALID_OPERATION=1002,CLIENT_BANNED=4005,USER_NOT_EXIT=9001,DEBUG=1,WARN=3,EMPTY_FUNCTION=function(){};function formatLog(e,t,r,i){let s=[];return r&&s.push(r),i&&s.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${s.join("|")}] ${t}`}function info(e,t,r,i=[]){i.unshift(formatLog("INFO",e,t,r)),console.log(...i)}function warn(e,t,r,i=[]){i.unshift(formatLog("WARN",e,t,r)),console.log(...i)}function error$1(e,t,r,i=[]){i.unshift(formatLog("ERROR",e,t,r)),console.log(...i)}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}/BRTC/.test(EMPTY_FUNCTION.toString());var UnsubscriptionError=createErrorClass((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function arrRemove(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var n=__values(o),a=n.next();!a.done;a=n.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}else o.remove(this);var d=this.initialTeardown;if(isFunction(d))try{d()}catch(e){s=e instanceof UnsubscriptionError?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=__values(u),c=l.next();!c.done;c=l.next()){var h=c.value;try{execFinalizer(h)}catch(e){s=null!=s?s:[],e instanceof UnsubscriptionError?s=__spreadArray(__spreadArray([],__read(s)),__read(e.errors)):s.push(e)}}}catch(e){r={error:e}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}}if(s)throw new UnsubscriptionError(s)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&arrRemove(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}(),EMPTY_SUBSCRIPTION=Subscription.EMPTY;function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}var config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},timeoutProvider={setTimeout:function(e,t){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var s=timeoutProvider.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,__spreadArray([e,t],__read(r))):setTimeout.apply(void 0,__spreadArray([e,t],__read(r)))},clearTimeout:function(e){var t=timeoutProvider.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function reportUnhandledError(e){timeoutProvider.setTimeout((function(){throw e}))}function noop(){}var context=null;function errorContext(e){if(config.useDeprecatedSynchronousErrorHandling){var t=!context;if(t&&(context={errorThrown:!1,error:null}),e(),t){var r=context,i=r.errorThrown,s=r.error;if(context=null,i)throw s}}else e()}var Subscriber=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,isSubscription(t)&&t.add(r)):r.destination=EMPTY_OBSERVER,r}return __extends(t,e),t.create=function(e,t,r){return new SafeSubscriber(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Subscription),_bind=Function.prototype.bind;function bind(e,t){return _bind.call(e,t)}var ConsumerObserver=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){handleUnhandledError(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){handleUnhandledError(e)}else handleUnhandledError(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){handleUnhandledError(e)}},e}(),SafeSubscriber=function(e){function t(t,r,i){var s,o,n=e.call(this)||this;isFunction(t)||!t?s={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=i?i:void 0}:n&&config.useDeprecatedNextContext?((o=Object.create(t)).unsubscribe=function(){return n.unsubscribe()},s={next:t.next&&bind(t.next,o),error:t.error&&bind(t.error,o),complete:t.complete&&bind(t.complete,o)}):s=t;return n.destination=new ConsumerObserver(s),n}return __extends(t,e),t}(Subscriber);function handleUnhandledError(e){reportUnhandledError(e)}function defaultErrorHandler(e){throw e}var EMPTY_OBSERVER={closed:!0,next:noop,error:defaultErrorHandler,complete:noop},observable="function"==typeof Symbol&&Symbol.observable||"@@observable";function identity(e){return e}function pipeFromArray(e){return 0===e.length?identity:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Observable=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var i=this,s=isSubscriber(e)?e:new SafeSubscriber(e,t,r);return errorContext((function(){var e=i,t=e.operator,r=e.source;s.add(t?t.call(s,r):r?i._subscribe(s):i._trySubscribe(s))})),s},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=getPromiseCtor(t))((function(t,i){var s=new SafeSubscriber({next:function(t){try{e(t)}catch(e){i(e),s.unsubscribe()}},error:i,complete:t});r.subscribe(s)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=getPromiseCtor(e))((function(e,r){var i;t.subscribe((function(e){return i=e}),(function(e){return r(e)}),(function(){return e(i)}))}))},e.create=function(t){return new e(t)},e}();function getPromiseCtor(e){var t;return null!==(t=null!=e?e:config.Promise)&&void 0!==t?t:Promise}function isObserver(e){return e&&isFunction(e.next)&&isFunction(e.error)&&isFunction(e.complete)}function isSubscriber(e){return e&&e instanceof Subscriber||isObserver(e)&&isSubscription(e)}var ObjectUnsubscribedError=createErrorClass((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),Subject=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return __extends(t,e),t.prototype.lift=function(e){var t=new AnonymousSubject(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new ObjectUnsubscribedError},t.prototype.next=function(e){var t=this;errorContext((function(){var r,i;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var s=__values(t.currentObservers),o=s.next();!o.done;o=s.next()){o.value.next(e)}}catch(e){r={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}}}))},t.prototype.error=function(e){var t=this;errorContext((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}}))},t.prototype.complete=function(){var e=this;errorContext((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,i=r.hasError,s=r.isStopped,o=r.observers;return i||s?EMPTY_SUBSCRIPTION:(this.currentObservers=null,o.push(e),new Subscription((function(){t.currentObservers=null,arrRemove(o,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,i=t.thrownError,s=t.isStopped;r?e.error(i):s&&e.complete()},t.prototype.asObservable=function(){var e=new Observable;return e.source=this,e},t.create=function(e,t){return new AnonymousSubject(e,t)},t}(Observable),AnonymousSubject=function(e){function t(t,r){var i=e.call(this)||this;return i.destination=t,i.source=r,i}return __extends(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:EMPTY_SUBSCRIPTION},t}(Subject),BehaviorSubject=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return __extends(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,i=e._value;if(t)throw r;return this._throwIfClosed(),i},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Subject);Object.freeze({}),Object.freeze([]);const LOGGER_TAG_CLIENT="c";var MODEL_SORT_ENUM_STAND,MODEL_SORT_ENUM_ZY,STREAM_TYPE;!function(e){e[e.SCREEN_MASTER=0]="SCREEN_MASTER",e[e.SCREEN_MANAGER_AUDIO_VIDEO=1]="SCREEN_MANAGER_AUDIO_VIDEO",e[e.SCREEN_MANAGER_AUDIO=2]="SCREEN_MANAGER_AUDIO",e[e.SCREEN_MANAGER_VIDEO=3]="SCREEN_MANAGER_VIDEO",e[e.SCREEN_MANAGER=4]="SCREEN_MANAGER",e[e.SCREEN_GUEST_AUDIO_VIDEO=5]="SCREEN_GUEST_AUDIO_VIDEO",e[e.SCREEN_GUEST_AUDIO=6]="SCREEN_GUEST_AUDIO",e[e.SCREEN_GUEST_VIDEO=7]="SCREEN_GUEST_VIDEO",e[e.SCREEN_GUEST=8]="SCREEN_GUEST",e[e.SCREEN_COMMONUSER_AUDIO_VIDEO=9]="SCREEN_COMMONUSER_AUDIO_VIDEO",e[e.SCREEN_COMMONUSER_AUDIO=10]="SCREEN_COMMONUSER_AUDIO",e[e.SCREEN_COMMONUSER_VIDEO=11]="SCREEN_COMMONUSER_VIDEO",e[e.SCREEN_OTHER=12]="SCREEN_OTHER",e[e.MASTER=13]="MASTER",e[e.LOCAL=14]="LOCAL",e[e.MANAGER_AUDIO_VIDEO=15]="MANAGER_AUDIO_VIDEO",e[e.MANAGER_AUDIO=16]="MANAGER_AUDIO",e[e.MANAGER_VIDEO=17]="MANAGER_VIDEO",e[e.MANAGER=18]="MANAGER",e[e.RAISE_HAND=19]="RAISE_HAND",e[e.RAISE_AUDIO=20]="RAISE_AUDIO",e[e.RAISE_VIDEO=21]="RAISE_VIDEO",e[e.GUEST_AUDIO_VIDEO=22]="GUEST_AUDIO_VIDEO",e[e.GUEST_AUDIO=23]="GUEST_AUDIO",e[e.GUEST_VIDEO=24]="GUEST_VIDEO",e[e.GUEST=25]="GUEST",e[e.SIGNAL=26]="SIGNAL",e[e.COMMONUSER_AUDIO_VIDEO=27]="COMMONUSER_AUDIO_VIDEO",e[e.COMMONUSER_AUDIO=28]="COMMONUSER_AUDIO",e[e.COMMONUSER_VIDEO=29]="COMMONUSER_VIDEO",e[e.OTHER=30]="OTHER"}(MODEL_SORT_ENUM_STAND||(MODEL_SORT_ENUM_STAND={})),function(e){e[e.SCREEN=0]="SCREEN",e[e.RAISE_AUDIO=1]="RAISE_AUDIO",e[e.RAISE_VIDEO=2]="RAISE_VIDEO",e[e.LOCAL=3]="LOCAL",e[e.MASTER_AUDIO_VIDEO=4]="MASTER_AUDIO_VIDEO",e[e.MANAGER_AUDIO_VIDEO=5]="MANAGER_AUDIO_VIDEO",e[e.AUDIO_VIDEO=6]="AUDIO_VIDEO",e[e.MASTER_AUDIO=7]="MASTER_AUDIO",e[e.MANAGER_AUDIO=8]="MANAGER_AUDIO",e[e.AUDIO=9]="AUDIO",e[e.MASTER_VIDEO=10]="MASTER_VIDEO",e[e.MANAGER_VIDEO=11]="MANAGER_VIDEO",e[e.VIDEO=12]="VIDEO",e[e.MASTER=13]="MASTER",e[e.MANAGER=14]="MANAGER",e[e.GUEST=15]="GUEST",e[e.COMMON_USER=16]="COMMON_USER",e[e.SIGNAL=17]="SIGNAL",e[e.OTHER=18]="OTHER"}(MODEL_SORT_ENUM_ZY||(MODEL_SORT_ENUM_ZY={})),function(e){e[e.SUB_MAIN=0]="SUB_MAIN",e[e.SINGLE=1]="SINGLE",e[e.SHARE=2]="SHARE",e[e.OTHER=3]="OTHER"}(STREAM_TYPE||(STREAM_TYPE={}));const STREAM_SUFFIX_SCREEN="_screen",MOBILE_STREAM_SUFFIX_SCREEN="screen-",SIGNAL_SUFFIX="xinhao_",RECEIVE_SUBSCRIBE_MESSAGE="sub-message",USER_SORT_NUM_CHANGE="user-sort-num-change",BIND_ELEMENT="bind-element",HANDLE_STREAM_CONNECT_ERROR="stream-connect-error",RAISE_HAND="raise-hand",MANUAL_SUBSCRIPTION="manual-subscription",UNSUBSCRIBE_STREAM="unsubscribe-stream",CHANG_IS_GUEST="change-is-guest",BIND_BIG_ELEMENT="bind-big-element",NO_CONTAINER="no-container",MODEL_SORT_NUM_CHANGE="model-sort-num-change",ADD_PULL_USER="add-pull-user",SET_VOLUME="set-volume",ADD_AUDIO_PLAY="add-audio-play";function mitt(e){return{all:e=e||new Map,on:function(t,r){var i=e.get(t);i?i.push(r):e.set(t,[r])},off:function(t,r){var i=e.get(t);i&&(r?i.splice(i.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var i=e.get(t);i&&i.slice().map((function(e){e(r)})),(i=e.get("*"))&&i.slice().map((function(e){e(t,r)}))}}}class BoomEmitter{static getInstance(){return BoomEmitter.emitter||(BoomEmitter.emitter=mitt()),BoomEmitter.emitter}}function getSortNum(e){return 2===_selfSortType?sortZY(e):sortStand(e)}function sortStand(e){let t=MODEL_SORT_ENUM_STAND.OTHER;return e.isSharing?(t=e.isMaster?MODEL_SORT_ENUM_STAND.SCREEN_MASTER:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO_VIDEO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_VIDEO:e.isManager?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER:e.isCommonUser?e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_OTHER:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_GUEST,t):(e.isMaster?t=MODEL_SORT_ENUM_STAND.MASTER:e.isLocal?t=MODEL_SORT_ENUM_STAND.LOCAL:e.isManager?t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_VIDEO:MODEL_SORT_ENUM_STAND.MANAGER:e.raiseHand?t=MODEL_SORT_ENUM_STAND.RAISE_HAND:e.isCommonUser?e.isSignal?t=MODEL_SORT_ENUM_STAND.SIGNAL:e.isCommonUser&&(t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.OTHER):t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_VIDEO:MODEL_SORT_ENUM_STAND.GUEST,t)}function sortZY(e){let t;return t=e.isToupingma?MODEL_SORT_ENUM_ZY.SCREEN:e.raiseHand?MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?MODEL_SORT_ENUM_ZY.RAISE_AUDIO:e.raiseVideoHands?MODEL_SORT_ENUM_ZY.RAISE_VIDEO:e.isLocal?MODEL_SORT_ENUM_ZY.LOCAL:e.isMaster&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO_VIDEO:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO_VIDEO:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.AUDIO_VIDEO:e.isMaster&&e.audioEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO:e.audioEnable?MODEL_SORT_ENUM_ZY.AUDIO:e.isMaster&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_VIDEO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_VIDEO:e.videoEnable?MODEL_SORT_ENUM_ZY.VIDEO:e.isMaster?MODEL_SORT_ENUM_ZY.MASTER:e.isManager?MODEL_SORT_ENUM_ZY.MANAGER:e.isCommonUser?MODEL_SORT_ENUM_ZY.COMMON_USER:e.isSignal?MODEL_SORT_ENUM_ZY.SIGNAL:MODEL_SORT_ENUM_ZY.GUEST,t}BoomEmitter.emitter=void 0,BoomEmitter.removeEmitter=()=>{var e,t,r,i,s,o,n,a,d,u,l,c,h,m;null===(e=BoomEmitter.emitter)||void 0===e||e.off(RECEIVE_SUBSCRIBE_MESSAGE),null===(t=BoomEmitter.emitter)||void 0===t||t.off(USER_SORT_NUM_CHANGE),null===(r=BoomEmitter.emitter)||void 0===r||r.off(HANDLE_STREAM_CONNECT_ERROR),null===(i=BoomEmitter.emitter)||void 0===i||i.off(RAISE_HAND),null===(s=BoomEmitter.emitter)||void 0===s||s.off(UNSUBSCRIBE_STREAM),null===(o=BoomEmitter.emitter)||void 0===o||o.off(MANUAL_SUBSCRIPTION),null===(n=BoomEmitter.emitter)||void 0===n||n.off(CHANG_IS_GUEST),null===(a=BoomEmitter.emitter)||void 0===a||a.off(BIND_ELEMENT),null===(d=BoomEmitter.emitter)||void 0===d||d.off(BIND_BIG_ELEMENT),null===(u=BoomEmitter.emitter)||void 0===u||u.off(NO_CONTAINER),null===(l=BoomEmitter.emitter)||void 0===l||l.off(MODEL_SORT_NUM_CHANGE),null===(c=BoomEmitter.emitter)||void 0===c||c.off(ADD_PULL_USER),null===(h=BoomEmitter.emitter)||void 0===h||h.off(SET_VOLUME),null===(m=BoomEmitter.emitter)||void 0===m||m.off(ADD_AUDIO_PLAY),BoomEmitter.emitter=void 0};class BMUser{constructor(e,t=!1){var r;this.streamModels=new Map,this.sortNum=100,this.raiseVideoHands=!1,this.raiseAudioHands=!1,this.raiseHand=!1,this.isAudience=!1,this.isCommonUser=!1,this.inBackground=!1,this.raiseHandTime=0,this.userId=e.userId,this.userInfo=e.userInfo,this.nickName=e.nickname,this.isMaster=!!e.isMaster,this.isManager=!!e.isManager,this.isToupingma=!!e.isToupingma,this.isLocal=t,this.hasMultiple=!!e.hasMultiple,this.isCreate=!!e.isCreate,this.hasShare=!!e.hasShare,this.avatar=null===(r=e.userInfo)||void 0===r?void 0:r.avatar,this.permission=e.permission,this.raiseAudioHands=!!e.raiseAudioHands,this.raiseVideoHands=!!e.raiseVideoHands,this.raiseHand=!!e.raiseHand,this.isAudience=!!e.isAudience,this.isCommonUser=!!e.isCommonUser,this.inBackground=!!e.inBackground,this.audienceEnableSpeaking=!!e.audienceEnableSpeaking,this.raiseHandTime=e.raiseHandTime||0;const i={operation:"none",user:this};this.watcher=new BehaviorSubject(i),this.updateSortNum(!1)}get isWeb(){return!(!this.userInfo.pos||!this.userInfo.pos.includes("web")&&!this.userInfo.pos.includes("pc"))}setup(e,t,r){this.isLocal=!0,this.userId=e,this.userInfo=t,this.nickName=r||t.nickname,this.avatar=t.avatar}getMainStreamModel(){return this.streamModels.get(this.userId)}get nickname(){return this.nickName}getShareStreamModel(){return this.streamModels.get(`${this.userId}${STREAM_SUFFIX_SCREEN}`)}get audioEnable(){const e=this.getMainStreamModel();return!!e&&e._audio_enable}get isMixer(){return this.userId.includes("-mixer-")}get videoEnable(){const e=this.getMainStreamModel();return!!e&&e._video_enable}get isSharing(){let e=!1;for(let t of this.streamModels.values())if(t.isShare){e=!0;break}return e}get isSignal(){var e;return!!(null===(e=this.userId)||void 0===e?void 0:e.startsWith(SIGNAL_SUFFIX))}checkLocalHasMaster(){return this.isMaster||this.isManager}addStream(e,t){this.streamModels.set(e,t),this.watcher.next({operation:"changeShare",user:this})}removeStream(e){this.streamModels.delete(e),e.includes(STREAM_SUFFIX_SCREEN)&&info("删除的是共享屏幕的流:","","",["streamId =>",e]),setTimeout((()=>{this.watcher.next({operation:"changeShare",user:this})}),400)}getID(){return this.userId}getNickName(){return this.nickName}getUserInfo(){return this.userInfo}getStreams(){return this.streamModels}updateUserInfo(e,t={},r){var i,s,o,n,a,d;const u=null===(i=null==t?void 0:t.params)||void 0===i?void 0:i.customInfo,l=(null==u?void 0:u.updateKeys)||[];let c=!1,h="none";if(info("updateUserInfo =>","updateUser",e.userId,["updateKeys",l.toString(),"permission",null===(s=e.permission)||void 0===s?void 0:s.permission,"isMaster =>",this.isMaster,"isManager =>",this.isManager]),this.nickName!==e.nickname&&(h="changeNickName"),this.isMaster||!this.isManager||e.permission.getManage()||(h="removeManager",this.isManager=!1),this.isMaster||this.isManager||!e.permission.getManage()||-1!=l.indexOf("changeMaster")||(h="getManager",this.isManager=!0),e.userinfo.pos)this.userInfo=e.userinfo;else{const t=this.userInfo.pos;this.userInfo=e.userinfo,this.userInfo.pos=t}(l.includes("changeMaster")||l.includes("permission"))&&(e.permission=t.getPermission()),l.includes("raiseHandsAudio")&&(this.raiseAudioHands=u.raiseHandsAudio,h="raiseHandsAudio",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsAudio",user:this}),c=!0),l.includes("raiseHandsVideo")&&(this.raiseVideoHands=u.raiseHandsVideo,h="raiseHandsVideo",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsVideo",user:this}),c=!0),l.includes("raiseHand")&&(this.raiseHand=u.raiseHand,this.raiseHandTime=u.raiseHandTime,h="raiseHand",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHand",user:this}),c=!0),1!==r.conferenceMode&&this.isAudience&&l.includes("permission")&&(-1!==(null===(n=null===(o=t.params)||void 0===o?void 0:o.customInfo)||void 0===n?void 0:n.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!0),this.audienceEnableSpeaking=!0,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceEnable()),-1===(null===(d=null===(a=t.params)||void 0===a?void 0:a.customInfo)||void 0===d?void 0:d.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!1),this.audienceEnableSpeaking=!1,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceDisable())),l.includes("inBackground")&&(h="inBackground",this.inBackground=u.inBackground),this.nickName=e.nickname,this.permission=e.permission;let m=!this.isCommonUser;this.isCommonUser=!e.permission.getSubscribe(),m!==!this.isCommonUser&&(info(`身份有发生过变化,从${m?"嘉宾":"普通参会者"} => ${this.isCommonUser?"普通参会者":"嘉宾"}`),BoomEmitter.emitter.emit(CHANG_IS_GUEST,{user:this,isGuest:!this.isCommonUser,preIsGuest:m})),h&&this.watcher.next({operation:h,user:this}),(!c||c&&!this.isLocal)&&this.updateSortNum(!0)}hasManager(){return this.isManager||this.isMaster}getNicknameSuffix(){let e="";return this.isLocal&&this.isMaster?e="(我、主持人)":this.isLocal&&this.isManager?e="(我、联席主持人)":this.isLocal?e="(我)":this.isMaster?e="(主持人)":this.isManager?e="(联席主持人)":this.isSharing&&!this.isToupingma?e="的共享屏幕":this.isSharing&&this.isToupingma&&(e="(仅共享屏幕)"),e}updateSortNum(e=!0,t=!1){let r=getSortNum(this);this.setSortNum(r,e,t)}setSortNum(e,t,r){this.sortNum!==e&&(this.sortNum=e,t&&BoomEmitter.emitter.emit(USER_SORT_NUM_CHANGE,{isCommon:this.isCommonUser,shouldDelay:r}))}}const NULL=null,UNDEFINED=void 0,RAW_FUNCTION="function";Object.freeze({}),Object.freeze([]);const EMPTY_STRING="";function func(e){return typeof e===RAW_FUNCTION}function indexOf(e,t,r){return e.indexOf(t,r!==UNDEFINED?r:0)}function has(e,t){return indexOf(e,t)>=0}function toString(e,t){return e!=NULL&&e.toString?e.toString():t!==UNDEFINED?t:EMPTY_STRING}function isNative(e){return func(e)&&has(toString(e),"[native code]")}typeof setImmediate===RAW_FUNCTION&&isNative(setImmediate)&&setImmediate,typeof MessageChannel===RAW_FUNCTION&&isNative(MessageChannel);const notGetTalkInterval=3e5;function handleTime(e){let t=new Date(e),r=new Date,i=t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,s=t.getDate()<10?"0"+t.getDate():t.getDate(),o=t.getHours()<10?"0"+t.getHours():t.getHours(),n=t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes();return r.setHours(0,0,0,0)==t.setHours(0,0,0,0)?o+":"+n:i+"月"+s+"日 "+o+":"+n}function sortUsers(e){return e.sort(((e,t)=>e.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND&&t.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND?e.raiseHandTime-t.raiseHandTime:e.sortNum-t.sortNum))}function sortStreamModels(e){return e.sort(((e,t)=>e.sortNum!==t.sortNum?t.sortNum-e.sortNum:Number(e.getUser().isCommonUser)-Number(t.getUser().isCommonUser)))}function getIsCommonUser(e){return!getPermission(e,"s")}function getIsManager(e){return getPermission(e,"m")}function getIsMaster(e){return getPermission(e,"o")}function getPermission(e,t){return e.toLowerCase().includes(t)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}const ignoreUserId=["-mixer-","-rtmpmixer-","record#","robot_","stt_"],BLOUD_PAGE_SIZE=500,PERMISSION_NOT_COMMON="RWPSAVMO,RWPSAVM,RWPSAV";class BMUserVM{constructor(e,t,r){this.userList=new Map,this.audiencesList=new Map,this.signalList=new Map,this.commonUserList=new Map,this.userListWatcher=new BehaviorSubject(Array.from(this.userList.values())),this.audiencesListWatcher=new BehaviorSubject(Array.from(this.audiencesList.values())),this.commonUserListWatcher=new BehaviorSubject(Array.from(this.commonUserList.values())),this.signalListWatcher=new BehaviorSubject(Array.from(this.signalList.values())),this.masterUserWatcher=new BehaviorSubject(null),this.getForceUserWatcher=new BehaviorSubject(!1),this.commTimer=200,this.addBCUser=(e,t=!1)=>{var r;const i=this.addUser(e);if(!this.room.bmStreamVm.streamModels.get(e.userId)){const t=this.getUser(e.userId);t?this.room.bmStreamVm.createStreamModel(t):error$1(`there is no user named ${e.userId}, and create streamModel failed!!!`)}{const i=this.room.bmStreamVm.streamModels.get(e.userId);i&&(e.stream.size?e.stream.forEach((r=>__awaiter(this,void 0,void 0,(function*(){var s,o,n;const{video_enable:a,audio_enable:d,customInfo:u}=r;if(r.screen){this.room.bmStreamVm.shareBloudStateMap.set(e.userId,{audio:d,video:a,customInfo:u,userId:e.userId,streamId:r.getID(),isScreen:!0});const n={id:i.userId,isScreen:!0,isWeb:i.isWeb};if(t){const t=new Map;t.set(e.userId,n),yield null===(s=this.room)||void 0===s?void 0:s.processUser(t)}else null===(o=this.room)||void 0===o||o.addUser2Queue(n)}else if(i&&(i.updateBloudStream({video:a,audio:d,isScreen:r.screen,customInfo:u},this.room.bmStreamVm),t)){const t={id:i.userId,isScreen:!1,isWeb:i.isWeb},r=new Map;r.set(e.userId,t),null===(n=this.room)||void 0===n||n.processUser(r)}})))):(i.bloudStream&&i.updateBloudStream(void 0,this.room.bmStreamVm),null===(r=this.room)||void 0===r||r.bmStreamVm.removeShareStreamModelByUId(e.userId)))}return i&&i.isMaster&&this.masterUserWatcher.next(i),null==i||i.updateSortNum(!1),i},this.updateAllSort=()=>{this.updateUserSort(),this.updateCommonUserSort()},this.updateSortByType=e=>{var t,r;(null===(t=this.room)||void 0===t?void 0:t.isSingleColumns)||e.isCommon?(null===(r=this.room)||void 0===r?void 0:r.isBig)&&e.shouldDelay?this.updateDelayCommonUserSort():this.updateCommonUserSort():this.updateUserSort()},this.updateUserSort=debounce((()=>{const e=this.sortUsers();this.userListWatcher.next(BMUserVM.filterUsers(e))}),200,{maxWait:1e3}),this.updateCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),this.commTimer,{maxWait:12e3}),this.updateDelayCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),12e4,{maxWait:12e4}),this.updateAudienceUserSort=()=>{const e=this.sortAudiences();this.audiencesListWatcher.next(BMUserVM.filterUsers(e))},this.updateSignalUserSort=()=>{const e=this.sortSignalUsers();this.signalListWatcher.next(e)},this.transBloudUsers=(e,t="",r=!1,i=0)=>__awaiter(this,void 0,void 0,(function*(){const s=new Map;yield this.getAllUsers(e,s,t,r).catch((()=>i<3?(error$1("get bloud user error, retry"),i+=1,void this.transBloudUsers(e,t,r,i)):void error$1("get current page of bloud users after 10 times final failed","","",[" page ",e," permission ",t]))),yield this.initUserList(s),s.clear();let o=[];for(let e of this.userList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&o.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&o.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands)&&o.push(e);this.room.roomInfo.setRaiseHandsList(o),this.updateAllSort(),this.room.bmStreamVm.updateModelSort()})),this.boomCore=e,this.localUser=t,this.room=r,BoomEmitter.emitter||error$1("init boom emitter error"),BoomEmitter.emitter.on(CHANG_IS_GUEST,this.handleUserRoleChange.bind(this)),BoomEmitter.emitter.on(USER_SORT_NUM_CHANGE,this.updateSortByType)}handleUserRoleChange(e){var t,r,i;return __awaiter(this,void 0,void 0,(function*(){const{user:s,isGuest:o,preIsGuest:n}=e,a=null===(t=this.room)||void 0===t?void 0:t.roomInfo.isBigRoom;info("handleUserRoleChange","",s.userId,["isGuest =>",o,"preIsGuest =>",n,"isBigRoom =>",a]);if(1===(null===(r=this.room)||void 0===r?void 0:r.userListColumns)||(n?this.userList.delete(s.userId):this.commonUserList.delete(s.userId),o?this.userList.set(s.userId,s):this.commonUserList.set(s.userId,s)),a)if(o)s.isLocal&&(yield this.initUsers());else{const e=null===(i=this.room)||void 0===i?void 0:i.getLocalParticipant().isCommonUser;if(s.isLocal&&(this.handleUnSubCommonUser(),this.handleCommonUserChange(),this.commonUserList.set(s.userId,s)),e){const e=s.getMainStreamModel();e&&e.unSubscribeStream(),s.isLocal||this.commonUserList.delete(s.userId)}}this.updateAllSort()}))}addUser(e){var t;const r=this.getUser(e.userId);if(r)return info("该用户已经加入房间",LOGGER_TAG_CLIENT,e.userId),this.updateUser(r,e),null;let i;return this.boomCore.userId==e.userId?(this.updateUser(this.localUser,e),i=this.localUser):i=this.toBMUser(e),1===(null===(t=this.room)||void 0===t?void 0:t.userListColumns)?this.commonUserList.set(i.userId,i):i.isAudience?this.audiencesList.set(i.userId,i):i.isSignal?this.signalList.set(i.userId,i):i.isCommonUser?this.commonUserList.set(i.userId,i):this.userList.set(i.userId,i),i}removeUser(e){let t=this.userList.delete(e);return t||(t=this.signalList.delete(e)),t||(t=this.audiencesList.delete(e)),t||(t=this.commonUserList.delete(e)),t||warn("userList中未找到该用户, 移除无效",LOGGER_TAG_CLIENT,e),t}videoEnable(e){const t=this.getUser(e);if(t)return t.videoEnable;throw new BoomError(USER_NOT_EXIT,"用户不存在")}audioEnable(e){const t=this.getUser(e);if(t)return t.audioEnable;throw new BoomError(USER_NOT_EXIT,"用户不存在")}checkIsMaster(e){if(!e)return!1;const t=this.boomCore.getMaster();return!!t&&t===e}checkLocalHasMaster(){return this.localUser.isMaster||this.localUser.isManager}checkUserHasMaster(e){const t=this.userList.get(e);return!!t&&t.permission.getManage()}getUser(e){let t;return t=(null==e?void 0:e.startsWith(SIGNAL_SUFFIX))?this.signalList.get(e):this.userList.get(e),t||(t=this.commonUserList.get(e)),t||(t=this.audiencesList.get(e)),t}getAllUsers(e,t,r="",i=!1){return __awaiter(this,void 0,void 0,(function*(){let s;if(i){let{users:t,total:i}=yield this.boomCore.getUsersList(e,r,BLOUD_PAGE_SIZE);s=t}else{let{users:t,total:i}=yield this.boomCore.getUsers(e,r,BLOUD_PAGE_SIZE);s=t}s.forEach((e=>{t.set(e.userId,e)}))}))}initUserList(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){const i=e.get(this.localUser.userId);if(i){const e=this.addUser(i);if(!(null===(t=this.room)||void 0===t?void 0:t.bmStreamVm.getStreamModelByUId(i.userId))){const e=this.getUser(i.userId);e?null===(r=this.room)||void 0===r||r.bmStreamVm.createStreamModel(e):error$1("there is no local streamModel exits, and create failed!!!")}(null==e?void 0:e.isMaster)&&this.masterUserWatcher.next(e)}e.delete(this.localUser.userId),e&&e.size>0&&this.addBcUsersMap(e)}))}addBcUsersMap(e,t=!1){e.forEach((e=>{this.addBCUser(e,t)}))}updateMaster(e,t,r){const i=this.getUser(e);i&&(i.isManager&&(i.isManager=!1),i.isMaster=!0,i.updateSortNum());const s=this.getUser(t);return s&&(s.isMaster=!1,r&&(s.isManager=!0),s.updateSortNum()),i||s||error$1("未找到该用户, updateMaster未生效",LOGGER_TAG_CLIENT,e,["masterId => ",e,"oldMasterId => ",t]),{master:i,oldMaster:s}}managerChangeToGuest(e){const t=this.getUser(e);return t?t.isManager?(t.permission.setManage(!1),t.permission.setSubscribe(!0),this.boomCore.updateUser(e,{customInfo:{permission:t.permission.get()}}),t.watcher.next({operation:"getGuest",user:t}),this.updateAllSort()):error$1("该用户不是管理员,无法设置为嘉宾",LOGGER_TAG_CLIENT,e):error$1("未找到该用户, managerChangeToGuest未生效",LOGGER_TAG_CLIENT,e),t}updateManager(e,t,r=!0){const i=this.getUser(e);return i?(i.permission.setManage(t),i.permission.setSubscribe(t),this.boomCore.updateUser(e,{customInfo:{permission:i.permission.get()}}),i.watcher.next({operation:t?"getManager":"removeManager",user:i}),this.updateAllSort()):error$1("userList中未找到该用户, updateManager未生效",LOGGER_TAG_CLIENT,e),i}getLocalUser(){return this.localUser}updateUser(e,t){var r,i,s,o,n;const a=this.checkIsMaster(t.userId),d=((null===(r=t.permission)||void 0===r?void 0:r.getManage())||getIsManager(null===(i=t.permission)||void 0===i?void 0:i.permission))&&!((null===(s=t.permission)||void 0===s?void 0:s.getOwn())||getIsMaster(null===(o=t.permission)||void 0===o?void 0:o.permission));let u="none";const l=e.isMaster;e.isManager!==d&&(u=d?"getManager":"removeManager"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),10),l!==a&&(u=a?"getMaster":"removeMaster"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),100);const c=e.raiseHand,h=t.customInfo.raiseHand;c!==h&&(!h&&c&&this.room.roomInfo.removeSimpleRaiseHandUser(e.userId),setTimeout((()=>{e.watcher.next({operation:"raiseHand",user:e})}),300));const m=e.raiseVideoHands,p=t.customInfo.raiseHandsVideo;m!==p&&(!p&&m&&this.room.roomInfo.removeVideoRaiseHandUser(e.userId),setTimeout((()=>{e.watcher.next({operation:"raiseHandsVideo",user:e})}),300));const f=e.raiseAudioHands,v=t.customInfo.raiseHandsAudio;f!==v&&(!v&&f&&this.room.roomInfo.removeRaiseHandUser(e.userId),setTimeout((()=>{e.watcher.next({operation:"raiseHandsAudio",user:e})}),300));e.nickname!==t.nickname&&setTimeout((()=>{e.watcher.next({operation:"changeNickName",user:e})}),300),e.userInfo=t.userinfo,e.nickName=t.nickname,e.userId=t.userId,e.permission=t.permission,e.avatar=t.userinfo.avatar,e.isToupingma=t.userinfo.pos.includes("_toupingma"),e.raiseHand=h,e.isMaster=a,e.isCreate=this.boomCore.getCreator()===t.userId,e.isAudience=!t.permission.getAudio(),e.isCommonUser=!t.permission.getSubscribe(),e.isManager=d,e.inBackground=!!(null===(n=null==t?void 0:t.customInfo)||void 0===n?void 0:n.inBackground),e.updateSortNum()}updateLocalUserPermission(e){const t=this.getLocalUser();t.isMaster=getIsMaster(e),t.isManager=!getIsMaster(e)&&getIsManager(e),t.isCommonUser=getIsCommonUser(e),t.watcher.next({operation:"none",user:t})}toBMUser(e){var t,r;let i={};i.userInfo=e.userinfo,i.nickname=e.nickname,i.userId=e.userId,i.streamModels=[],i.permission=e.permission,i.stream=e.stream,i.isToupingma=!(!e.userinfo.pos||!e.userinfo.pos.includes("_toupingma")),i.isMaster=this.checkIsMaster(i.userId),i.isAudience=!e.permission.getAudio(),i.isCommonUser=!e.permission.getSubscribe()||getIsCommonUser(e.permission.permission),i.raiseAudioHands=e.customInfo.raiseHandsAudio,i.raiseVideoHands=e.customInfo.raiseHandsVideo,i.raiseHand=e.customInfo.raiseHand,i.raiseHandTime=e.customInfo.raiseHandTime,i.inBackground=e.customInfo.inBackground,i.isCreate=this.boomCore.getCreator()===e.userId;let s=this.boomCore.getLocalParticipant();if(!s)throw new BoomError(INVALID_PARAMETER,"BCUserVM addUser时未找到本地用户");return s.getID()==i.userId&&(i.isLocal=!0),!(null===(t=i.permission)||void 0===t?void 0:t.getManage())&&!getIsManager(null===(r=i.permission)||void 0===r?void 0:r.permission)||i.isMaster||(i.isManager=!0),new BMUser(i,i.isLocal)}sortUsers(){return sortUsers(Array.from(this.userList.values()))}sortAudiences(){return sortUsers(Array.from(this.audiencesList.values()))}sortCommonUsers(){return sortUsers(Array.from(this.commonUserList.values()))}sortSignalUsers(){return sortUsers(Array.from(this.signalList.values()))}static filterUsers(e){return e.filter((e=>!ignoreUserId.some((t=>e.userId.includes(t)))))}initUsers(){var e;return __awaiter(this,void 0,void 0,(function*(){const t=yield this.getTotalUserNumber();info(`initUsers total users num: ${t}`);const r=Math.ceil(t/BLOUD_PAGE_SIZE);let i=0;const s=[],o=e=>__awaiter(this,void 0,void 0,(function*(){e<r&&(yield this.transBloudUsers(e-1))})),n=e=>__awaiter(this,void 0,void 0,(function*(){for(const t of e)yield t(),yield sleep(50)}));if(this.localUser.isCommonUser&&(null===(e=this.room)||void 0===e?void 0:e.isBig))this.commonUserList.set(this.localUser.userId,this.localUser),yield this.transBloudUsers(-1,PERMISSION_NOT_COMMON,!0);else{for(;i<r;)s.push(o.bind(null,i)),i+=1;n(s)}}))}handleUnSubCommonUser(){this.commonUserList.forEach((e=>{const t=e.getMainStreamModel();(null==t?void 0:t.hasPulled)&&t.unSubscribeStream()}))}handleCommonUserChange(){let e=new Map;this.room.bmStreamVm.streamModels.forEach((t=>{t.getUser().isCommonUser&&!t.isLocal||e.set(t.userId,t)})),this.room.bmStreamVm.streamModels=e,this.commonUserList.clear()}getUsers(e,t,r="RWPAV"){return __awaiter(this,void 0,void 0,(function*(){const{users:i,total:s}=yield this.boomCore.getUsers(e,r,t),o=[];return i.forEach((e=>{const t=this.toBMUser(e);o.push(t)})),{userList:o,total:s}}))}getUsersList(e,t,r="",i=!1){var s,o;return __awaiter(this,void 0,void 0,(function*(){const{users:n,total:a,pageIndex:d}=yield this.boomCore.getUsersList(e,r,t,i),u=[];return n.forEach((e=>{const t=this.toBMUser(e);u.push(t)})),i&&(null===(s=this.room)||void 0===s?void 0:s.roomInfo.totalWaitRoomUserWatcher.value)!==a&&(null===(o=this.room)||void 0===o||o.roomInfo.totalWaitRoomUserWatcher.next(a)),{userList:u,total:a,pageIndex:d}}))}getTotalUserNumber(){return __awaiter(this,void 0,void 0,(function*(){const e=()=>__awaiter(this,void 0,void 0,(function*(){const{total:e}=yield this.boomCore.getUsers(0,"",1);return e})),t=r=>{e().then((e=>{r(e)})).catch((e=>{error$1("getTotalUserNumber error","","",[JSON.stringify(e)]),t(r)}))};return new Promise(((e,r)=>__awaiter(this,void 0,void 0,(function*(){t(e)}))))}))}clearUsers(){this.userList.clear(),this.commonUserList.clear(),this.audiencesList.clear(),this.signalList.clear()}searchUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!1);let i=[],s=[];return r.forEach((e=>{const t=this.userList.get(e.userId);if(t)return void i.push(t);const r=this.commonUserList.get(e.userId);r&&s.push(r)})),{userList:i,commonUserList:s}}catch(e){return Promise.reject(new BoomError(LOCAL_ERROR,"boomCore.searchUsers发生错误:"+(null==e?void 0:e.message)))}}))}searchWaitRoomUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!0),i=[];return r.forEach((e=>{const t=this.toBMUser(e);i.push(t)})),i}catch(e){return Promise.reject(new BoomError(LOCAL_ERROR,"search wait room users error"))}}))}}class BMMessageInfo{constructor(e){this.isMeetingNotice=!1,this.userId=e.userId,this.message=e.message,this.role=e.role,this.isLocal=e.isLocal,this.avatar=e.avatar,this.nickName=e.nickName,this.to=e.to,this.isDanger=e.isDanger,this.seq=e.seq,this.failed=e.failed;let t=!1;e.isMeetingNotice&&(t=!0),this.isMeetingNotice=t,e.sendTime?(this.timeStamp=e.sendTime,this.time=handleTime(this.timeStamp)):(this.timeStamp=(new Date).getTime(),this.time=handleTime(this.timeStamp))}}function isShareStream(e){const t=e.getStreamId();return e.getUserId().toString().endsWith(STREAM_SUFFIX_SCREEN)||t.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()}function checkStreamIsNormal(e){var t,r,i,s;if(e&&!e.isLocal){(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(s=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===s?void 0:s.call(i)))&&setTimeout((()=>{var t,r,i,s;(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(s=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===s?void 0:s.call(i)))&&(warn("用户流检测,但是流订阅出现了问题,需要重新订阅","用户流检测",e.userId,[" nickname => ",e.nickname,"isDisplay =>",e.isDisplay]),e.hasPulled=!1,e.pulledStreamType="small",e.sendMessage2Room())}),2e3)}}function handleBloudReconnectStreamEvent(e){var t,r;const i=e.getLocalStreamModel();if(i&&!(null==i?void 0:i.stream))e.bloudStream&&(info("brtc 已经没有流了,bloud 的流要取消掉"),e.bloudStream.unpublish(),i.updateBloudStream(void 0,e),e.bloudStream=null);else if(i&&i.stream){info("brtc 流已经重推上去了,bloud要重新发推流的逻辑");const t=i.stream.getAudioOn(),r=i.stream.getVideoOn();e.publishBloudStream(t,r).then((()=>{info("brtc stream repub success bloud repub success, notify reconnect success"),e.localStreamConnectErrorWatcher.next(Rr$1(t,r))}))}if(e.localIsShare){info("brtc has share stream, and bloud need to republish share stream");const i=null===(t=e.room)||void 0===t?void 0:t.boomCore.shareScreenStream;if(i){const t=i.getAudioOn(),s=i.getVideoOn();try{null===(r=e.room)||void 0===r||r.boomCore.createAndPubBloudShareStream(t,s)}catch(e){error$1("bloud 共享屏幕流,断网重连重推流失败")}}}}const handleReconnectedStream=debounce((e=>{if(e.networkState.bloud&&e.networkState.brtc)try{e.streamQueue.restart()}catch(t){e.streamQueue.setQueueProcessor(e.queueProcessor),e.streamQueue.restart()}}),300);function handleStreamPublished(e,t,r,i){const s=e.stream;if(info("本地推流","本地推流",s.getUserId()),s){const e=t.getLocalStreamModel();if(e&&t.updateStreamModel(e,s),i[dt$1.STREAM_PUBLISHED].next({published:!0,model:e}),1===r.conferenceMode){r.getLocalParticipant().isAudience&&t.getStreamModels().forEach((e=>{e.sendMessage2Room()}))}}else i[dt$1.STREAM_PUBLISHED].next({published:!1})}function handleBloudStreamPublished(e,t,r){info("bloud publish stream"),handleBloudStreamPubAUpdate(e,t,!0),r[H$1.STREAM_PUBLISHED].next(e)}function handleBloudStreamPubAUpdate(e,t,r=!1){var i;info("bloud stream update","","",[JSON.stringify(e)]);const s=e.userId,o=e.isScreen,n=t.streamModels.get(s);if(n)if(o){t.shareBloudStateMap.set(s,e);const r={id:s,isWeb:n.isWeb,isScreen:o};null===(i=t.room)||void 0===i||i.addUser2Queue(r)}else n.updateBloudStream(e,t,r),n.getUser().updateSortNum();else error$1("bloud stream update, but can not get streamModel","",s)}function handleBloudStreamUnPublished(e,t,r){info("bloud unpublish stream","","",[JSON.stringify(e)]),handleBloudStreamUnpublish(e,t),r[H$1.STREAM_REMOVED].next(e)}function handleBloudStreamUpdated(e,t,r){info("bloud stream update","","",[JSON.stringify(e)]);const i=e.streamId,s=e.userId,o=e.params.customInfo;let n;n=i.includes("_screen")?t.shareStreamModels.get(s):t.streamModels.get(s),n?n.updateBloudCustomInfo(o):error$1("bloud stream update, but can not get streamModel","",s,["streamId =>",i]),r[H$1.UPDATE_STREAM].next(e)}function handleBloudStreamUnpublish(e,t){var r,i,s;const o=e.userId;if(e.isScreen){const e=t.shareStreamModels.get(o);if(e){const r=e.stream;r?(r.destroy(),t.remoteStreamUnpublished(r)):t.removeShareStreamModelByUId(o);const i={id:o,isWeb:e.isWeb,isScreen:!0};null===(s=t.room)||void 0===s||s.streamQueue.removeUsers([i])}}else{const e=t.streamModels.get(o);if(e){e.updateBloudStream(void 0,t);const s=e.stream;s&&(null===(r=t.room.audioPlayer)||void 0===r||r.removeStream(s),t.remoteStreamUnpublished(s),s.destroy());const n={id:o,isWeb:e.isWeb,isScreen:!1};null===(i=t.room)||void 0===i||i.streamQueue.removeUsers([n])}}}function handleShareStreamFailed(e,t){setTimeout((()=>__awaiter(this,void 0,void 0,(function*(){info("handle republish share stream");try{const r=e.boomCore.shareScreenStream;if(r){const i=r.getAudioOn(),s=r.getVideoOn();yield e.boomCore.shareBrtcClient.publish(r),e.boomCore.createAndPubBloudShareStream(i,s),info("handle republish share stream success"),t.localShareError.next(Or$1())}else warn("no share stream exist, unpublish share stream, to prevent share stream state error"),t.toggleShareScreen(!1,void 0)}catch(e){error$1("handle republish share stream failed , now unpublish"),t.localShareError.next(Ar()),yield t.toggleShareScreen(!1,void 0)}}))),1e3)}function setupRoomInfo(e,t,r){const i=e.permission,s=e.total;i&&r.updateLocalUserPermission(i),t.isInWaitRoom=e.joinwait;const o=e.waitroom;t.roomInfo.isOpenWaitRoom.next(o),t.roomInfo.totalUserWatcher.next(s);const n=e.audiooff,a=e.selfopenaudio;n===t.roomInfo.audioOff&&a===t.roomInfo.selfopenaudio||null!=n&&null!=a&&t.roomInfo.setAudioOff(n,a)}function handleRoomConnected(e,t,r,i,s=!0){var o;return __awaiter(this,void 0,void 0,(function*(){info("room-connected",t.getLocalParticipant().userId,"room-connected",["roomId =>",t.roomInfo.roomID," local permission => ",e.permission]),t.forceId=null===(o=e.customStats.forceOn)||void 0===o?void 0:o.user,handleInitRoomInfo(e,t),setupRoomInfo(e,t,r),s&&i[H$1.ROOM_CONNECTED].next(e)}))}function handleInitJoinRoomUsers(e){return __awaiter(this,void 0,void 0,(function*(){info("join ready init users"),e.isInWaitRoom||(e.forceId&&(yield e.getForceUser(e.forceId)),yield e.userVM.initUsers())}))}function handleRoomUpdated(e,t){info("update-stats "," ","",["options => ",JSON.stringify(e.options)]),e.options&&"audiooff"==e.options[0]||"selfopenaudio"==e.options[1]?t.roomInfo.setAudioOff(e.room.audiooff,e.room.selfopenaudio):e.options&&"lock"==e.options[0]?t.roomInfo.setlock(e.room.lock):e.options&&"waitroom"==e.options[0]&&t.roomInfo.isOpenWaitRoom.next(e.stats.waitroom)}function handleInitRoomInfo(e,t){t.roomInfo.msgSeq=e.msgSeq,e.customStats&&t.roomInfo.initCustomStats(e.customStats)}function exitUserUpdateStream(e,t,r,i,s){var o;e.updateUser(t,r);const n=r.stream,a=i.streamModels.get(t.userId);if(a||error$1("bmUserVM中存在该用户,但是bmStreamModelVM中不存在该用户,佛了"),!n.size){(null==a?void 0:a.bloudStream)&&(a.updateBloudStream(void 0,i),s.streamQueue.removeUsers([{id:t.userId,isScreen:!1},{id:t.userId,isScreen:!0}]));const e=i.shareStreamModels.get(t.userId);if(e&&!e.isLocal){try{null===(o=e.stream)||void 0===o||o.destroy()}catch(e){}i.removeShareStreamModel(e)}}n.get(`${t.userId}_screen`)&&s.addUser2Queue({id:t.userId,isScreen:!0,isWeb:t.isWeb});const d=n.get(t.userId);d&&(null==a||a.updateBloudStream({audio:d.audio_enable,video:d.video_enable,isScreen:!1},i))}function addUsers(e,t,r,i){e.isSingleColumns?t.commonUserList.forEach((s=>{const o=r.get(s.userId);if(o)return r.delete(s.userId),void exitUserUpdateStream(t,s,o,i,e);t.commonUserList.delete(s.userId),i.streamModels.delete(s.userId),i.shareStreamModels.delete(s.userId)})):t.userList.forEach((s=>{const o=r.get(s.userId);if(o)return exitUserUpdateStream(t,s,o,i,e),void(s.isCommonUser?t.userList.delete(s.userId):r.delete(s.userId));t.userList.delete(s.userId),i.streamModels.delete(s.userId),i.shareStreamModels.delete(s.userId)})),e.userVM.addBcUsersMap(r)}function handleRoomSync(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){const s=t.getLocalParticipant().userId,{users:o}=yield t.boomCore.queryUsers([s]),n=o.get(s);n&&r.updateUser(r.localUser,n);const a=t.getLocalParticipant().isCommonUser;if(t.isBig&&a){const{users:e}=yield t.boomCore.getUsersList(0,PERMISSION_NOT_COMMON,500);addUsers(t,r,e,i)}else{const e=(yield t.userVM.getTotalUserNumber())/BLOUD_PAGE_SIZE;let s=new Map;for(let r=0;r<e;r++){let{users:e}=yield t.boomCore.getUsers(r-1,"",BLOUD_PAGE_SIZE);e.forEach((e=>{s.set(e.userId,e)}))}addUsers(t,r,s,i)}handleInitRoomInfo(e,t),t.userVM.updateAllSort(),t.bmStreamVm.updateModelSort()}))}function handleBrtcRoomReconnecting(e,t,r){info("brtc room reconnecting"),t.networkState.brtc=!1,t.streamWSReconnectWatcher.next(!1),r[dt$1.BRTC_ROOM_ROCONNECTING].next(e)}function handleBrtcRoomReconnected(e,t,r){info("brtc room reconnected"),t.networkState.brtc=!0,handleReconnectedStream(t),r[dt$1.BRTC_ROOM_RECONNECTED].next(e)}function handleBloudRoomReconnecting(e,t,r){info("bloud room reconnecting"),t.networkState.bloud=!1,t.bloudWSReconnectWatcher.next(!1),r[H$1.RECONNECTING].next(e)}function handleBloudRoomReconnected(e,t,r){return __awaiter(this,void 0,void 0,(function*(){t.hasSyncPermission?(info("bloud room reconnected"),t.bloudWSReconnectWatcher.next(!1),r[H$1.MOVE_USER_ROOM].next(null),yield t.syncRoom().then((()=>{t.hasSyncPermission=!0,r[H$1.ROOM_CONNECTED].next(e)})).catch((e=>{error$1("sync room error",JSON.stringify(e));if(43===e.code)return t.hasSyncPermission=!1,void r[H$1.USER_REJOINED].next(e);t.hasSyncPermission=!1,r[H$1.TIMEOUT].next(e)}))):r[H$1.TIMEOUT].next(e)}))}function handleBloudRoomSync(e,t,r,i,s){return __awaiter(this,void 0,void 0,(function*(){info("bloud sync room completed"),setupRoomInfo(e,r,t),yield handleRoomSync(e,r,t,i),handleBloudReconnectStreamEvent(i),r.networkState.bloud=!0,handleReconnectedStream(r),r.bloudWSReconnectWatcher.next(!0),s[H$1.ROOM_SYNCED].next(e)}))}const{USER_REJOINED:USER_REJOINED,PARTICIPANT_JOINED:PARTICIPANT_JOINED,CHANGE_MASTER:CHANGE_MASTER,EVICTED:EVICTED,UPDATE_USER:UPDATE_USER,PARTICIPANT_LEFT:PARTICIPANT_LEFT,CUSTOM_MESSAGE:CUSTOM_MESSAGE,MOVE_USER_ROOM:MOVE_USER_ROOM}=H$1;function handleParticipantJoin(e,t,r,i,s,o){var n,a,d,u,l,c,h,m,p,f,v,g,S;const b=null===(a=null===(n=null==e?void 0:e.participant)||void 0===n?void 0:n.params)||void 0===a?void 0:a.info.sync,y=e.mode;info("用户入会","用户入会",e.user.userId,["sync => ",b,"mode =>",y]);const _=t.room.isBig&&r.streamModels.size>1e3;let E=!1;if(b){let r=t.userList.get(e.user.userId);if(r||(r=t.commonUserList.get(e.user.userId)),r)return void(r.inBackground!=!!(null===(u=null===(d=e.user)||void 0===d?void 0:d.customInfo)||void 0===u?void 0:u.inBackground)&&(r.inBackground=!!(null===(c=null===(l=e.user)||void 0===l?void 0:l.customInfo)||void 0===c?void 0:c.inBackground),r.watcher.next({operation:"inBackground",user:r})))}1===y&&(null===(h=t.room)||void 0===h?void 0:h.isBig)&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId));if(getIsCommonUser(e.user.permission.permission)){t.userList.get(e.user.userId)&&(t.userList.delete(e.user.userId),r.streamModels.delete(e.user.userId),E=!0)}else{const i=t.commonUserList.get(e.user.userId);(null===(m=t.room)||void 0===m?void 0:m.isSingleColumns)||i&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId),E=!0)}let M=t.addBCUser(e.user);if(M){M.inBackground!=!!(null===(f=null===(p=e.user)||void 0===p?void 0:p.customInfo)||void 0===f?void 0:f.inBackground)&&(M.inBackground=!!(null===(g=null===(v=e.user)||void 0===v?void 0:v.customInfo)||void 0===g?void 0:g.inBackground),M.watcher.next({operation:"inBackground",user:M}));let n=!1;if(ignoreUserId.forEach((e=>{(null==M?void 0:M.userId.includes(e))&&(n=!0)})),E?t.updateAllSort():(null===(S=t.room)||void 0===S?void 0:S.isSingleColumns)?t.updateCommonUserSort():M?M.isCommonUser?_?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),!n){if(1!==e.mode){const e=new BMMessageInfo({isMeetingNotice:!0,userId:M.userId,message:M.nickName+"加入"+(2==i.roomType?"直播":"会议")});s.addMessage(e,!0)}o[PARTICIPANT_JOINED].next({user:M,mode:y,data:e})}}}function handleLeaveUsers(e,t,r,i,s,o,n){var a;const d=e.userIds;info("bloud leave users","","",["userIds =>",d]),d.length&&(d.forEach((e=>{const a=leaveUser(e,t,r,s);a&&sendLeveNotification(a,o,n,i,!0,0)})),(null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():t.updateAllSort(),s.updateModelSort())}function handleParticipantLeft(e,t,r,i,s,o,n){var a;info(`bloud participant left ===>${e.userId}, ${e.mode}`);const d=1===e.mode,u=e.userId,l=r.isBig&&s.streamModels.size>1e3;if(u){const c=leaveUser(u,t,r,s);if((null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():c?c.isCommonUser?l?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),s.updateModelSort(),d)return void i[PARTICIPANT_LEFT].next({user:c,mode:e.mode,data:e});c&&sendLeveNotification(c,o,n,i,1!==e.mode,e.mode)}else warn("participant-left触发=======>但是该用户信息不存在",LOGGER_TAG_CLIENT,null,[e.userId]),i[PARTICIPANT_LEFT].next({user:e.userId,mode:e.mode,data:e})}function sendLeveNotification(e,t,r,i,s,o){let n=!1;if(ignoreUserId.forEach((t=>{(null==e?void 0:e.userId.includes(t))&&(n=!0)})),!n){if(s){const i=new BMMessageInfo({isMeetingNotice:!0,userId:e.userId,message:(null==e?void 0:e.nickName)+"离开"+(2==t.roomType?"直播":"会议")});r.addMessage(i,!0)}i[PARTICIPANT_LEFT].next({user:e,mode:o})}}function leaveUser(e,t,r,i){const s=t.getUser(e);return t.removeUser(e),r.streamQueue.removeUsers([{id:e,isScreen:!1},{id:e,isScreen:!0}]),i.removeStreamModelByUId(e),i.removeShareStreamModelByUId(e),r.roomInfo.removeRaiseHandUser(e),r.roomInfo.removeVideoRaiseHandUser(e),r.roomInfo.removeSimpleRaiseHandUser(e),i.shareBloudStateMap.delete(e),s}function handleChangeMaster(e,t,r,i,s){info("changeMaster =>","changeMaster","",["master: => ",e.master,"oldMaster =>",e.oldMaster]);const o=e.master,n=e.oldMaster,a=e.isKeep;if(o){let d=t.updateMaster(o,n,a);d.master&&(d.master.watcher.next({operation:"getMaster",user:d.master}),r.userVM.masterUserWatcher.next(d.master)),d.oldMaster&&(d.oldMaster.watcher.next({operation:"removeMaster",user:d.oldMaster}),a&&d.oldMaster.watcher.next({operation:"getManager",user:d.oldMaster}));const u=s.getStreamModelByUId(n),l=s.getStreamModelByUId(o);null==u||u.updateSortNum(),null==l||l.updateSortNum(),i[CHANGE_MASTER].next({master:d.master,oldMaster:d.oldMaster,data:e})}else warn("change-master触发=======>但是房间内找不到master",LOGGER_TAG_CLIENT,null,o),i[CHANGE_MASTER].next(null)}function handleEvict(e,t,r,i,s){var o;const n=e.userId,a=t.getUser(n);info("踢出用户 => ","evict ",null==a?void 0:a.userId,["nickname => ",null==a?void 0:a.nickName]);const d=leaveUser(n,t,i,r);(null===(o=t.room)||void 0===o?void 0:o.isSingleColumns)?t.updateCommonUserSort():d?d.isCommonUser?t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),s[EVICTED].next(e)}function handleUpdateUser(e,t,r,i,s){var o,n;if(info("用户信息被改变","",null===(o=e.user)||void 0===o?void 0:o.userId),null===(n=e.user)||void 0===n?void 0:n.userId){let o=t.getUser(e.user.userId),n=i.getStreamModelByUId(e.user.userId);o?o.updateUserInfo(e.user,e.participant,r):console.warn("participant-update: bmUser is null"),n&&n.updateSortNum(!0),s[UPDATE_USER].next({bmUser:o,params:e.participant.params})}}const handleUserRejoined=debounce(((e,t)=>{e[USER_REJOINED].next(t)}),1e3);function handleMoveUserRoom(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){info("bloud move user room","","",[r]);const s=r.toWait;if(e.isInWaitRoom=s,s){e.handleResetOtherStreamStatus(),t.userList.clear(),t.userListWatcher.next([]),t.commonUserList.clear(),t.commonUserListWatcher.next([]),t.getForceUserWatcher.next(!1),e.bmStreamVm.streamModels.clear(),e.bmStreamVm.clearDetector(),e.bmStreamVm.speakerWatcher.next(null),i[CUSTOM_MESSAGE].next(null),e.messageWatcher.next({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),e.audioPlayer.destroy();const r=e.bmStreamVm.localModel;r&&e.bmStreamVm.streamModels.set(r.userId,r),e.bmStreamVm.streamModelsWatcher.next([]),e.bmStreamVm.shareStreamModels.clear(),e.bmStreamVm.shareStreamModelsWatcher.next([]),e.roomInfo.raiseHandsWatcher.next([]),e.roomInfo.raiseVideoHandsWatcher.next([]),e.roomInfo.raiseSimpleHandsWatcher.next([]),i[MOVE_USER_ROOM].next(s),Object.values(e.observes).forEach((e=>{e.next(null)}))}else{const{audiooff:o,selfopenaudio:n,lock:a}=r.info;a!==e.roomInfo.lock&&e.roomInfo.setlock(a),o===e.roomInfo.audioOff&&n===e.roomInfo.selfopenaudio||e.roomInfo.setAudioOff(o,n),yield handleRoomConnected(r.info,e,t,i,!0),yield handleInitJoinRoomUsers(e),i[MOVE_USER_ROOM].next(s)}}))}function handleSendMessage(e,t,r,i){var s,o,n,a,d,u,l,c,h;let m=Object.assign({},e);if(m.message){if(m.message="string"==typeof m.message?JSON.parse(m.message):m.message,info("new-message","","",[" method => ",m.message.method]),"send-talk"===m.message.method){const i=m.user===(null===(s=t.getLocalUser())||void 0===s?void 0:s.userId),p=(null===(n=null===(o=m.message)||void 0===o?void 0:o.params)||void 0===n?void 0:n.status)||"",f=null===(u=null===(d=null===(a=m.message)||void 0===a?void 0:a.params)||void 0===d?void 0:d.stream)||void 0===u?void 0:u.avatar,v=e.seq,g=new BMMessageInfo({userId:m.user,message:p,isLocal:i,avatar:f,to:m.to,seq:v,nickName:null===(h=null===(c=null===(l=m.message)||void 0===l?void 0:l.params)||void 0===c?void 0:c.stream)||void 0===h?void 0:h.nickname,sendTime:(new Date).getTime()});r.addMessage(g,!1)}i[H$1.SEND_MESSAGE].next(m)}}function handleCustomMessage(e,t,r){var i,s,o,n,a,d,u,l,c,h,m,p,f;let v=Object.assign({},e);if(v.message)if(v.message="string"==typeof v.message?JSON.parse(v.message):v.message,info("custom-message","","",[" method => ",v.message.method]),"video-force-change"==v.message.method){const e="enabled"==v.message.params.status;info(`远端控制本地摄像头: ${e}`),t.messageWatcher.next({type:MessageType.VIDEO_FORCE_CHANGE,status:e,fromUserId:v.user})}else if("audio-force-change"==v.message.method){let e;e="checkUserAudio"==v.message.params.status?v.message.params.status:"enabled"==v.message.params.status,info(`远端控制本地麦克风: ${e}`),t.messageWatcher.next({type:MessageType.AUDIO_FORCE_CHANGE,status:e,fromUserId:v.user,isNotCancelRootReport:null===(i=v.message.params)||void 0===i?void 0:i.isNotCancelRootReport})}else if("raise-hands"===v.message.method)t.raiseHandleRespWatcher.next(v.message.params);else if("give-like"===v.message.method)null===(s=t.roomVM)||void 0===s||s.giveLikeList.push({userId:v.user,nickName:null===(a=null===(n=null===(o=v.message)||void 0===o?void 0:o.params)||void 0===n?void 0:n.stream)||void 0===a?void 0:a.nickname,time:(new Date).getTime(),type:null===(l=null===(u=null===(d=v.message)||void 0===d?void 0:d.params)||void 0===u?void 0:u.stream)||void 0===l?void 0:l.type}),null===(c=t.roomVM)||void 0===c||c.giveLikeListWatcher.next(null===(h=t.roomVM)||void 0===h?void 0:h.giveLikeList);else if("resp-to-check-devices"===v.message.method)(null===(m=v.message)||void 0===m?void 0:m.params)&&(v.message.params.fromUserId=v.user),r[H$1.CUSTOM_MESSAGE].next(v);else if("usercount"===v.message.method){if(v.message.params){let e=null===(f=null===(p=v.message)||void 0===p?void 0:p.params)||void 0===f?void 0:f.total;e?(e=Number(e),e<0&&(warn("服务返回的usercount为负数,"+e),e=0)):(warn("服务未返回usercount,"+e),e=0),t.roomInfo.totalUserWatcher.next(e)}}else if("waitusercount"===v.message.method){if(v.message.params){const e=v.message.params.total;t.roomInfo.totalWaitRoomUserWatcher.next(e)}}else r[H$1.CUSTOM_MESSAGE].next(v)}let reconnectFailed=0,shareReconnectFailed=0;const NETWORK_ERROR_QUEUE=new Set;function handleBRTCRoomError(e,t,r,i,s){return __awaiter(this,void 0,void 0,(function*(){error$1("brtc error","brtc error","",[(new Date).toLocaleTimeString(),JSON.stringify(e),e.getCode()]);if(4002===e.getCode()){t.BRTCConnectFailed=!0,t.networkState.brtc=!1,warn("brtc 信令通道错误,需要重新走入会","brtc error",""),t.streamWSReconnectWatcher.next(!1);try{yield r.brtcClient.leave("room_close")}catch(e){error$1("brtc 离会失败")}setTimeout((()=>__awaiter(this,void 0,void 0,(function*(){t.handleResetOtherStreamStatus(),yield reconnectBrtcWS(r,t,s,e).catch((t=>{info("brtc断网重连失败, 处理一下退会逻辑","","",[JSON.stringify(t)]),s[dt$1.ERROR].next(e)}))}))),1e3)}else s[dt$1.ERROR].next(e)}))}function reconnectBrtcWS(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((s,o)=>{setTimeout((()=>{info("brtc重连"),e.brtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>__awaiter(this,void 0,void 0,(function*(){info("brtc断网重连成功, 重新处理拉流和推流"),t.networkState.brtc=!0,setTimeout((()=>{t.brtcNetEnableWatcher.next(!0)}),2e3),handleReconnectedStream(t),t.BRTCConnectFailed=!1,reconnectFailed=0,yield t.handleRePushSelf(),t.streamWSReconnectWatcher.next(!0),s(!0)})))).catch((s=>{const n=s.getCode();info("断网重连入会失败","","",[s,n]),reconnectFailed<=10?(reconnectFailed+=1,e.brtcClient.isJoinning=!1,setTimeout((()=>{reconnectBrtcWS(e,t,r,i)}),2e3)):(error$1("brtc断网重连失败,处理一下退会"),reconnectFailed=0,r[dt$1.ERROR].next(i),o(!1))}))}),7e3)}))}))}function reconnectBRTCShareWS(e){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{setTimeout((()=>{info("共享屏幕重连"),e.shareBrtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>{shareReconnectFailed=0,t(!0)})).catch((t=>{const r=t.getCode();if(info("共享屏幕断网重连入会失败","","",[t,r]),!(shareReconnectFailed<=3))throw error$1("共享屏幕用户重连失败,处理一下取消共享屏幕"),shareReconnectFailed=0,new Error("共享屏幕重连失败");shareReconnectFailed+=1,reconnectBRTCShareWS(e)}))}),7e3)}))}))}function handleBloudError(e,t,r,i,s){return __awaiter(this,void 0,void 0,(function*(){error$1("network-error","network-error","local-client",["本地链接出现问题","netconnectiong => ",e.netConnecting]),e.netConnecting?yield handleBloudRoomReconnected(i,e,s):s[H$1.TIMEOUT].next(i)}))}function handleCustomStats(e,t,r){let i=null==e?void 0:e.updateKeys;info("update-custom-stats"," "," ",["updateKeys => ",JSON.stringify(i)]),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich"))||(null==i?void 0:i.includes("fileUpdateLook"))||(null==i?void 0:i.includes("fileUpdateDown"))||(null==i?void 0:i.includes("fileUpdateEdit"))||(null==i?void 0:i.includes("fileUpdateModel"))||(null==i?void 0:i.includes("screenShareModel"))||(null==i?void 0:i.includes("onlyOnePersonShare"))||(null==i?void 0:i.includes("chatEnable"))||(null==i?void 0:i.includes("giveLikeEnable"))||(null==i?void 0:i.includes("cloudRecord"))||(null==i?void 0:i.includes("joinAudioEnable"))||(null==i?void 0:i.includes("joinVideoEnable"))||(null==i?void 0:i.includes("userListEnable"))||(null==i?void 0:i.includes("audioEnable"))||(null==i?void 0:i.includes("videoEnable"))||(null==i?void 0:i.includes("modifyNameEnable"))||(null==i?void 0:i.includes("backgroundAIEnable"))||(null==i?void 0:i.includes("recordEnable"))||(null==i?void 0:i.includes("joinMicrophoneDisable"))||(null==i?void 0:i.includes("joinCameraDisable"))||(null==i?void 0:i.includes("raiseHandEnable"))||(null==i?void 0:i.includes("forceOpenUserMic"))||(null==i?void 0:i.includes("forceOpenUserCamera"))||(null==i?void 0:i.includes("joinCueVoice")))&&t.roomInfo.updateOperationPermission(e.customStats),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich")))&&t.roomInfo.chatNoticeWatcher.next(e),r[H$1.UPDATE_CUSTOM_STATS].next(e)}var dist={},eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,i,o,n){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new s(i,o||e,n),d=r?r+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],a]:e._events[d].push(a):(e._events[d]=a,e._eventsCount++),e}function n(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,s=[];if(0===this._eventsCount)return s;for(i in e=this._events)t.call(e,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,o=i.length,n=new Array(o);s<o;s++)n[s]=i[s].fn;return n},a.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,s,o,n){var a=r?r+e:e;if(!this._events[a])return!1;var d,u,l=this._events[a],c=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),c){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,s),!0;case 5:return l.fn.call(l.context,t,i,s,o),!0;case 6:return l.fn.call(l.context,t,i,s,o,n),!0}for(u=1,d=new Array(c-1);u<c;u++)d[u-1]=arguments[u];l.fn.apply(l.context,d)}else{var h,m=l.length;for(u=0;u<m;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),c){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,i);break;case 4:l[u].fn.call(l[u].context,t,i,s);break;default:if(!d)for(h=1,d=new Array(c-1);h<c;h++)d[h-1]=arguments[h];l[u].fn.apply(l[u].context,d)}}return!0},a.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,i,s){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return n(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||s&&!a.once||i&&a.context!==i||n(this,o);else{for(var d=0,u=[],l=a.length;d<l;d++)(a[d].fn!==t||s&&!a[d].once||i&&a[d].context!==i)&&u.push(a[d]);u.length?this._events[o]=1===u.length?u[0]:u:n(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&n(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}(eventemitter3);var pTimeout$1={exports:{}},pFinally$1=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))));const pFinally=pFinally$1;class TimeoutError extends Error{constructor(e){super(e),this.name="TimeoutError"}}const pTimeout=(e,t,r)=>new Promise(((i,s)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);const o=setTimeout((()=>{if("function"==typeof r){try{i(r())}catch(e){s(e)}return}const o=r instanceof Error?r:new TimeoutError("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),s(o)}),t);pFinally(e.then(i,s),(()=>{clearTimeout(o)}))}));pTimeout$1.exports=pTimeout,pTimeout$1.exports.default=pTimeout,pTimeout$1.exports.TimeoutError=TimeoutError;var priorityQueue={},lowerBound$1={};function lowerBound(e,t,r){let i=0,s=e.length;for(;s>0;){const o=s/2|0;let n=i+o;r(e[n],t)<=0?(i=++n,s-=o+1):s=o}return i}Object.defineProperty(lowerBound$1,"__esModule",{value:!0}),lowerBound$1.default=lowerBound,Object.defineProperty(priorityQueue,"__esModule",{value:!0});const lower_bound_1=lowerBound$1;class PriorityQueue{constructor(){Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]})}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const i=lower_bound_1.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}priorityQueue.default=PriorityQueue,Object.defineProperty(dist,"__esModule",{value:!0});const EventEmitter=eventemitter3.exports,p_timeout_1=pTimeout$1.exports,priority_queue_1=priorityQueue,empty=()=>{},timeoutError=new p_timeout_1.TimeoutError;class PQueue extends EventEmitter{constructor(e){var t,r,i,s;if(super(),Object.defineProperty(this,"_carryoverConcurrencyCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isIntervalIgnored",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalCap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalEnd",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queueClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_concurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isPaused",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_resolveEmpty",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_resolveIdle",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_throwOnTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:priority_queue_1.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(i=e.interval)||void 0===i?void 0:i.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother()}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=empty,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=empty)}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother)return this.emit("active"),this._queue.dequeue()(),e&&this._initializeIntervalIfNeeded(),!0}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={},r=null){return new Promise(((i,s)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const o=void 0===this._timeout&&void 0===t.timeout?e():p_timeout_1.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&s(timeoutError),r&&r("resolve-timeout")}));r&&r("resolving"),i(await o),this._isPaused?r&&r("resolve-paused"):r&&r("resolve")}catch(e){this._isPaused?r&&r("resolve-paused"):r&&r("resolve"),s(e)}this._next()}),t),this._tryToStartAnother()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}var _default=dist.default=PQueue;class Pqueue{constructor(e,t=!0){this.queue=new _default({concurrency:e,autoStart:t,carryoverConcurrencyCount:!0,timeout:3e3,completeAction:e=>{console.log("task complete",e)}}),this.queueArray=[],this.isTaskPending=t}addQueue(e,t,r=0,i=""){this.queue.isPaused&&this.queue.start();let s={};s.taskID=t,s.status="pending",this.queue.add(e,{priority:r,timeout:3e3},(e=>{if(s.status=e,"resolve"===s.status||"resolve-paused"===s.status||"resolve-timeout"===s.status){const e=this.queueArray.findIndex((e=>s.taskID===e.taskID));-1!==e&&this.queueArray.splice(e,1)}})),this.queueArray.push(s)}clearQueue(){this.queue.clear(),this.queueArray=[],this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{console.log("clearQueue全部完事")}))}startQueue(){this.queue.start()}pauseQueue(){return this.queue.pause(),console.log(`size:${this.size()}`),this.isTaskPending=!1,this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{})),this.queueArray}size(){return this.queue.size}pending(){return this.queue.pending}checkTaskStatus(){return this.isTaskPending}setTaskStatus(e){this.isTaskPending=e}onIdle(){return this.queue.onIdle()}onEmpty(){return this.queue.onEmpty()}}const streamPullQueue=new Pqueue(4),eventQueue=new Pqueue(10);var MessageType,PlayerState;function attachEvents(e,t,r,i,s){info("attachEvents init");let o={};e.on("toggle-screen-share",(()=>{error$1("share stream video track ended, now unpublish share stream"),r.localShareError.next(Ar()),r.toggleShareScreen(!1,void 0).then((()=>{}))})),e.on("client-banned",(()=>__awaiter(this,void 0,void 0,(function*(){yield s.boomCore.leaveShare()})))),e.on("share-brtc-error",(t=>__awaiter(this,void 0,void 0,(function*(){if(4002===t.getCode())try{info("brtc share client disconnected, reconnecting"),yield e.shareBrtcClient.leave("room_close"),reconnectBRTCShareWS(e).then((()=>__awaiter(this,void 0,void 0,(function*(){if(info("brtc share client reconnected, retry repub share stream"),yield sleep(1e3),e.shareScreenStream){const t=e.shareScreenStream.getAudioOn(),r=e.shareScreenStream.getVideoOn();e.shareBrtcClient.publish(e.shareScreenStream),e.createAndPubBloudShareStream(t,r)}})))).catch((e=>{throw new Error("共享屏幕重新入会失败")}))}catch(e){r.toggleShareScreen(!1,void 0).then((()=>{})).catch((e=>{error$1("共享发生错误退会失败","","",[JSON.stringify(e)])}))}}))));let n=[];return n=n.concat(Object.values(H$1)),n=n.concat(Object.values(dt$1)),n=n.concat(Object.values(Nt$1)),n.forEach((e=>{o[e]=new BehaviorSubject(null)})),n.forEach((n=>{switch(n){case dt$1.STREAM_PUBLISHED:e.on(dt$1.STREAM_PUBLISHED,(e=>{eventQueue.addQueue(handleStreamPublished.bind(null,e,r,s,o),dt$1.STREAM_PUBLISHED)}));break;case dt$1.BRTC_SYNC_ROOM_COMPLETED:e.on(dt$1.BRTC_SYNC_ROOM_COMPLETED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(s.handleResetOtherStreamStatus.bind(s),dt$1.BRTC_SYNC_ROOM_COMPLETED)}))));break;case Nt$1.BRTC_SHARE_SYNC_ROOM_COMPLETED:e.on(Nt$1.BRTC_SHARE_SYNC_ROOM_COMPLETED,(()=>{info("brtc share client sync completed, retry publish share stream"),eventQueue.addQueue(handleShareStreamFailed.bind(null,s,r),Nt$1.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));break;case dt$1.BRTC_ROOM_ROCONNECTING:e.on(dt$1.BRTC_ROOM_ROCONNECTING,(e=>{eventQueue.addQueue(handleBrtcRoomReconnecting.bind(null,e,s,o),dt$1.BRTC_ROOM_ROCONNECTING)}));break;case dt$1.BRTC_ROOM_RECONNECTED:e.on(dt$1.BRTC_ROOM_RECONNECTED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBrtcRoomReconnected.bind(null,e,s,o),dt$1.BRTC_ROOM_RECONNECTED)}))));break;case dt$1.CLIENT_BANNED:e.on(dt$1.CLIENT_BANNED,(e=>{info("brtc client banned"),handleUserRejoined(o,e)}));break;case dt$1.ERROR:e.on(dt$1.ERROR,(t=>__awaiter(this,void 0,void 0,(function*(){s.netConnecting?eventQueue.addQueue(handleBRTCRoomError.bind(null,t,s,e,r,o),dt$1.ERROR):NETWORK_ERROR_QUEUE.add(handleBRTCRoomError.bind(null,t,s,e,r,o))}))));break;case H$1.SYNC_FAILED:e.on(H$1.SYNC_FAILED,(e=>{error$1("bloud sync failed, leave room"),o[H$1.TIMEOUT].next(e)}));break;case H$1.ROOM_CONNECTED:e.on(H$1.ROOM_CONNECTED,(e=>__awaiter(this,void 0,void 0,(function*(){return handleRoomConnected(e,s,t,o)}))));break;case Nt$1.JOIN_READY:e.on(Nt$1.JOIN_READY,(()=>handleInitJoinRoomUsers(s)));break;case H$1.PARTICIPANT_JOINED:e.on(H$1.PARTICIPANT_JOINED,(n=>__awaiter(this,void 0,void 0,(function*(){s.isInWaitRoom||eventQueue.addQueue(handleParticipantJoin.bind(null,n,t,r,e,i,o),H$1.PARTICIPANT_JOINED)}))));break;case H$1.PARTICIPANT_LEFT:e.on(H$1.PARTICIPANT_LEFT,(n=>{s.isInWaitRoom||eventQueue.addQueue(handleParticipantLeft.bind(null,n,t,s,o,r,e,i),H$1.PARTICIPANT_LEFT)}));break;case H$1.LEAVE_USERS:e.on(H$1.LEAVE_USERS,(n=>eventQueue.addQueue(handleLeaveUsers.bind(null,n,t,s,o,r,e,i),H$1.LEAVE_USERS)));break;case H$1.CHANGE_MASTER:e.on(H$1.CHANGE_MASTER,(e=>{eventQueue.addQueue(handleChangeMaster.bind(null,e,t,s,o,r),H$1.CHANGE_MASTER)}));break;case H$1.SEND_MESSAGE:e.on(H$1.SEND_MESSAGE,(e=>{eventQueue.addQueue(handleSendMessage.bind(null,e,t,i,o),H$1.SEND_MESSAGE)}));break;case H$1.CUSTOM_MESSAGE:e.on(H$1.CUSTOM_MESSAGE,(e=>{eventQueue.addQueue(handleCustomMessage.bind(null,e,s,o),H$1.CUSTOM_MESSAGE)}));break;case H$1.EVICTED:e.on(H$1.EVICTED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleEvict.bind(null,e,t,r,s,o),H$1.EVICTED)}))));break;case H$1.UPDATE_USER:e.on(H$1.UPDATE_USER,(e=>{eventQueue.addQueue(handleUpdateUser.bind(null,e,t,s,r,o),H$1.UPDATE_USER)}));break;case H$1.UPDATE_STATS:e.on(H$1.UPDATE_STATS,(e=>{eventQueue.addQueue(handleRoomUpdated.bind(null,e,s),H$1.UPDATE_STATS)}));break;case H$1.UPDATE_CUSTOM_STATS:e.on(H$1.UPDATE_CUSTOM_STATS,(e=>{eventQueue.addQueue(handleCustomStats.bind(null,e,s,o),H$1.UPDATE_CUSTOM_STATS)}));break;case H$1.TIMEOUT:e.on(H$1.TIMEOUT,(t=>{eventQueue.addQueue(handleBloudError.bind(null,s,e,r,t,o),H$1.TIMEOUT)}));break;case H$1.USER_REJOINED:e.on(H$1.USER_REJOINED,(e=>{info("bloud user rejoined"),handleUserRejoined(o,e)}));break;case H$1.RECONNECTING:e.on(H$1.RECONNECTING,(e=>{eventQueue.addQueue(handleBloudRoomReconnecting.bind(null,e,s,o),H$1.RECONNECTING)}));break;case H$1.RECONNECTED:e.on(H$1.RECONNECTED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomReconnected.bind(null,e,s,o),H$1.RECONNECTED)}))));break;case H$1.ROOM_SYNCED:e.on(H$1.ROOM_SYNCED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomSync.bind(null,e,t,s,r,o),H$1.ROOM_SYNCED)}))));break;case H$1.STREAM_PUBLISHED:e.on(H$1.STREAM_PUBLISHED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPublished.bind(null,e,r,o),H$1.STREAM_PUBLISHED)}))));break;case H$1.STREAM_REMOVED:e.on(H$1.STREAM_REMOVED,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUnPublished.bind(null,e,r,o),H$1.STREAM_REMOVED)}))));break;case H$1.UPDATE_STREAM:e.on(H$1.UPDATE_STREAM,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUpdated.bind(null,e,r,o),H$1.UPDATE_STREAM)}))));case H$1.STREAM_UPDATE:e.on(H$1.STREAM_UPDATE,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPubAUpdate.bind(null,e,r),H$1.STREAM_UPDATE)}))));break;case H$1.MOVE_USER_ROOM:e.on(H$1.MOVE_USER_ROOM,(e=>__awaiter(this,void 0,void 0,(function*(){eventQueue.addQueue(handleMoveUserRoom.bind(null,s,t,e,o),H$1.MOVE_USER_ROOM)}))));break;default:e.on(n,(e=>o[n].next(e)))}})),o}!function(e){e.INIT="init",e.VIDEO_FORCE_CHANGE="video-force-change",e.AUDIO_FORCE_CHANGE="audio-force-change"}(MessageType||(MessageType={}));class BMRoomVM{constructor(e,t,r){this.room=null,this.tipQueueObj={},this.roomInfo=r,this.userVM=t,this.boomCore=e,this.giveLikeList=[],this.giveLikeListWatcher=new Subject}initWithRoom(e){this.room=e}evictUser(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!e)return Promise.reject(Zn("未传递用户id"));if(!this.userVM.checkLocalHasMaster())return Promise.reject(Zn("只有主持人权限才能踢出用户"));if(this.userVM.checkIsMaster(e))return Promise.reject(Zn("主持人不能被踢出"));try{yield this.boomCore.evictUser(e,t)}catch(e){return Promise.reject(Zn(`踢出用户失败${JSON.stringify(e)}`))}}))}updateUser(e,t){return __awaiter(this,void 0,void 0,(function*(){return e?t?void(yield this.boomCore.updateUser(e,{customInfo:t}).catch((e=>Promise.reject(tr(`boomCore updateUser出错 ${JSON.stringify(e)}`))))):Promise.reject(tr("info为空,请写入要更新的信息")):Promise.reject(tr("未传递目标用户id"))}))}changeMaster(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(!e)return Promise.reject(qn("未传递主持人id"));if(!this.userVM.checkLocalHasMaster()&&!(null===(r=this.userVM.getUser(e))||void 0===r?void 0:r.isCreate))return console.error("该用户没有管理员权限, 无法改变主持人",LOGGER_TAG_CLIENT,e),Promise.reject(qn("您没有管理员权限, 无法改变主持人"));try{yield this.boomCore.changeMaster(e,t)}catch(e){return Promise.reject(qn(`boomCore changeMaster error ${e}`))}}))}updateManager(e,t,r=!0){return __awaiter(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()?this.userVM.updateManager(e,t,r):(console.error("该用户没有管理员权限, 无法改变联席主持人",LOGGER_TAG_CLIENT,e),Promise.reject(Qn("该用户没有管理员权限, 无法改变主持人"))):Promise.reject(Qn("未传递联席主持人id"))}))}changeNickName(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={nickname:t};yield this.updateUser(e,r)}))}sendMessageWithMaster(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!this.userVM.checkLocalHasMaster())return Promise.reject($n("您不是主持人,没有该权限"));if(t){if(!this.userVM.getUser(t))return Promise.reject($n(`uid: ${t} 未找到用户`))}try{yield this.boomCore.customMessage(JSON.stringify(e),t)}catch(e){return Promise.reject(e)}}))}setRemoteAudioEnable(e,t,r){return __awaiter(this,void 0,void 0,(function*(){let i=e?"enabled":"disabled";"enabled"==i&&r&&(i="checkUserAudio");let s={domain:"room-control",method:"audio-force-change",params:{status:i,isNotCancelRootReport:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(s,t).catch((e=>Promise.reject($n(`boomCore.sendMessage发生错误 ${e}`))))}))}setRemoteVideoEnable(e,t){return __awaiter(this,void 0,void 0,(function*(){let r={domain:"room-control",method:"video-force-change",params:{status:e?"enabled":"disabled",fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(Gn(`boomCore.sendMessage发生错误 ${e}`))))}))}closeRemoteShare(e){return __awaiter(this,void 0,void 0,(function*(){let t={domain:"room-control",method:"close-remote-share",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject($n(`boomCore.sendMessage发生错误 ${e}`))))}))}tipUser(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){let s={domain:"room-control",method:"tip-user",params:{fromUserId:this.boomCore.getLocalParticipant().getID(),message:t,richMsg:r}};i?this.tipQueueObj[e]=setTimeout((()=>{this.sendMessageWithMaster(s,e)}),60*(i.minutes||0)*1e3+1e3*(i.seconds||0)):this.sendMessageWithMaster(s,e).catch((e=>Promise.reject($n(`boomCore.sendMessage发生错误 ${JSON.stringify(e)}`))))}))}raiseHands(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){const i=null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().getID();let s={};"raiseHand"===e?(s.raiseHand=t,s.raiseHandTime=Math.floor((new Date).getTime()/1e3)):s["audio"===e?"raiseHandsAudio":"raiseHandsVideo"]=t,yield this.updateUser(i,s)}))}handleRaiseHands(e,t,r){var i,s,o;return __awaiter(this,void 0,void 0,(function*(){let n={domain:"user-control",method:"raise-hands",params:{raiseHandsType:e,raiseHands:t}};try{if(r)yield this.boomCore.customMessage(JSON.stringify(n),r);else{const t=null===(i=this.room)||void 0===i?void 0:i.roomInfo.raiseHandsWatcher.getValue(),r=null===(s=this.room)||void 0===s?void 0:s.roomInfo.raiseVideoHandsWatcher.getValue(),a=null===(o=this.room)||void 0===o?void 0:o.roomInfo.raiseSimpleHandsWatcher.getValue();0===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(n),e.userId)})),null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(n),e.userId)}))),1===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(n),e.userId)}))),2===e&&(null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(n),e.userId)}))),3===e&&(null==a||a.forEach((e=>{this.boomCore.customMessage(JSON.stringify(n),e.userId)})))}}catch(e){return Promise.reject(new BoomError(LOCAL_ERROR,"boomCore.sendMessage发生错误"))}}))}updateCustomStats(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){yield this.boomCore.updateCustomStats(e,t).catch((t=>Promise.reject(Vn(`${JSON.stringify(e)} - ${JSON.stringify(t)}`))))}))}sendChatNotice(e,t,r){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatNotice:e,chatNoticeRich:t,showTipNotice:r}).catch((e=>e))}))}giveLikeEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({giveLikeEnable:e}).catch((e=>e))}))}changeAutoMute(e){return __awaiter(this,void 0,void 0,(function*(){return this.updateCustomStats({autoMute:e})}))}allUserReceiveJoinLeaveMessages(e){return __awaiter(this,void 0,void 0,(function*(){return this.updateCustomStats({allUserReceiveJoinLeaveMessages:e})}))}userJoinMasterVoice(e){return __awaiter(this,void 0,void 0,(function*(){return this.updateCustomStats({userJoinMasterVoice:e})}))}userGiveLike(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){let i=(new Date).getTime(),s={domain:"room-control",method:"give-like",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:i,nickname:this.userVM.localUser.nickName,type:e||1}}},o=this.userVM.getLocalUser();try{yield this.boomCore.customMessage(JSON.stringify(s),void 0),this.giveLikeList.push({userId:null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant().userId,nickName:null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().nickName,time:(new Date).getTime(),type:e}),this.giveLikeListWatcher.next(this.giveLikeList)}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==o?void 0:o.userId),new BoomError(CLIENT_BANNED,"用户点赞==>sendMessage出错")}}))}chatEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatEnable:e}).catch((e=>e))}))}joinAudioEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinAudioEnable:e}).catch((e=>e))}))}joinVideoEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinVideoEnable:e}).catch((e=>e))}))}userListEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({userListEnable:e}).catch((e=>e))}))}audioEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({audioEnable:e}).catch((e=>e))}))}videoEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({videoEnable:e}).catch((e=>e))}))}modifyNameEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({modifyNameEnable:e}).catch((e=>e))}))}backgroundAIEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({backgroundAIEnable:e}).catch((e=>e))}))}forceOpenUserCamera(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserCamera:e}).catch((e=>e))}))}forceOpenUserMic(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserMic:e}).catch((e=>e))}))}joinCueVoice(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCueVoice:e}).catch((e=>e))}))}recordEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({recordEnable:e}).catch((e=>e))}))}raiseHandEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({raiseHandEnable:e}).catch((e=>e))}))}joinMicrophoneDisable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinMicrophoneDisable:e}).catch((e=>e))}))}joinCameraDisable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCameraDisable:e}).catch((e=>e))}))}changeFileUpdateModelPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateModel:e}).catch((e=>e))}))}changeFileUpdateLookPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateLook:e}).catch((e=>e))}))}changeFileUpdateDownPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateDown:e}).catch((e=>e))}))}changeFileUpdateEditPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateEdit:e}).catch((e=>e))}))}changeScreenShareModelPermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({screenShareModel:e}).catch((e=>e))}))}changeOnlyOnePersonSharePermission(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({onlyOnePersonShare:e}).catch((e=>e))}))}setForceOnUser(e){return __awaiter(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOn:{user:e}}).catch((e=>e))}))}updateHostLayout(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){if(this.userVM.checkLocalHasMaster())return this.updateCustomStats({from:{fromTag:"masterId"},hostLayout:e},t);info("您不是主持人,没有该上报权限",LOGGER_TAG_CLIENT)}))}checkDevices(e){return __awaiter(this,void 0,void 0,(function*(){const t={domain:"user-control",method:"check-devices",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(cr(`检测对方设备send-message发生错误: ${e}`))))}))}resp2CheckDevices(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-check-devices",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};if(!t)return Promise.reject(cr(`响应设备检测: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(cr(`响应响应设备检测send-message发生错误 ${e}`))}}))}changeRemoteVideoProfile(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-video-profile",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(sr$1(`调节对方的视频分辨率send-message发生错误: ${e}`))))}))}resp2ChangeRemoteVideoProfile(e,t,r){return __awaiter(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"resp-to-change-video-profile",params:{status:e,profile:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(sr$1(`响应调节视频分辨率: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(i),t)}catch(e){return Promise.reject(sr$1(`响应调节视频分辨率send-message发生错误 ${e}`))}}))}changeRemoteAudioProfile(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-audio-profile",params:{microphoneDevice:e.microphoneDevice,speakerDevice:e.speakerDevice,echoCancellation:e.echoCancellation,noiseSuppression:e.noiseSuppression,autoGainControl:e.autoGainControl,speakerVolume:e.speakerVolume,microVolume:e.microVolume,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(ir(`调节音频send-message发生错误 ${JSON.stringify(e)}`))))}))}resp2ChangeRemoteAudioProfile(e,t){return __awaiter(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-change-audio-profile",params:{status:e,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(ir(`响应调节音频: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(ir(`响应调节音频send-message发生错误 ${e}`))}}))}}class BMChatVM{constructor(e,t,r){this.messageList=[],this.hasDangerMessageWatcher=new Subject,this.notificationMessageList=debounce((()=>{this.messageListWatcher.next(this.messageList)}),500),this.boomCore=e,this.userVM=t,this.bmRoom=r,this.messageListWatcher=new BehaviorSubject(this.messageList)}sendMessage(e,t,r){return __awaiter(this,void 0,void 0,(function*(){let i=e.replace(/(^\s*)|(\s*$)/g,""),s=(new Date).getTime(),o={domain:"room-control",method:"send-talk",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:s,nickname:this.userVM.localUser.nickName},status:i}},n=this.userVM.getLocalUser();try{let e,a=!1,d=r;d||(yield this.boomCore.sendMessage(JSON.stringify(o),t).then((t=>{e=t.seq})).catch((e=>{warn("sendmessage 出错","",null==n?void 0:n.userId,[e]),e&&39===e.code&&(a=!0,this.hasDangerMessageWatcher.next(!0))})));const u=new BMMessageInfo({userId:null==n?void 0:n.userId,message:i,isLocal:null==n?void 0:n.isLocal,avatar:null==n?void 0:n.avatar,nickName:null==n?void 0:n.nickName,sendTime:s,to:t,isDanger:a,seq:e,failed:d});return this.addMessage(u,!1),d?Promise.reject(u):Promise.resolve()}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==n?void 0:n.userId),new BoomError(CLIENT_BANNED,"发送聊天消息==>sendMessage出错")}}))}addMessage(e,t){if(!t||this.bmRoom.participantNotice){if(0==this.messageList.length||e.timeStamp-this.messageList[this.messageList.length-1].timeStamp>=notGetTalkInterval){const e=new BMMessageInfo({isMeetingNotice:!0,message:""});this.messageList.push(e)}this.messageList.push(e),this.notificationMessageList()}}updateMessageListWatcher(e){this.messageList=e,this.messageListWatcher.next(this.messageList)}getHistoryMessage(){return __awaiter(this,void 0,void 0,(function*(){const e=yield this.boomCore.getMessages(0,this.boomCore.getMsgSeq());let t=[];return e.items.forEach((e=>{if(e.private||e.to)return!1;if(0==e.msg.length||-1==e.msg.indexOf("{"))return!1;const r=JSON.parse(e.msg);if("send-talk"!=r.method)return!1;const i=e.seq;let s=r.params,o=s.stream.user?s.stream.user:e.userId;s.stream.nickname,s.status,(new Date).getTime();const n=new BMMessageInfo({userId:o,message:s.status,nickName:s.stream.nickname,isLocal:o==this.userVM.localUser.userId,avatar:s.stream.avatar,sendTime:s.stream.sendTime,seq:i});t.push(n)})),Promise.resolve(t)}))}}class BMSpeaker{constructor(e,t){this.user=e,this.stream=t}getID(){return this.stream.getStreamId()}getUser(){return this.user}}function getMasterSort(e,t){return 16|~~e<<1|~~t}function getLocalSort(e,t){return 12|~~e<<1|~~t}function getManagerSort(e,t){return 8|~~e<<1|~~t}function getGuestSort(e,t){return 4|~~e<<1|~~t}function getTimestamp(){return Date.now()}function benchmark(){const e=getTimestamp();return function(){return getTimestamp()-e}}!function(e){e[e.NO_CONTAINER=0]="NO_CONTAINER",e[e.NO_PLAYING=1]="NO_PLAYING",e[e.PLAYING=2]="PLAYING"}(PlayerState||(PlayerState={}));const namespace$1=`.streammodel${Math.random()}`;class BMStreamModel{constructor(e,t){this.streamType=STREAM_TYPE.OTHER,this.pullFailedNum=0,this._video_enable=!1,this._audio_enable=!1,this.videoEnableWatcher=new BehaviorSubject(this._video_enable),this.audioEnableWatcher=new BehaviorSubject(this._audio_enable),this.streamUpdateWatcher=new Subject,this.isSubScribedWatcher=new Subject,this.playStateChangeWatcher=new Subject,this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.audioLevelWatcher=new Subject,this.isCurrentDisplay=!1,this.isDisplay=!1,this.isDisplayObserve=new Subject,this.isInBig=!1,this.isInBigObserve=new Subject,this._hasPulled=!1,this.playerId="",this.shouldPull=!1,this.smallPlayFailed=0,this._pulledStreamType="small",this.pulledStreamGoal="small",this.bigPlayerId="",this.isPlayingBig=!1,this.muted=!1,this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount=0,this.sortNum=-1,this.handleDisplayChange=e=>{var t;this.isDisplay!==e&&(this.isDisplay=e,null===(t=this.stream)||void 0===t||t.stop(),this.isDisplay||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.pulledStreamType="small"),this.sendMessage2Room())},this.onPlayerStateChange=e=>{var t,r;"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&(info("播放失败, 需要调用 resume 方法"),this.playStateChangeWatcher.next(this)),"PAUSED"!==e.state&&"pause"!==e.reason||(this.player&&(null===(t=this.player)||void 0===t||t.resume()),null===(r=this.stream)||void 0===r||r.resume())},this.handleStreamConnectError=()=>{info("流出现的connect-error userId","",this.userId,["streamId ==>",this.streamId,"nickname =>",this.nickname,"isLocal => ",this.isLocal]),this.isLocal?BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!0}):BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!1})},this.bindElement=e=>{this.playerId=e,(this.isLocal||this.stream&&this.stream.isSubscribed())&&this.sendMessage2Room()},this.bindBigElement=e=>{this.bigPlayerId=e,(this.isLocal||this.stream&&this.stream.isSubscribed())&&this.sendMessage2Room()},this.sendMessage2Room=debounce((()=>{BoomEmitter.emitter.emit(RECEIVE_SUBSCRIBE_MESSAGE,{stream:this})}),300),this.emitBindElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_ELEMENT,{stream:this})}),50),this.emitBindBigElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_BIG_ELEMENT,{stream:this})}),50),this.currentIsPlaying=e=>{const t=document.getElementById(e);if(!t)return PlayerState.NO_CONTAINER;let r,i,s=0;const o=Array.from(t.children);return r=o.length>0,i=o.length,o.forEach((e=>{0===e.children.length&&(s+=1,e.style.display="none",t.removeChild(e))})),r&&i>s?PlayerState.PLAYING:PlayerState.NO_PLAYING},this.play=()=>__awaiter(this,void 0,void 0,(function*(){var e;const t=this.stream;if(t)if(this.isDisplay&&this.videoEnable){const e=this.currentIsPlaying(this.playerId);if(e===PlayerState.NO_CONTAINER)warn("找不到播放器容器","stream play",this.userId,["流 id =>",this.streamId,"nickname =>",this.nickname,"playerId =>",this.playerId]),this.playerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"small"});else if(e===PlayerState.NO_PLAYING)try{info("远端流开始播放","",this.userId);const e=benchmark();yield t.play(this.playerId,{backgroundColor:"#202020",fit:"contain",audio:!1}),info("远端流播放结束",this.userId,this.streamId,[this.nickname]),info(`播放耗时: ${e()}`,"",this.userId),this.smallPlayFailed=0,this.checkSmallVideo()}catch(e){t.stop(),setTimeout((()=>{error$1("播放小流失败, 尝试重新播放","播放",this.userId,[this.streamId,this.stream,"error => ",JSON.stringify(e)]),this.play()}),2e3)}}else try{null===(e=this.stream)||void 0===e||e.stop()}catch(e){}})),this.playInBig=()=>__awaiter(this,void 0,void 0,(function*(){var e;const t=this.stream;if(t){const r=this.currentIsPlaying(this.bigPlayerId);if(this.isInBig&&this.videoEnable&&this.bigPlayerId){if(r===PlayerState.NO_CONTAINER)warn("找不到 bigPlayerId","大流播放",this.userId,["流 id =>",this.streamId]),this.bigPlayerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"big"});else if(r===PlayerState.NO_PLAYING){info("远端流大流开始播放","",this.userId);const e=benchmark();this.initBigPlayer(),this.player&&(yield this.player.play(t),this.isPlayingBig=!0,this.checkBigVideo()),info(`大流播放耗时: ${e()}`,"",this.userId),info("远端流大流播放结束",this.userId,this.streamId,[this.nickname])}}else null===(e=this.player)||void 0===e||e.destroy(),this.player=null,this.isPlayingBig=!1}})),this.collectAudioLevel=()=>{this.stream?(this.stream.off("audio-level"+namespace$1,this.handleAudioLevel),this.stream.on("audio-level"+namespace$1,this.handleAudioLevel)):warn("collection audio level but not have brtc stream")},this.handleAudioLevel=e=>{this.audioLevelWatcher.next(e)},this.checkSmallVideo=()=>__awaiter(this,void 0,void 0,(function*(){if(this.videoEnable&&this.stream&&!this.isShare){if(!!document.getElementById(this.playerId)){const e=`video_${this.stream.getStreamId()}`;if(!!document.getElementById(e))return void this.checkVideoDecodeFrame(e);error$1(`stream is display, but no video element, should replay now: ${this.smallPlayFailed}`),this.smallPlayFailed<3&&(this.smallPlayFailed+=1,yield sleep(1e3),this.stream.stop(),yield this.play())}}})),this.checkBigVideo=debounce((()=>{var e;if(this.videoEnable&&this.stream){const t=`video_${this.stream.getStreamId()}_big`;if(!this.isShare&&this.isDisplay&&this.playerId){const r=!!document.getElementById(t);if(this.isInBig){if(r)return void this.checkVideoDecodeFrame(t);error$1("stream is playing in big, but no video element, replay now"),null===(e=this.player)||void 0===e||e.destroy(),this.playInBig()}}this.isShare&&this.isInBig&&this.bigPlayerId&&this.checkVideoDecodeFrame(t)}}),2e3),this.checkStreamIsPlaying=debounce((()=>{if(this.isDisplay&&this.videoEnable){if(!this.stream)return;if(!document.getElementById(this.playerId))return;this.currentIsPlaying(this.playerId)===PlayerState.NO_PLAYING||(error$1(`${this.userId} - ${this.nickname}: current is ${this.isDisplay}, but there is no player, try play again`),this.play())}}),1e3),this.user=e,this.updateUser(e),this._stream=t,this.isDisplayObserve.subscribe((e=>{this.handleDisplayChange(e)})),this.isInBigObserve.subscribe((e=>{this.handleIsInBig(e)})),this.updateSortNum(!1)}get hasPulled(){return this._hasPulled}set hasPulled(e){this._hasPulled=e}get pulledStreamType(){return this._pulledStreamType}set pulledStreamType(e){this._pulledStreamType=e}get uuid(){return this.isShare?`${this.userId}_share`:this.userId}get isAudience(){return this.user.isAudience}get canShow(){return!this.isAudience||(this.audioEnable||this.videoEnable)}changeMute(e){this.muted!==e&&(this.muted=e,this.handleSpeakerChange())}handleSpeakerChange(){var e,t;this.isLocal||(this.muted?null===(e=this.stream)||void 0===e||e.setAudioVolume(0):null===(t=this.stream)||void 0===t||t.setAudioVolume(1))}get isToupingma(){return this.user.isToupingma}get isMixer(){return this.user.isMixer}get isSignal(){return this.user.isSignal}genReceiveSubMsg(){let e=null;return e=this.isDisplay?{audio:!0,video:!0,streamType:"small"}:{audio:!0,video:!1,streamType:"small"},e}handleIsInBig(e){this.isInBig!==e&&(this.isInBig=e,info("isInBig change","",this.userId,["streamId =>",this.streamId,"isInBig => ",e]),this.isInBig?this.pulledStreamGoal="big":this.pulledStreamGoal="small",this.sendMessage2Room(),this.isShare&&(this.isInBig||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0)))}setVideoEnable(e){this._video_enable!==e&&(this._video_enable=e,this.videoEnableWatcher.next(e))}setAudioEnable(e){this._audio_enable!==e&&(this._audio_enable=e,this.audioEnableWatcher.next(e))}updateStream(e,t=!0,r){if(this._stream&&this._stream.off(namespace$1),this._stream=e,e){const i=e.getVideoOn(),s=e.getAudioOn();info("更新用户的流","updateStream",null==e?void 0:e.getUserId(),["nickname =>",this.nickname,"audioOn",s,"videoOn",i,"streamId",e.getStreamId()]),s&&(this.isShare||r.addToDetector(new BMSpeaker(this.user,e)),this.collectAudioLevel()),e.on("player-state-changed"+namespace$1,this.onPlayerStateChange),e.on("connect-error"+namespace$1,this.handleStreamConnectError),e.on("stream-connection-error"+namespace$1,this.handleStreamConnectError),t&&this.sendMessage2Room()}else this.hasPulled=!1,this.pulledStreamType="small",this.streamType=STREAM_TYPE.OTHER}updateBloudStream(e,t,r=!1){var i,s,o,n,a,d;let u=!1,l=!1;if(e){if(this.bloudStream={audio:e.audio,video:e.video,isScreen:e.isScreen},e.customInfo&&(this.bloudStream.customInfo&&(null===(i=this.bloudStream.customInfo)||void 0===i?void 0:i.volume)===e.customInfo.volume||Number.isNaN(e.customInfo.volume)||this.setRemoteAudioLevel(e.customInfo.volume),this.bloudStream.customInfo=e.customInfo),this.stream&&(this.bloudStream.audio?this.isShare||(t.addToDetector(new BMSpeaker(this.user,this.stream)),this.collectAudioLevel()):t.removeFromDetector(this.stream.getStreamId())),this.bloudStream.video!==this._video_enable&&(u=!0),this.bloudStream.audio!=this._audio_enable&&(l=!0),this.setVideoEnable(this.bloudStream.video),this.setAudioEnable(this.bloudStream.audio),r){try{null===(s=this.stream)||void 0===s||s.destroy()}catch(e){}null===(o=this.player)||void 0===o||o.destroy(),this.stream&&(null===(n=t.room.audioPlayer)||void 0===n||n.removeStream(this.stream)),this.updateStream(void 0,!1,t),this._stream=void 0}l&&!this.audioEnable&&this.stream&&(null===(a=t.room.audioPlayer)||void 0===a||a.removeStream(this.stream)),(this.bloudStream.audio||this.bloudStream&&this.isDisplay)&&(!this.stream||r?BoomEmitter.emitter.emit(ADD_PULL_USER,{id:this.userId,isWeb:this.isWeb,isScreen:this.isShare}):(this.isLocal||this.hasPulled&&this.stream.isSubscribed()||this.sendMessage2Room(),u&&this.sendMessage2Room(),!this.isLocal&&l&&this.audioEnable&&this.stream.isSubscribed()&&BoomEmitter.getInstance().emit(ADD_AUDIO_PLAY,{stream:this})))}else this.bloudStream=void 0,this.setVideoEnable(!1),this.setAudioEnable(!1),null===(d=this.player)||void 0===d||d.destroy(),this.stream&&t.removeFromDetector(this.stream.getStreamId());this.updateSortNum(!0),this.streamUpdateWatcher.next(!0)}updateBloudCustomInfo(e){var t;this.bloudStream?(this.bloudStream.customInfo&&(null===(t=this.bloudStream.customInfo)||void 0===t?void 0:t.volume)===e.volume||Number.isNaN(e.volume)||this.setRemoteAudioLevel(e.volume),this.bloudStream.customInfo=e):error$1("updateBloudCustomInfo, but bloudStream is undefined","","",["userId =>",this.userId])}get streamId(){return this._stream?this._stream.getStreamId():this.userId}get bStreamId(){return this.isShare?`${this.userId}_screen`:this.userId}get userId(){return this.user.userId}get stream(){return this._stream}get isLocal(){return this.user.isLocal}get isShare(){var e,t,r;return this.stream?this.user.isWeb?null===(t=null===(e=this.stream)||void 0===e?void 0:e.getUserId().toString())||void 0===t?void 0:t.endsWith(STREAM_SUFFIX_SCREEN):!(!this.stream||!this.stream.getType||"assist"!==this.stream.getType()):!!(null===(r=this.bloudStream)||void 0===r?void 0:r.isScreen)}get isWeb(){return this.user.isWeb}get audioEnable(){return this._audio_enable}get videoEnable(){return this._video_enable}get brtcPlayerId(){return`player_${this.stream.getStreamId()}`}get selfPlayerId(){return`player_${this.stream.getStreamId()}_big_container`}get nickname(){var e;return this.user.isToupingma?`${this.user.nickName}(的投屏)`:(null===(e=this.streamId)||void 0===e?void 0:e.includes(STREAM_SUFFIX_SCREEN))?`${this.user.nickName}(的屏幕共享)`:this.user.nickName}get audioLevel(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.getAudioLevel())||0}getUser(){return this.user}setRemoteAudioLevel(e){if(this.isLocal)throw new Error("不能设置本地流的音量");BoomEmitter.emitter.emit(SET_VOLUME,{streamId:this.streamId,volume:e})}getStats(){var e;return null===(e=this._stream)||void 0===e?void 0:e.getStats()}initBigPlayer(){try{if(this.bigPlayerId){const e=document.querySelector(`#${this.bigPlayerId}`);if(!e)return void console.error("播放大流失败,找不到大流容器",this.userId,this.streamId,this.bigPlayerId);this.player&&this.player.destroy(),this.player=null,this.player=new x(e,{fit:"contain"}),this.player.on("player-state-changed",(e=>{var t;this.stream&&(info("big player state change","","",[JSON.stringify(e)]),"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&this.playStateChangeWatcher.next(this),"PAUSED"===e.state&&(null===(t=this.player)||void 0===t||t.resume()))}))}}catch(e){error$1("初始化大窗口的播放器失败",this.userId,this.streamId,e.message)}}stop(){var e;null===(e=this._stream)||void 0===e||e.stop()}destroy(){var e;null===(e=this._stream)||void 0===e||e.destroy()}isPlaying(){var e;return null===(e=this._stream)||void 0===e?void 0:e.isPlaying()}replay(){var e;return null===(e=this._stream)||void 0===e?void 0:e.replay()}resume(){var e,t;null===(e=this._stream)||void 0===e||e.resume(),null===(t=this.player)||void 0===t||t.resume()}hasAudio(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasAudio())||!1}hasVideo(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasVideo())||!1}updateUser(e){this.user=e;const t=this.user.userInfo.pos;t?t.includes("web")||t.includes("pc")?this.streamType=STREAM_TYPE.SUB_MAIN:t.includes("_toupingma")?this.streamType=STREAM_TYPE.SHARE:this.streamType=STREAM_TYPE.SINGLE:this.streamType=STREAM_TYPE.SINGLE}updateSortNum(e=!0){const t=this.getSortNum();this.setSortNum(t,e)}setSortNum(e,t){this.sortNum!==e&&(this.sortNum=e,t&&(BoomEmitter.emitter.emit(MODEL_SORT_NUM_CHANGE,null),this.user.updateSortNum(!0)))}getSortNum(){return this.user.isMaster?getMasterSort(this.audioEnable,this.videoEnable):this.user.isLocal?getLocalSort(this.audioEnable,this.videoEnable):this.user.isManager?getManagerSort(this.audioEnable,this.videoEnable):getGuestSort(this.audioEnable,this.videoEnable)}checkVideoDecodeFrame(e){const t=document.getElementById(e);if(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),!t)return info("黑帧检测没有播放容器",this.userId,"",["streamId =>",this.streamId,"isShare =>",this.isShare,"playerId =>",this.playerId,"bigPlayerId =>",this.bigPlayerId,"isDisplay => ",this.isDisplay,"isInbig =>",this.isInBig]),void(this.isShare&&this.isInBig&&this.bigPlayerId&&(warn("share stream has no video player, retry play"),this.playInBig()));this.checkVideoTimer=setTimeout((()=>{var r,i,s;const o=(null==t?void 0:t.getVideoPlaybackQuality)&&(null===(r=null==t?void 0:t.getVideoPlaybackQuality())||void 0===r?void 0:r.totalVideoFrames)||0;if(!t||t.getVideoPlaybackQuality){if(o>0)return clearTimeout(this.checkVideoTimer),void(this.checkFailedCount=0);if(this.checkCount>10){if(error$1("检测超过了十次,还没有视频流,需要重新拉取","黑帧检测",this.userId,["streamId =>",this.streamId,"nickname =>",this.nickname,"videoContainer => ",e]),this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount+=1,this.checkFailedCount<=3){this.hasPulled=!1,this.pulledStreamType="small",null===(i=this._stream)||void 0===i||i.off(namespace$1);try{null===(s=this._stream)||void 0===s||s.destroy()}catch(e){}this._stream=void 0,this.sendMessage2Room()}}else this.checkCount+=1,this.checkVideoDecodeFrame(e)}else this.checkVideoTimer&&clearTimeout(this.checkVideoTimer)}),200)}subscribeStream(){this.shouldPull=!0,BoomEmitter.emitter.emit(MANUAL_SUBSCRIPTION,{stream:this})}unSubscribeStream(){this.shouldPull=!1,BoomEmitter.emitter.emit(UNSUBSCRIBE_STREAM,{stream:this})}unAttach(e){var t,r,i,s;info("unattach stream play","",this.userId,["streamId =>",this.streamId,"nickname =>",this.nickname,"type =>",e]),"all"===e?(null===(t=this.stream)||void 0===t||t.stop(),null===(r=this.player)||void 0===r||r.destroy()):"big"===e?null===(i=this.player)||void 0===i||i.destroy():"small"===e&&(null===(s=this.stream)||void 0===s||s.stop())}}function getHTMLMediaStreamOptions(e){let t=null;const r=e.videoElement,i=r.offsetWidth,s=r.offsetHeight;if(r.captureStream?t=r.captureStream():r.mozCaptureStream&&(t=r.mozCaptureStream()),t){const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];return{video:!!e,audio:!!r,videoSource:e,audioSource:r,width:i,height:s}}return null}function getMediaStreamInfo(e,t){try{const r=e.getVideoTracks()[0],i=e.getAudioTracks()[0];return{video:!!r,audio:!!i,videoSource:r,audioSource:i,width:t.width,height:t.height}}catch(e){return console.log("获取共享音频参数有误",e),null}}function transShareScreen2User(e){return e.split("_")[0]}const namespace=`.streammuteevent${Math.random()}`;class BMStreamModelVM{constructor(){this.streamModels=new Map,this.streamModelsWatcher=new BehaviorSubject(BMStreamModelVM.filterStreamModels(this.sortStreamModels())),this.shareStreamModels=new Map,this.shareStreamModelsWatcher=new BehaviorSubject(Array.from(this.shareStreamModels.values())),this.localStreamErrorWatcher=new Subject,this.localModel=null,this.room=null,this.bloudStream=null,this.videoStream=null,this.audioStream=null,this.audioStats=!1,this.videoStats=!1,this.localIsShare=!1,this.isShareWatcher=new Subject,this._speaker_enable=!0,this.speakerEnableWatcher=new BehaviorSubject(this._speaker_enable),this.mixStreamModelWatcher=new BehaviorSubject(null),this.canvasTimer=null,this._isRecording=!1,this._slicingRecord=!1,this.isRecordingWatcher=new BehaviorSubject(this._isRecording),this._speaker=null,this._speakers=new Map,this.speakerWatcher=new BehaviorSubject(this._speaker),this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.localStreamConnectErrorWatcher=new Subject,this.localShareError=new Subject,this.shareBloudStateMap=new Map,this.updateModelSort=debounce((()=>{const e=this.sortStreamModels();this.streamModelsWatcher.next(BMStreamModelVM.filterStreamModels(e))}),200,{maxWait:500}),this.handleNoContainer=e=>{const{type:t,container:r,id:i}=e;let s;s="share"===t?this.shareStreamModels.get(i):this.streamModels.get(i),s&&("small"===r?this.noContainerWatcher.next(s):this.noBigContainerWatcher.next(s))},this.getHTMLMediaStream=getHTMLMediaStreamOptions,this.getMediaStream=getMediaStreamInfo,this.createCanvas(),setTimeout((()=>{this.canvasDisplay()}),100),BoomEmitter.emitter.on(MODEL_SORT_NUM_CHANGE,this.updateModelSort),BoomEmitter.emitter.on(NO_CONTAINER,this.handleNoContainer)}static filterStreamModels(e){return e.filter((e=>!e.isToupingma)).filter((e=>!ignoreUserId.some((t=>e.userId.includes(t))))).filter((e=>e.canShow))}initWithRoom(e){return this.room=e,this}setSpeakerEnable(e){var t;this._speaker_enable!==e&&(null===(t=this.room.audioPlayer)||void 0===t||t.mute(!e),this._speaker_enable=e,this.speakerEnableWatcher.next(e))}getStreamModels(){return Array.from(this.streamModels.values())}getStreamModelByUId(e){return this.streamModels.get(e)}getShareStreamModelByUId(e){return this.shareStreamModels.get(e)}getLocalStreamModel(){return this.localModel}createStreamModel(e,t){const r=new BMStreamModel(e,void 0);return t&&r.updateStream(t,!0,this),r.isShare?(e.addStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`,r),this.addShareStreamModel(r)):(e.addStream(e.userId,r),this.addStreamModel(r)),r}addStreamModel(e){e&&(e.isLocal?this.localModel||(this.localModel=e,this.streamModels.set(this.localModel.userId,this.localModel)):this.streamModels.set(e.userId,e))}addShareStreamModel(e){e&&(e.isLocal||(this.shareStreamModels.set(e.userId,e),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))))}removeStreamModel(e){if(!e)return;const t=e.getUser();this.streamModels.delete(e.userId),t.removeStream(e.userId)}removeShareStreamModelByUId(e){var t,r,i,s;const o=this.shareStreamModels.get(e);if(o){try{null===(t=o.stream)||void 0===t||t.stop(),null===(r=o.stream)||void 0===r||r.destroy()}catch(e){}o.audioEnable&&o.stream&&(null===(s=null===(i=this.room)||void 0===i?void 0:i.audioPlayer)||void 0===s||s.removeStream(o.stream)),this.removeShareStreamModel(o)}}removeShareStreamModel(e){if(!e)return;const t=e.getUser();this.shareStreamModels.delete(e.userId),t.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`),t.updateSortNum(!0),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}removeStreamModelByUId(e){var t,r,i;const s=this.getStreamModelByUId(e);if(s){if(s.stream){this.removeFromDetector(s.streamId);try{s.stream.stop(),s.stream.destroy()}catch(e){}}s.audioEnable&&(s.stream?null===(r=null===(t=this.room)||void 0===t?void 0:t.audioPlayer)||void 0===r||r.removeStream(s.stream):null===(i=this.room)||void 0===i||i.audioPlayer.removeStreamByUid(e)),this.removeStreamModel(s)}return s}remoteStreamPublished(e){const t=e.getStreamId(),r=e.getUserId().toString();let i,s=this.getStreamModelByUId(r);if(s||(i=transShareScreen2User(String(r)),s=this.getStreamModelByUId(i)),s){if(isShareStream(e)){let t;if(i&&(t=this.shareStreamModels.get(i)),t){if(t.isLocal)return;t.hasPulled=!1,t.pulledStreamType="small",t.updateStream(e,!0,this),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}else{const t=this.createStreamModel(s.getUser(),e),r=e.getVideoOn(),i=e.getAudioOn(),o=this.shareBloudStateMap.get(s.userId);o?t.updateBloudStream({audio:o.audio,video:o.video,isScreen:!0,customInfo:o.customInfo},this):t.updateBloudStream({audio:i,video:r,isScreen:!0},this),t.streamType=STREAM_TYPE.SHARE}}else s.hasPulled=!1,s.pulledStreamType="small",this.updateStreamModel(s,e);s.getUser().isMixer&&this.mixStreamModelWatcher.next(s),this.changeSingleStreamSpeaker(s).catch((e=>{error$1("设置单股流的扬声器的播放出现了问题","设置播放音量",null==s?void 0:s.userId)}))}else error$1("brtc有人推流了,但是找不到对应的streamModel, 找不到对应的用户","",r,["streamId => ",t,"types =>",e.getType&&e.getType()])}remoteStreamUnpublished(e){var t,r,i;let s;const o=e.getUserId().toString(),n=e.getStreamId();let a=!1;if(o.includes(STREAM_SUFFIX_SCREEN)){const e=transShareScreen2User(String(o));if(e==(null===(r=null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant())||void 0===r?void 0:r.userId))return info("本地用户取消共享屏幕","取消共享屏幕",o),void this.localModel.getUser().removeStream(o);s=this.getShareStreamModelByUId(e),a=!0}else n.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()?(s=this.getShareStreamModelByUId(o),a=!0):s=this.getStreamModelByUId(o);if(this.removeFromDetector(n),this.removeFromRecorder(e),!s)return void error$1("brtc有人取消推流 但是找不到对应的streamModel","取消推流",o,[n]);const d=null===(i=s.stream)||void 0===i?void 0:i.getStreamId();if(d===n)return s.hasPulled=!1,s.pulledStreamType="small",a||s.streamType===STREAM_TYPE.SHARE?(s.updateStream(void 0,!0,this),void this.removeShareStreamModel(s)):(s.updateStream(void 0,!0,this),s);error$1("当前取消推流的和当前绑定的不是同一股流","",o,["streamId =>",n,"streamModel.streamId",d])}sortStreamModels(){return sortStreamModels(Array.from(this.streamModels.values()))}updateStreamModel(e,t){e.updateStream(t,!0,this)}updateShareStreamModel(e,t){e.updateStream(t,!0,this)}setLocalVideoEnable(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(!(null===(r=this.room)||void 0===r?void 0:r.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地摄像头,不与响应");if(!this.room.mediaPermission.camera)return Promise.reject(Er$1());const i=this.getLocalStreamModel();if(info(`开关本地摄像头, 状态 => ${e}`,"本地用户",null==i?void 0:i.userId),i)if(e)if(null==i?void 0:i.stream){if(t)yield i.stream.replaceTrack(t).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}));else{if("CanvasCaptureMediaStreamTrack"===i.stream.getVideoTrack().constructor.name){const e=yield this.createVideoStream().catch((e=>Promise.reject(e)));yield i.stream.replaceTrack(e).then((()=>{info("replace video track success")})).catch((e=>(error$1("本地视频流更换视频流失败","","",JSON.stringify(e)),this.handleStreamUpdateFailed(),Promise.reject(mr$1()))))}}if(!(yield i.stream.unmuteVideo()))return error$1("brtc unmuteVideo失败"),this.handleStreamUpdateFailed(),Promise.reject(mr$1());info("brtc unmute video success"),yield this.bloudStream.setVideoEnabled(!0).then((()=>{i.updateStream(i.stream,!0,this),i.updateBloudStream({video:!0,audio:i.audioEnable,isScreen:!1},this),i.playInBig()})).catch((e=>{error$1("bloud unmuteVideo失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!1,!0,i,t).catch((e=>{var t,r,i,s,o;return error$1("开启本地摄像头失败","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(s=this.localModel)||void 0===s||s.updateStream(void 0,!0,this),null===(o=this.localModel)||void 0===o||o.updateBloudStream(void 0,this),Promise.reject(e)}));else{i.stream&&(yield this.muteOrUnpublishStream("video",!0,i).catch((e=>(error$1("关闭本地摄像头失败","","",[e]),Promise.reject(zn(e))))))}}))}handleStreamUpdateFailed(){return __awaiter(this,void 0,void 0,(function*(){error$1("brtc unmute stream failed, now unpublish"),yield this.unpublishStream()}))}setLocalAudioEnable(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(!(null===(t=this.room)||void 0===t?void 0:t.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地麦克风,不与响应");if(!this.room.mediaPermission.microphone)return Promise.reject(Sr$1());const r=this.getLocalStreamModel();if(info(`开关本地麦克风, 状态 => ${e}`,"本地用户",null==r?void 0:r.userId),r)if(e){if(null==r?void 0:r.stream){const e=yield r.stream.unmuteAudio();if(info(`unmute local stream audio res : ${e}`),!e)return error$1("brtc unmuteAudio失败","本地用户",""),yield this.handleStreamUpdateFailed(),Promise.reject(xr$1());info("unmute audio success"),yield this.bloudStream.setAudioEnabled(!0).then((()=>{info("bloud stream set audio enable"),r.updateStream(r.stream,!1,this),r.updateBloudStream({audio:!0,video:r.videoEnable,isScreen:!1},this)})).catch((e=>{error$1("bloud unmuteAudio失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!0,!1,r).catch((e=>{var t,r,i,s,o;return error$1("开启本地麦克风失败","","",[e]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(s=this.localModel)||void 0===s||s.updateStream(void 0,!0,this),null===(o=this.localModel)||void 0===o||o.updateBloudStream(void 0,this),Promise.reject(e)}));(null==r?void 0:r.stream)&&this.addToRecorder(null==r?void 0:r.stream)}else{const e=r.stream;if(e){this.removeFromRecorder(e),this.removeFromDetector(e.getStreamId());try{yield this.muteOrUnpublishStream("audio",!0,r)}catch(e){return error$1("关闭本地麦克风失败","","",[JSON.stringify(e)]),Promise.reject(Kn(e))}}}}))}joinWithAudioAndAudio(e,t){return __awaiter(this,void 0,void 0,(function*(){info("join with audio and video","join publish","",[e,t]);const r=this.getLocalStreamModel();r&&(yield this.createStreamAndPublish(e,t,r).catch((e=>{var t,r,i,s,o;return error$1("join create and publish failed","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(s=this.localModel)||void 0===s||s.updateStream(void 0,!0,this),null===(o=this.localModel)||void 0===o||o.updateBloudStream(void 0,this),Promise.reject(e)})))}))}changeSpeaker(e,t=!1){var r,i;return __awaiter(this,void 0,void 0,(function*(){if(info("change speaker","","",[JSON.stringify(e)]),!e.deviceId)throw new s(LOCAL_ERROR,"切换扬声器失败!,原因: 选择的设备没有deviceId"+(null==e?void 0:e.name));try{this.room.setSelectSpeakerDevice(e),null===(i=null===(r=this.room)||void 0===r?void 0:r.audioPlayer)||void 0===i||i.setDevice(e.deviceId,t)}catch(e){throw error$1("切换扬声器失败","","",["error",null==e?void 0:e.message,JSON.stringify(e)]),new s(LOCAL_ERROR,"切换扬声器失败")}}))}changeSingleStreamSpeaker(e){return __awaiter(this,void 0,void 0,(function*(){const t=this.room.selectAudioOutputDevice;t&&(e.isLocal||e.stream&&(yield e.stream.setAudioOutput(t.deviceId)))}))}changeAudioInput(e){var t,r,i;return __awaiter(this,void 0,void 0,(function*(){info("change audio input device","","",[JSON.stringify(e)]);const s=null===(t=this.localModel)||void 0===t?void 0:t.stream;if(null===(r=this.room)||void 0===r||r.setSelectAudioDevice(e),s){return"ended"===(null===(i=s.getAudioTrack())||void 0===i?void 0:i.readyState)?(error$1("try to change audio input device but audio track is ended"),!1):(this.removeFromRecorder(s),yield s.switchDevice("audio",e.deviceId),this.addToRecorder(s),!0)}}))}changeVideoInput(e){var t,r,i,s;return __awaiter(this,void 0,void 0,(function*(){info("change video input device","","",[JSON.stringify(e)]);const o=null===(t=this.localModel)||void 0===t?void 0:t.stream;if(null===(r=this.room)||void 0===r||r.setSelectVideoDevice(e),o){return"ended"===(null===(i=o.getVideoTrack())||void 0===i?void 0:i.readyState)?(error$1("try to change video input device but video track is ended"),!1):(yield o.switchDevice("video",e.deviceId),(null===(s=this.localModel)||void 0===s?void 0:s.isDisplay)&&this.localModel.isInBig&&this.localModel.playInBig(),!0)}}))}muteSpeaker(e){return __awaiter(this,void 0,void 0,(function*(){info("静音扬声器 状态 =>","","",["status =>",e]);try{this.setSpeakerEnable(e)}catch(t){return Promise.reject(Xn(`开关扬声器失败 ${e} error: ${JSON.stringify(t)}`))}}))}createLocalAudioStream(){var e;return __awaiter(this,void 0,void 0,(function*(){this.room.mediaPermission.microphone?(yield this.room.initDevices(),this.room.audioDevices.length?(null===(e=this.audioStream)||void 0===e||e.destroy(),this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},this.localModel.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e))))):error$1("there is no audio device exists")):error$1("there is no microphone permission")}))}createStreamAndPublish(e,t,r,i){var s,o,n,a,d,u,l,c;return __awaiter(this,void 0,void 0,(function*(){let h=BMStreamModelVM.getCanvasStream();if(yield this.room.initDevices(),t)null===(a=this.brtcStream)||void 0===a||a.destroy(),(null===(d=this.room)||void 0===d?void 0:d.audioDevices.length)||(error$1("当前电脑中没有音频输入设备,重新获取"),yield null===(u=this.room)||void 0===u?void 0:u.initDevices()),(null===(l=this.room)||void 0===l?void 0:l.videoDevices.length)||(error$1("当前电脑中没有视频输入设备, 重新获取"),yield null===(c=this.room)||void 0===c?void 0:c.initDevices()),this.room.audioDevices.length>0?this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:this.room.mediaPermission.microphone},r.userId).catch((e=>(error$1("create brtc audio and video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))):(error$1("没有音频输入设备,只能创建视频流"),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!1},r.userId).catch((e=>(error$1("create brtc video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))));else{const e=h.getVideoTracks()[0];this.audioStream||(this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},r.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e)))));const t=null===(s=this.audioStream)||void 0===s?void 0:s.getAudioTrack();if(!t||t&&t.muted)throw null===(o=this.audioStream)||void 0===o||o.destroy(),this.audioStream=null,this.localStreamErrorWatcher.next("audio"),error$1("麦克风设备不可用","","",["muted => ?",null==t?void 0:t.muted]),pr$1("麦克风");null===(n=this.brtcStream)||void 0===n||n.destroy(),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!0,videoSource:e,audioSource:t},r.userId).catch((e=>Promise.reject(e)))}this.brtcStream&&(t||(yield this.brtcStream.muteVideo()),e||(yield this.brtcStream.muteAudio()),i&&(yield this.brtcStream.replaceTrack(i).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}))),yield this.room.publish(this.brtcStream).catch((e=>{var t,r;return null===(t=this.brtcStream)||void 0===t||t.destroy(),null===(r=this.localModel)||void 0===r||r.updateBloudStream(void 0,this),Promise.reject(e)})),this.brtcStream.on("video-track-mute"+namespace,this.muteHandler.bind(this,"video")),this.brtcStream.on("video-track-ended"+namespace,this.muteHandler.bind(this,"video")),this.brtcStream.on("audio-track-mute"+namespace,this.muteHandler.bind(this,"audio")),this.brtcStream.on("audio-track-ended"+namespace,this.muteHandler.bind(this,"audio")),yield this.publishBloudStream(e,t))}))}publishBloudStream(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){const i=this.localModel.userId;this.bloudStream=this.room.boomCore.creteBloudLocalStream({audio_enable:e,video_enable:t},i),yield this.bloudStream.publish({video_enable:t,audio_enable:e}),null===(r=this.localModel)||void 0===r||r.updateBloudStream({video:t,audio:e,isScreen:!1},this)}))}muteHandler(e){const t=()=>__awaiter(this,void 0,void 0,(function*(){var e,t,r,i,s,o,n,a,d;(null===(e=this.localModel)||void 0===e?void 0:e.stream)&&(yield null===(t=this.room)||void 0===t?void 0:t.boomCore.unpublish(this.localModel.stream).catch((e=>{error$1("brtc local stream has problem and unpublish failed","","",[String(e)])}))),null===(i=null===(r=this.localModel)||void 0===r?void 0:r.stream)||void 0===i||i.destroy(),null===(s=this.audioStream)||void 0===s||s.destroy(),null===(o=this.videoStream)||void 0===o||o.destroy(),null===(n=this.brtcStream)||void 0===n||n.destroy(),this.brtcStream=void 0,this.audioStream=null,this.videoStream=null,null===(a=this.localModel)||void 0===a||a.updateStream(void 0,!0,this),yield this.bloudStream.unpublish(),this.bloudStream=null,null===(d=this.localModel)||void 0===d||d.updateBloudStream(void 0,this)}));setTimeout((()=>__awaiter(this,void 0,void 0,(function*(){var r,i,s,o,n,a,d,u,l,c,h,m,p,f,v,g,S;if(null===(r=this.localModel)||void 0===r?void 0:r.stream){const r=null===(i=this.localModel)||void 0===i?void 0:i.videoEnable,b=null===(s=this.localModel)||void 0===s?void 0:s.audioEnable;if("video"===e){const i=null===(o=this.localModel.stream.getVideoTrack())||void 0===o?void 0:o.muted,s=null===(n=this.localModel.stream.getVideoTrack())||void 0===n?void 0:n.label,g=null===(a=this.localModel.stream.getVideoTrack())||void 0===a?void 0:a.enabled,S=null===(d=this.localModel.stream.getVideoTrack())||void 0===d?void 0:d.readyState,y="ended"===S;if(info("brtc video track status","","",[i,g,S,s]),!y&&!i&&g)return;info("video track has problem, now try recreate and publish"),error$1("brtc本地流出现异常,需要重新推流处理","","",["videoEnable",r,"audioEnable",b,"type",e]),this.localStreamConnectErrorWatcher.next(hr("摄像头")),(null===(u=this.localModel)||void 0===u?void 0:u.stream)&&(yield null===(l=this.room)||void 0===l?void 0:l.boomCore.unpublish(this.localModel.stream).catch((e=>{error$1("brtc local stream has problem and unpublish failed","","",[String(e)])})),null===(c=this.localModel)||void 0===c||c.updateStream(void 0,!0,this),null===(m=null===(h=this.localModel)||void 0===h?void 0:h.stream)||void 0===m||m.destroy(),null===(p=this.audioStream)||void 0===p||p.destroy(),null===(f=this.brtcStream)||void 0===f||f.destroy(),this.brtcStream=void 0,null===(v=this.videoStream)||void 0===v||v.destroy(),this.audioStream=null,this.videoStream=null),yield this.createStreamAndPublish(b,r,this.localModel).catch((e=>__awaiter(this,void 0,void 0,(function*(){error$1("brtc video stream has problem and republish stream failed","","",[JSON.stringify(e)]),yield t(),this.localStreamConnectErrorWatcher.next(dr())}))))}else{error$1("brtc本地流出现异常,需要重新推流处理","","",["videoEnable",r,"audioEnable",b,"type",e]),this.localStreamConnectErrorWatcher.next(hr("麦克风")),null===(g=this.audioStream)||void 0===g||g.destroy(),this.audioStream=null,this.audioStream=yield this.room.createPBSingleLocalStream({video:!1,audio:!0});const i=null===(S=this.audioStream)||void 0===S?void 0:S.getAudioTrack();i&&!i.muted?this.localModel.stream&&(yield this.localModel.stream.replaceTrack(i).catch((e=>{error$1("本地流出现异常, 重新创建audio stream replace 失败","本地流出现异常","",[JSON.stringify(e)]),this.localStreamConnectErrorWatcher.next(dr()),t()}))):(error$1("recreate audio stream failed, now unpub"),this.localStreamConnectErrorWatcher.next(dr()),t())}}this.localStreamErrorWatcher.next(e)}))),1e3)}unpublishStream(){var e,t,r,i;return __awaiter(this,void 0,void 0,(function*(){info("unpublish stream");const s=this.getLocalStreamModel();if(s){const o=s.stream;o&&(yield null===(e=this.room)||void 0===e?void 0:e.unpublish(o).catch((e=>{error$1("brtc 取消发布失败","取消推流",s.userId,[JSON.stringify(e)])})));try{this.removeFromRecorder(o),null==o||o.destroy(),null===(t=this.videoStream)||void 0===t||t.destroy(),null===(r=this.audioStream)||void 0===r||r.destroy(),null===(i=this.brtcStream)||void 0===i||i.destroy(),this.videoStream=null,this.audioStream=null,this.brtcStream=void 0,s.updateStream(void 0,!0,this),yield this.bloudStream.unpublish().catch((e=>{error$1("bloud unpublish stream failed","bloud unpublish stream",s.userId,[JSON.stringify(e),null==e?void 0:e.code,null==e?void 0:e.message])})),s.updateBloudStream(void 0,this),this.bloudStream=null}catch(e){error$1("stream destroy failed","取消推流",s.userId,[JSON.stringify(e)])}}}))}muteOrUnpublishStream(e,t,r){var i;return __awaiter(this,void 0,void 0,(function*(){const t=r.stream;let s=!0;if("audio"===e?s=t.getVideoOn():"video"===e&&(s=t.getAudioOn()),s){if("audio"===e){(yield t.muteAudio())||error$1("brtc muteAudio失败","关闭本地音频","本地"),yield this.bloudStream.setAudioEnabled(!1).catch((e=>{error$1("bloud setAudioEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({audio:!1,video:!0,isScreen:!1},this)}else if("video"===e){const e=BMStreamModelVM.getCanvasStream().getVideoTracks()[0];try{yield t.replaceTrack(e),yield t.muteVideo()}catch(e){error$1("关闭本地视频失败","关闭本地视频","本地",[JSON.stringify(e)])}try{null===(i=this.videoStream)||void 0===i||i.destroy(),this.videoStream=null}catch(e){error$1("this.videoStream destroy failed")}yield this.bloudStream.setVideoEnabled(!1).catch((e=>{error$1("bloud setVideoEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({video:!1,audio:!0,isScreen:!1},this)}}else yield this.unpublishStream()}))}toggleShareScreen(e,t,r){var i,s,o,n,a;return __awaiter(this,void 0,void 0,(function*(){info("开关共享屏幕","","开关共享屏幕",["stats => ",e]),!e&&(null===(i=this.room)||void 0===i?void 0:i.boomCore.shareScreenStream)&&this.removeFromRecorder(null===(s=this.room)||void 0===s?void 0:s.boomCore.shareScreenStream);const d=null===(o=this.room)||void 0===o?void 0:o.voiceMode;return yield this.room.boomCore.toggleShareScreen(e,{audioHint:d},r).then((()=>{if(info("bmStreamVm toggleShareScreen success","切换共享屏幕","",["enable =>",e,"options =>",JSON.stringify(t)]),e){const e=this.room.boomCore.shareScreenStream;e&&this.remoteStreamPublished(e)}else this.localModel.getUser().removeStream(`${this.localModel.userId}_screen`),this.localModel.getUser().updateSortNum(!0)})).catch((r=>(error$1("bmStreamVm toggleShareScreen error","切换共享屏幕","",["enable =>",e,"options =>",t]),Promise.reject(r)))),e&&(null===(n=this.room)||void 0===n?void 0:n.boomCore.shareScreenStream)&&this.addToRecorder(null===(a=this.room)||void 0===a?void 0:a.boomCore.shareScreenStream),this.localIsShare=e,this.isShareWatcher.next(e),Promise.resolve(!0)}))}setShareScreenContentHint(e){var t;null===(t=this.room)||void 0===t||t.boomCore.setShareScreenContentHint(e)}createCanvas(){const e=document.createElement("canvas");e.id="tarCanvas",e.style.width="1px",e.style.height="1px",e.style.position="absolute",e.style.bottom="0",document.body.appendChild(e)}canvasDisplay(){let e=document.getElementById("tarCanvas");if(e){e.width=640,e.height=360;let t=e.getContext("2d");t.fill(),t.beginPath(),t.fillStyle="rgb(0,0,0)",t.fillRect(0,0,e.width,e.height),this.canvasTimer&&clearTimeout(this.canvasTimer),this.canvasTimer=setTimeout((()=>{this.canvasDisplay()}),1e3)}}static getCanvasStream(){return document.getElementById("tarCanvas").captureStream()}createVideoStream(){var e;return __awaiter(this,void 0,void 0,(function*(){return yield this.room.initDevices(),null===(e=this.videoStream)||void 0===e||e.destroy(),this.videoStream=yield this.room.createPBSingleLocalStream({video:!0,audio:!1},this.localModel.userId).catch((e=>Promise.reject(ar("视频")))),this.videoStream.getVideoTrack()}))}startRecord(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(this._recorder)return;this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(e),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended")})),this._recorder.on("started",(()=>{info("record started.")}));let r=!0;try{yield this._recorder.start(),this._isRecording=!0,this.isRecordingWatcher.next(!0),this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),r=!1,yield t.stop()}return r}))}addToRecorder(e){this._isRecording&&!this._slicingRecord&&(e.on("audio-track-ended",(()=>{this.removeFromRecorder(e)})),this._recorder.addStream(e))}removeFromRecorder(e){this._isRecording&&!this._slicingRecord&&this._recorder.removeStream(e)}stopRecord(){return __awaiter(this,void 0,void 0,(function*(){this._recorder&&(this._isRecording=!1,this.isRecordingWatcher.next(!1),yield this._recorder.stop(),this._recorder=void 0)}))}sliceRecord(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(!this._isRecording)return;let r=this._recorder._opts;this._slicingRecord=!0;try{yield this._recorder.stop()}catch(e){error$1("stop record exception","","",[JSON.stringify(e)])}r.filename=e,this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(r),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended.")})),this._recorder.on("started",(()=>{info("record started.")}));let i=!0;try{yield this._recorder.start(),this._slicingRecord=!1,this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),this._slicingRecord=!1,i=!1,yield t.stop()}return i}))}startSpeakerDetector(){var e;this._speaker=null,this._speakerDetector=null===(e=this.room)||void 0===e?void 0:e.boomCore.createSpeakerDetector(),this._speakerDetector.on("speaker",(e=>{var t,r,i;let s=!0;e?((null===(t=this._speaker)||void 0===t?void 0:t.getUserInfo().userId)===e.getUser().userId&&(s=!1),this._speaker=e.getUser()):(this._speaker||(s=!1),this._speaker=null),s&&(info("当前讲话人","语音激励",null===(r=this._speaker)||void 0===r?void 0:r.userId,["nickname => ",null===(i=this._speaker)||void 0===i?void 0:i.nickname]),this.speakerWatcher.next(this._speaker))}))}addToDetector(e){this._speakers.set(e.getID(),e),this._speakerDetector&&this._speakerDetector.addStream(e)}removeFromDetector(e){let t=this._speakers.get(e);this._speakerDetector&&t&&(this._speakers.delete(e),this._speakerDetector.removeStream(t))}clearDetector(){const e=[];this._speakers.forEach(((t,r)=>{e.push(r)})),e.forEach((e=>{this.removeFromDetector(e)}))}shareCustomMedia(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){return null===(r=this.room)||void 0===r?void 0:r.boomCore.shareHTMLMedia(e,t)}))}updateBloudStreamCustomStats(e,t,r){var i;return null===(i=this.room)||void 0===i?void 0:i.boomCore.updateStream(e,t,r)}checkStreamStats(e){info("check stream stats","","",[e]),this.streamModels.size<100&&this.streamModels.forEach((e=>{e.checkStreamIsPlaying()}))}clearCache(){var e,t,r,i,s;try{null===(t=null===(e=this.localModel)||void 0===e?void 0:e.stream)||void 0===t||t.destroy(),null===(r=this.videoStream)||void 0===r||r.destroy(),null===(i=this.audioStream)||void 0===i||i.destroy()}catch(e){}this.streamModels.clear(),this.shareStreamModels.clear(),null===(s=this.room)||void 0===s||s.userVM.clearUsers(),this.shareBloudStateMap.clear()}}class BMRoomInfo{constructor(){this.room=null,this._roomName="",this.msgSeq="",this.roomID="",this.audioOff=!1,this.selfopenaudio=!1,this.lock=!1,this.leaveNotice=!1,this.openSelf=!1,this.chatNotice="",this.chatNoticeRich="",this.raiseHandsList=new Map,this.raiseHandsWatcher=new BehaviorSubject(Array.from(this.raiseHandsList.values())),this.raiseVideoHandsList=new Map,this.raiseVideoHandsWatcher=new BehaviorSubject(Array.from(this.raiseVideoHandsList.values())),this.raiseSimpleHandsList=new Map,this.raiseSimpleHandsWatcher=new BehaviorSubject(Array.from(this.raiseSimpleHandsList.values())),this.operationPermissionWatcher=new Subject,this.chatNoticeWatcher=new Subject,this.totalUserWatcher=new BehaviorSubject(0),this.totalWaitRoomUserWatcher=new BehaviorSubject(0),this.isOpenWaitRoom=new Subject,this.audioOffWatcher=new Subject,this.lockWatcher=new BehaviorSubject(this.lock),this.leaveNoticeWatcher=new BehaviorSubject(this.leaveNotice),this.openSelfWatcher=new BehaviorSubject(this.openSelf),this.setRaiseHandsWatcherValue=debounce((()=>{this.raiseHandsWatcher.next(Array.from(this.raiseHandsList.values()))}),1e3),this.setVideoRaiseHandsWatcherValue=debounce((()=>{this.raiseVideoHandsWatcher.next(Array.from(this.raiseVideoHandsList.values()))}),1e3),this.setSimpleRaiseHandsWatcherValue=debounce((()=>{this.raiseSimpleHandsWatcher.next(Array.from(this.raiseSimpleHandsList.values()))}),1e3),BoomEmitter.emitter.on(RAISE_HAND,(e=>{"raiseHandsAudio"===e.status?e.user.raiseAudioHands?this.addRaiseHandUser(e.user):this.removeRaiseHandUser(e.user.userId):"raiseHandsVideo"===e.status?e.user.raiseVideoHands?this.addVideoRaiseHandUser(e.user):this.removeVideoRaiseHandUser(e.user.userId):"raiseHand"===e.status&&(e.user.raiseHand?this.addSimpleRaiseHandUser(e.user):this.removeSimpleRaiseHandUser(e.user.userId))}))}get roomName(){return this._roomName||(this._roomName=this.room.getName()),this._roomName}get isBigRoom(){return this.room.isBig}setup(e){this.roomID=e.room,this.handleInitParams()}bindRoom(e){this.room=e}initCustomStats(e){this.operationPermission=e,void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}updateOperationPermission(e){this.operationPermission=Object.assign(Object.assign({},this.operationPermission),e),void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}handleInitParams(){const e=this.room.boomCore.getAudioOff(),t=this.room.boomCore.getSelfOpenAudio();this.setAudioOff(e,t)}setAudioOff(e,t){this.audioOff=e,this.selfopenaudio=t,this.audioOffWatcher.next({audioOff:e,selfopenaudio:t})}setlock(e){this.lock=e,this.lockWatcher.next(e)}setLeaveNotice(e){this.leaveNotice=e,this.leaveNoticeWatcher.next(e)}setRaiseHandsList(e){e.forEach((e=>{e.raiseAudioHands&&this.raiseHandsList.set(e.getID(),e),e.raiseVideoHands&&this.raiseVideoHandsList.set(e.getID(),e),e.raiseHand&&this.raiseSimpleHandsList.set(e.getID(),e)})),this.setRaiseHandsWatcherValue(),this.setVideoRaiseHandsWatcherValue(),this.setSimpleRaiseHandsWatcherValue()}addRaiseHandUser(e){this.raiseHandsList.set(e.getID(),e),this.setRaiseHandsWatcherValue()}removeRaiseHandUser(e){this.raiseHandsList.delete(e),this.setRaiseHandsWatcherValue()}addVideoRaiseHandUser(e){this.raiseVideoHandsList.set(e.getID(),e),this.setVideoRaiseHandsWatcherValue()}removeVideoRaiseHandUser(e){this.raiseVideoHandsList.delete(e),this.setVideoRaiseHandsWatcherValue()}addSimpleRaiseHandUser(e){this.raiseSimpleHandsList.set(e.getID(),e),this.setSimpleRaiseHandsWatcherValue()}removeSimpleRaiseHandUser(e){this.raiseSimpleHandsList.delete(e),this.setSimpleRaiseHandsWatcherValue()}}var name="@hysc/meeting",version="10.0.10",description="boom meeting",main="./dist/index.js",module$1="./dist/index.mjs",types="./dist/index.d.ts",files=["dist","umd"],scripts={build:"tsup ./src/index.ts --format cjs,esm --dts --minify",dev:"tsup ./src/index.ts --format esm,cjs --watch --dts"},author="yangliye",license="MIT",dependencies={"@hysc/bloud":"workspace:*","@hysc/core":"workspace:*","lodash-es":"^4.17.21",mitt:"^3.0.0","@hysc/p-queue":"6.3.0",rxjs:"^7.5.5",typescript:"^4.6.3","@hysc/utils":"workspace:*"},peerDependencies={"@hysc/core":"workspace:*"},devDependencies={"@types/lodash-es":"^4.17.6","@hysc/brtc":"workspace:*"},PackageJson={name:name,version:version,description:description,private:!1,main:main,module:module$1,types:types,files:files,scripts:scripts,author:author,license:license,dependencies:dependencies,peerDependencies:peerDependencies,devDependencies:devDependencies};class BMLiveVM{constructor(e){this.room=e}get localBMUser(){return this.room.getLocalParticipant()}get localIsAudience(){return this.room.getLocalParticipant().isAudience}handlePull(e){return __awaiter(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePull(e)):yield this.room.handlePull(e)}))}handleChangeStreamType(e){return __awaiter(this,void 0,void 0,(function*(){yield this.room.handleChangeStreamType(e)}))}handlePlay(e,t){return __awaiter(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePlay(e,t,!1)):yield this.room.handlePlay(e,t,!0)}))}handleAudienceDisable(){return __awaiter(this,void 0,void 0,(function*(){this.room.bmStreamVm.getStreamModels().forEach((e=>{var t;(null===(t=null==e?void 0:e.stream)||void 0===t?void 0:t.isSubscribed())&&e.hasPulled&&(e.hasPulled=!1,e.pulledStreamType="small",this.room.unsubscribe(e.stream).then((()=>{console.log("观众取消订阅这股流",e.userId,e.nickname,e.isDisplay,e.isCurrentDisplay)})))}));const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1))}))}handleAudienceEnable(){return __awaiter(this,void 0,void 0,(function*(){const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1)),this.room.bmStreamVm.getStreamModels().forEach((e=>{streamPullQueue.addQueue(this.room.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}))}))}}function addBrtcNetEvent(e){var t,r;null===(t=e.brtcClient.client)||void 0===t||t.signal.channel.on("reconnecting",(()=>e.fire(dt$1.BRTC_ROOM_ROCONNECTING))),null===(r=e.brtcClient.client)||void 0===r||r.signal.channel.on("reconnected",(()=>e.fire(dt$1.BRTC_ROOM_RECONNECTED)))}class SingletonQueue{constructor(){return this.pullMap=new Map,SingletonQueue.instance?SingletonQueue.instance:(SingletonQueue.instance=this,this)}addUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.set(`${e.id}_screen`,e):this.pullMap.set(e.id,e)})),this._callback&&this._callback(this.pullMap)}removeUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.delete(`${e.id}_screen`):this.pullMap.delete(e.id)}))}restart(){if(!this._callback)throw error$1("no callback exists in streamQueue please setQueueProcessor first!"),new Error("no callback");this._callback(this.pullMap)}setQueueProcessor(e){this._callback=e}removeQueueProcessor(){this._callback=void 0}}class AudioPlay{constructor(e,t){this.playMap=new WeakSet,this.playerMap=new Map,this.muted=!1,this.playStateChangeWatcher=new Subject;const r=document.getElementById(e);if(!r)throw new Error("no container found, play failed");this.container=r,this.room=t}addStream(e,t=!1){this.room.shouldPlayAudio&&this.room.autoPlayAudio&&e.isSubscribed()&&(this.playMap.has(e)&&!t||(info("add stream to player","",e.getUserId(),["streamId ",e.getStreamId()]),this.playMap.add(e),this.play(e)))}removeStream(e){const t=e.getStreamId();let r=this.playerMap.get(t);r&&(r.off(),r.destroy()),info("remove audio player","","",["streamId =>",t]),this.playerMap.delete(t),this.playMap.delete(e)}removeStreamByUid(e){let t=new Map;this.playerMap.forEach((r=>{isShareStream(r.stream)||r.stream.getUserId()===e&&t.set(r.stream.getStreamId(),r)})),t.forEach(((e,t)=>{e.off(),e.destroy(),this.playerMap.delete(t),this.playMap.delete(e.stream)})),t.clear()}play(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(e.hasAudio()&&this.container){const r=new _(this.container,{});if(this.addPlayerEvent(r),yield r.play(e),this.deviceId&&(yield r.setSinkId(this.deviceId)),this.muted)r.setVolume(0);else{let i;const s=transShareScreen2User(e.getUserId().toString());if(i=isShareStream(e)?this.room.bmStreamVm.shareStreamModels.get(s):this.room.bmStreamVm.streamModels.get(s),i){const e=null===(t=i.bloudStream)||void 0===t?void 0:t.customInfo;e&&e.volume&&(r.audioLevel=e.volume,r.setVolume(e.volume))}}this.playerMap.set(e.getStreamId(),r)}}))}mute(e){this.muted=e,e?this.playerMap.forEach((e=>e.setVolume(0))):this.playerMap.forEach((e=>{e.audioLevel>0?e.setVolume(e.audioLevel):e.setVolume(1)}))}setVolume(e,t){const r=this.playerMap.get(e);if(r){if(r.audioLevel=t,this.muted)return;r.setVolume(t)}else error$1("设置了流的音量,但是没有找到对应的播放器",e)}setDevice(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){this.deviceId=e,t&&(yield sleep(2e3)),this.playerMap.forEach((t=>__awaiter(this,void 0,void 0,(function*(){yield t.setSinkId(e)}))))}))}addPlayerEvent(e){e.on("player-state-changed",(t=>{e.stream&&(info("audio player state change","","",[JSON.stringify(t)]),"error"===t.type&&t.reason&&"NotAllowedError"===t.reason.name&&this.playStateChangeWatcher.next(e),"PAUSED"===t.state&&e.resume())}))}clear(){info("audio play clear"),this.playerMap.forEach((e=>e.destroy())),this.playerMap.clear(),this.playMap=new WeakSet}destroy(){info("audio play destroy"),this.playerMap.forEach((e=>e.destroy())),this.playerMap.clear(),this.playMap=new WeakSet}}let _selfSortType=1;const subscribeOptions={audio:!0,video:!0,streamType:"small",videoEnable:!0,audioEnable:!0};let autoPlayAudio=!0;class BMRoom{constructor({initDevices:e}={initDevices:!0}){this.roomVM=null,this.videoDevices=[],this.audioDevices=[],this.audioOutputDevices=[],this.selectVideoDevice=null,this.selectAudioDevice=null,this.selectAudioOutputDevice=null,this.streamQueue=new SingletonQueue,this.userListColumns=1,this.sortType=1,this.BRTCConnectFailed=!1,this.pubFailedNum=0,this.streamConnectedErrorQueue=[],this.conferenceMode=1,this.isBig=!1,this.selectVideoDeviceWatcher=new BehaviorSubject(this.selectVideoDevice),this.selectAudioDeviceWatcher=new BehaviorSubject(this.selectAudioDevice),this.selectAudioOutputDeviceWatcher=new BehaviorSubject(this.selectAudioOutputDevice),this.audioDevicesWatcher=new Subject,this.videoDevicesWatcher=new Subject,this.audioOutputDevicesWatcher=new Subject,this.raiseHandleRespWatcher=new Subject,this.enableAudienceSpeakingWatcher=new Subject,this.mediaPermission={microphone:!0,camera:!0,screen:!0},this.videoProfile="360p",this.audioProfile=null,this.voiceMode="",this.streamWSReconnectWatcher=new Subject,this.bloudWSReconnectWatcher=new Subject,this.netConnecting=!0,this.netConnectingWatcher=new Subject,this.hasSyncPermission=!0,this.meetingControlOptions={cancelAutoPull:!1},this.forceId="",this.networkState={bloud:!0,brtc:!0},this.brtcNetEnableWatcher=new Subject,this.autoPlayAudio=!0,this.pubFailedTimer=null,this.messageWatcher=new BehaviorSubject({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),this.isInWaitRoom=!1,this.shouldPlayAudio=!0,this.handleReprocessStreamError=()=>{this.netConnecting&&this.networkState.brtc&&this.networkState.bloud&&this.streamConnectedErrorQueue.length&&(info("brtc 网络恢复正常,处理重推逻辑","","",this.streamConnectedErrorQueue),this.streamConnectedErrorQueue.forEach((e=>{this.handleStreamConnectError(e)})),this.streamConnectedErrorQueue=[])},this.handleMediaDevicesChange=debounce((()=>__awaiter(this,void 0,void 0,(function*(){const e=this.filterDevice(this.audioDevices);yield this.bmStreamVm.changeAudioInput(e);const t=this.filterDevice(this.audioOutputDevices);yield this.bmStreamVm.changeSpeaker(t,!0)}))),1e3),this.enumVideoDevices=gt,this.enumAudioInputDevices=mt,this.enumAudioOutputDevices=pt,this.getPermissions=bt,this.checkSystemSupport=ft,this.createStream=yt,this.participantNotice=!1,this.handleQueueTask=(e,t=!1)=>__awaiter(this,void 0,void 0,(function*(){this.BRTCConnectFailed||(e.isLocal||!this.meetingControlOptions.cancelAutoPull||e.shouldPull)&&(this.streamModelExits(e)?yield this.handleStreamTask(e,t):warn(`streamModel is not exits, userId: ${e.userId}, isShare: ${e.isShare}, ignore`))})),this.republishLocalStream=debounce((e=>__awaiter(this,void 0,void 0,(function*(){const t=e.getAudioOn()||!1,r=e.getVideoOn()||!1;info("republish local stream ","","",[t,r]),(t||r)&&(yield this.publish(e).then((()=>__awaiter(this,void 0,void 0,(function*(){this.bmStreamVm.bloudStream=null,yield this.bmStreamVm.publishBloudStream(t,r),info("local stream connect error, and republish success, bloud stream republish success","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(Rr$1(t,r))})))).catch((()=>{info("local stream connect error, and republish failed","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(yr$1())})))}))),1e3),this.processUser=e=>__awaiter(this,void 0,void 0,(function*(){const t=new Set;if(e.forEach((e=>{if(e.isScreen){const r=this.bmStreamVm.getShareStreamModelByUId(e.id);r&&r.stream||(e.isWeb?t.add(`${e.id}_screen`):t.add(e.id))}else{let r=this.bmStreamVm.streamModels.get(e.id);r&&!r.stream&&t.add(e.id)}})),info("brtc query streams","","",["queryIds => ",JSON.stringify(Array.from(t))]),t.size)try{const e=yield this.queryBrtcStreams(Array.from(t));if(e&&e.length){const t=e.map((e=>[e.getUserId(),e.getStreamId()]));info("brtc query streams result","","",["streamInfo =>",JSON.stringify(t)]),e&&this.handleAddStreams(e)}}catch(e){error$1("query stream error","","",[JSON.stringify(e)])}})),this.queueProcessor=debounce(this.processUser,500,{maxWait:1e3}),kt$1.setLogLevel(se.INFO),info(`\n******************************************************************************\n* 欢迎使用 BoomCore(${PackageJson.version})\n******************************************************************************\n `),kt$1.info("this is formatted by hysc/logger module");const t=BoomEmitter.getInstance();this.localUser=new BMUser({},!0),this.roomInfo=new BMRoomInfo,this.roomInfo.bindRoom(this),this.bmLiveVM=new BMLiveVM(this),this.bmStreamVm=(new BMStreamModelVM).initWithRoom(this),this.boomCore=new St({}),t.on(RECEIVE_SUBSCRIBE_MESSAGE,(e=>{this.handleSubMessage(e)})),t.on(HANDLE_STREAM_CONNECT_ERROR,(e=>{this.handleStreamConnectError(e)})),t.on(ADD_PULL_USER,(e=>{this.addUser2Queue(e)})),t.on(MANUAL_SUBSCRIPTION,(e=>{this.manualSubscribeStreamModel(e.stream)})),t.on(UNSUBSCRIBE_STREAM,(e=>{this.handleUnsubscribe(e.stream)})),t.on(BIND_ELEMENT,(e=>{this.handleStreamBindElement(e.stream)})),t.on(BIND_BIG_ELEMENT,(e=>{this.handleStreamBindBigElement(e.stream)})),t.on(SET_VOLUME,(e=>{var t;null===(t=this.audioPlayer)||void 0===t||t.setVolume(e.streamId,e.volume)})),t.on(ADD_AUDIO_PLAY,(e=>{const t=e.stream.stream;t&&!t.isLocalStream()&&(this.audioPlayer.playMap.has(t)||this.audioPlayer.addStream(t))})),window.addEventListener("offline",(()=>{this.netConnecting=!1,this.netConnectingWatcher.next(!1)})),window.addEventListener("online",(()=>{this.netConnecting=!0,this.netConnectingWatcher.next(!0),NETWORK_ERROR_QUEUE.forEach((e=>{e()})),NETWORK_ERROR_QUEUE.clear(),this.handleReprocessStreamError()})),window.navigator.mediaDevices&&e&&(window.navigator.mediaDevices.ondevicechange=e=>__awaiter(this,void 0,void 0,(function*(){info("media devices change","","",[JSON.stringify(e)]),yield this.initDevices(),yield this.handleMediaDevicesChange()})),this.initDevices()),this.streamQueue.setQueueProcessor(this.queueProcessor),this.brtcNetEnableWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()})),this.bloudWSReconnectWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()}))}setVoiceMode(e){this.voiceMode=e}get isSingleColumns(){return 1===this.userListColumns}setAutoPlayAudio(e){this.autoPlayAudio=e,autoPlayAudio=e}setMediaPermission(e){this.mediaPermission=Object.assign(Object.assign({},this.mediaPermission),e),info("current media permission is ","","",[JSON.stringify(this.mediaPermission)])}setShouldPlayAudio(e){this.shouldPlayAudio=e}initAudioPlayer(e){info("init audio player"),this.audioPlayer=new AudioPlay(e,this)}setupMeetingControlOptions(e){e&&(this.meetingControlOptions=Object.assign(Object.assign({},this.meetingControlOptions),e))}handleSubMessage(e){streamPullQueue.addQueue(this.handleQueueTask.bind(this,e.stream),`${e.stream.streamId} - 订阅流 - display ${e.stream.isDisplay} - currentDisplay - ${e.stream.isCurrentDisplay}`,0,e.stream.nickname)}setVideoProfile(e){e&&(info(`set video profile ${e} `),this.videoProfile=e)}setUserListColumns(e){const t=toNumber(e);if(!isNumber(t))throw new Error("参数必须是数字");this.userListColumns=t}setSortType(e){const t=toNumber(e);if(t>2||t<1)throw new Error("排序映射只能为 2 或者 1");this.sortType=t,_selfSortType=this.sortType}setAudioProfile(e){this.audioProfile=e}setSig(e){this.boomCore.setShareSig(e)}initDevices(){return __awaiter(this,void 0,void 0,(function*(){return Promise.all([this.enumVideoDevices().then((e=>{this.videoDevices=e,this.videoDevicesWatcher.next(e)})),this.enumAudioInputDevices().then((e=>{this.audioDevices=e,this.audioDevicesWatcher.next(e)})),this.enumAudioOutputDevices().then((e=>{this.audioOutputDevices=e,this.audioOutputDevicesWatcher.next(e)}))]).then((()=>{let e=this.videoDevices.filter((e=>{var t;return e.name==(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.name)}));const t=e[0]?e[0]:this.filterDevice(this.videoDevices);t&&this.setSelectVideoDevice(t);let r=this.audioDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.name)}));const i=r[0]?r[0]:this.filterDevice(this.audioDevices);i&&this.setSelectAudioDevice(i);let s=this.audioOutputDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.name)}));const o=s[0]?s[0]:this.filterDevice(this.audioOutputDevices);return o&&this.setSelectSpeakerDevice(o),{videoDevices:this.videoDevices,audioDevices:this.audioDevices,audioOutputDevices:this.audioOutputDevices,selectVideoDevice:this.selectVideoDevice,selectAudioDevice:this.selectAudioDevice,selectAudioOutputDevice:this.selectAudioOutputDevice}}))}))}filterDevice(e){const t=e.filter((e=>e.default))[0];return t||e[0]}setSelectAudioDevice(e){var t;(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectAudioDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioDevice=e,this.selectAudioDeviceWatcher.next(e))}setSelectVideoDevice(e){var t;(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectVideoDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectVideoDevice=e,this.selectVideoDeviceWatcher.next(e))}setSelectSpeakerDevice(e){var t;(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectSpeakerDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioOutputDevice=e,this.selectAudioOutputDeviceWatcher.next(e))}observe(e,t){return this.observes[e].subscribe(t)}join(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.brtc_host;t&&this.setCustomUrl(t);try{if(this.boomCore.client)return error$1("重复 join,请先调用 destroy"),Promise.reject(vn);this.conferenceMode=e.roomType,this.isBig=e.is_big,info("========================","join info",e.userId,["roomId: ",e.room," roomType: ",e.roomType," roomName: ",e.name]),this.localUser.setup(e.userId,e.userinfo,e.nickname),this.bmStreamVm.createStreamModel(this.localUser),this.userVM=new BMUserVM(this.boomCore,this.localUser,this),this.isBig&&(this.userVM.commTimer=1e3),this.roomVM=new BMRoomVM(this.boomCore,this.userVM,this.roomInfo),this.roomVM.initWithRoom(this),this.chatVM=new BMChatVM(this.boomCore,this.userVM,this),this._attachEvents(),yield this.boomCore.join(e).catch((e=>Promise.reject(e))),this.roomInfo.setup(this.boomCore.getRoomInfo());for(let e in this.observes)this.observe(e,(()=>{}));this.bmStreamVm.startSpeakerDetector(),this.roomInfo.setlock(this.boomCore.client.lock),addBrtcNetEvent(this.boomCore)}catch(e){return error$1("join room error","","",[JSON.stringify(e)]),Promise.reject(e)}}))}leave(){var e,t;return __awaiter(this,void 0,void 0,(function*(){try{this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedNum=0,BoomEmitter.removeEmitter(),autoPlayAudio=!0,null===(e=this.audioPlayer)||void 0===e||e.destroy(),this.bmStreamVm.clearCache(),this.bmStreamVm.canvasTimer&&clearTimeout(this.bmStreamVm.canvasTimer);const r=yield this.boomCore.leave().catch((()=>{error$1("bloud离会失败")}));for(let e in this.observes)null===(t=this.observes[e])||void 0===t||t.unsubscribe();return this.observes={},r}catch(e){return error$1("leave room error","","",[JSON.stringify(e)]),Promise.reject(Hn(JSON.stringify(e)))}}))}releaseRoom(){return __awaiter(this,void 0,void 0,(function*(){yield this.boomCore.releaseRoom()}))}startRecord(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.bmStreamVm.startRecord(e)}))}stopRecord(){return __awaiter(this,void 0,void 0,(function*(){return yield this.bmStreamVm.stopRecord()}))}sliceRecord(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.bmStreamVm.sliceRecord(e)}))}close(){this.bmStreamVm.clearCache(),this.boomCore.close()}setRemoteVideoEnable(e,t){return __awaiter(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setRemoteAudioEnable(e,t,r){return __awaiter(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteAudioEnable(e,t,r).catch((e=>Promise.reject(e)))}))}setLocalVideoEnable(e,t){return __awaiter(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setLocalAudioEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalAudioEnable(e).catch((e=>Promise.reject(e)))}))}setLocalSpeakerEnable(e){return __awaiter(this,void 0,void 0,(function*(){yield this.bmStreamVm.muteSpeaker(e).catch((e=>Promise.reject(e)))}))}_attachEvents(){this.observes=attachEvents(this.boomCore,this.userVM,this.bmStreamVm,this.chatVM,this)}createSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter(this,void 0,void 0,(function*(){const s={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId,sourceType:"camera"};e.videoSource&&(s.videoSource=e.videoSource),e.audioSource&&(s.audioSource=e.audioSource),s.echoCancellation=!0,s.noiseSuppression=!0,s.autoGainControl=!0,this.voiceMode&&(s.audioHint=this.voiceMode,s.noiseSuppression=!1);const o=yield this.boomCore.createLocalStream(s,t).catch((t=>(error$1("create brtc stream error","","",[JSON.stringify(t),null==t?void 0:t.message]),Promise.reject(pr$1(e.video?"摄像头":"麦克风")))));e.video&&("720p"===this.videoProfile?o.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):o.setVideoProfile(this.videoProfile));try{yield o.init()}catch(t){if(error$1("brtc init stream failed","","",[null==t?void 0:t.message]),String(t).includes("Permission denied by system")){if(e.video)return Promise.reject(Er$1());if(e.audio)return Promise.reject(Sr$1())}else{if(String(t).includes("Could not start video source"))return Promise.reject(gr$1());if(String(t).includes("Could not start audio source"))return Promise.reject(Tr$1())}return Promise.reject(ar(e.video?"摄像头":"麦克风"))}return o}))}createPBSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter(this,void 0,void 0,(function*(){const s={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId,sourceType:"camera",echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};this.voiceMode&&(s.audioHint=this.voiceMode,s.noiseSuppression=!1);const o=yield this.boomCore.createPBLocalStream(s,t).catch((e=>Promise.reject(e)));return"720p"===this.videoProfile?o.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):o.setVideoProfile(this.videoProfile),yield o.init(),o}))}subscribe(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.boomCore.subscribe(e,t)}))}unsubscribe(e){return this.boomCore.unsubscribe(e).catch((e=>Promise.reject(e)))}publish(e){return new Promise(((t,r)=>{this.boomCore.publish(e).then((()=>{info("brtc stream publish success"),t(!0)})).catch((()=>__awaiter(this,void 0,void 0,(function*(){this.pubFailedNum<=3?(this.pubFailedNum+=1,this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedTimer=setTimeout((()=>(error$1(`local publish stream failed, retry failed num: ${this.pubFailedNum}`),this.publish(e).then(t).catch(r))),3e3)):(error$1("retry publish local stream failed, ubpublish now"),yield this.bmStreamVm.unpublishStream(),r(!1))}))))}))}unpublish(e){return this.boomCore.unpublish(e).catch((e=>Promise.reject(e)))}getUser(e){return this.userVM.getUser(e)}changeMaster(e,t=!1){var r;return __awaiter(this,void 0,void 0,(function*(){return null===(r=this.roomVM)||void 0===r?void 0:r.changeMaster(e,t).catch((e=>e))}))}updateManager(e,t,r=!0){return __awaiter(this,void 0,void 0,(function*(){return this.roomVM.updateManager(e,t,r).catch((e=>e))}))}getMaster(){return this.boomCore.getMaster()}getCreator(){return this.boomCore.getCreator()}getName(){return this.boomCore.getName()}evictUser(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.evictUser(e,t).catch((e=>e))}))}updateUser(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){null===(r=this.roomVM)||void 0===r||r.updateUser(e,t).catch((e=>e))}))}getMsgSeq(){return this.boomCore.getMsgSeq()}getLimits(){return this.boomCore.getLimits()}getSwitch(){return this.boomCore.getSwitch()}syncRoom(){return this.boomCore.syncRoom()}update(e){return this.boomCore.update(e)}getUsers(){return this.userVM.userList}getTotalUsers(){return this.userVM.userList.size}sendMessage(e,t){return this.boomCore.sendMessage(e,t)}customMessage(e,t){return this.boomCore.customMessage(e,t)}getMessages(e,t){return this.boomCore.getMessages(e,t)}getLocalParticipant(){var e;let t=null===(e=this.userVM)||void 0===e?void 0:e.getLocalUser();return t||(t=this.localUser),t}getAudioOff(){return this.boomCore.getAudioOff()}getSelfOpenAudio(){return this.boomCore.getSelfOpenAudio()}getVideoOff(){return this.boomCore.getVideoOff()}getMsgOff(){return this.boomCore.getMsgOff()}getLock(){return this.boomCore.getLock()}getRoomInfo(){return this.roomInfo}setAudioOff(e,t){return __awaiter(this,void 0,void 0,(function*(){return yield this.boomCore.setAudioOff(e,t).catch((e=>Promise.reject(er(`boomCore.setAudioOff error ${JSON.stringify(e)}`))))}))}updateRoom(e){return __awaiter(this,void 0,void 0,(function*(){return this.boomCore.client.update(e)}))}setVideoOff(e){return this.boomCore.setVideoOff(e).catch((e=>Promise.reject(nr$1(`boomCore.setVideoOff error ${JSON.stringify(e)}`))))}setMsgOff(e){return this.boomCore.setMsgOff(e).catch((e=>Promise.reject(rr(`boomCore.setMsgOff error ${JSON.stringify(e)}`))))}setSwitch(e){return this.boomCore.setSwitch(e)}setLock(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.boomCore.setLock(e),this.boomCore.getLock()}))}sendChatMessage(e,t,r){if(!this.chatVM)throw new BoomError(INVALID_OPERATION,"未初始化chatVM, 无法发送聊天信息");return this.chatVM.sendMessage(e,t,r)}getChatMessage(){if(!this.chatVM)throw new BoomError(INVALID_OPERATION,"未初始化chatVM, 无法获取聊天室消息");return this.chatVM.messageList}getHistoryMessage(){return __awaiter(this,void 0,void 0,(function*(){return this.chatVM.getHistoryMessage()}))}updateCustomStats(e){return info("updateCustomStats","","",[JSON.stringify(e)]),this.boomCore.updateCustomStats(Object.assign(Object.assign({},e),{pos:"web"})).catch((e=>Promise.reject(or(`.boomCore.updateCustomStats ${JSON.stringify(e)}`))))}getCustomStats(){return this.boomCore.getCustomStats()}getDuration(){return this.boomCore.getDuration()}checkUserHasMaster(e){return this.userVM.checkUserHasMaster(e)}changeNickName(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.changeNickName(e,t)}))}streamModelExits(e){const t=e.userId;return e.isShare?this.bmStreamVm.shareStreamModels.has(t):this.bmStreamVm.streamModels.has(t)}handleStreamTask(e,t=!1){return __awaiter(this,void 0,void 0,(function*(){this.streamModelExits(e)?e.stream?1===this.conferenceMode?(yield this.handlePull(e),yield this.handlePlay(e,t),yield this.handleChangeStreamType(e)):(yield this.bmLiveVM.handlePull(e),yield this.bmLiveVM.handleChangeStreamType(e),yield this.bmLiveVM.handlePlay(e,t)):((e.isDisplay||e.isInBig)&&e.bloudStream||e.audioEnable)&&(yield this.addUser2Queue({id:e.userId,isScreen:e.isShare,isWeb:e.isWeb})):warn(`streamModel is not exits, userId: ${e.userId}, isShare: ${e.isShare}, ignore`)}))}handlePull(e){var t;return __awaiter(this,void 0,void 0,(function*(){e.isLocal||(e.isMixer&&(yield this.handleSubscribeSteam(e)),(e.isDisplay!==e.isCurrentDisplay||e.isInBig&&e.pulledStreamType!==e.pulledStreamGoal||!e.hasPulled)&&(e.isCurrentDisplay=e.isDisplay,e.checkCount=0,e.isDisplay||e.isInBig||!e.isDisplay&&(e.audioEnable||(null===(t=e.stream)||void 0===t?void 0:t.getAudioOn()))?yield this.handleSubscribeSteam(e):yield this.handleUnsubscribeStream(e)))}))}manualSubscribeStreamModel(e){streamPullQueue.addQueue(this.handleStreamTask.bind(this,e),e.streamId,0,e.nickname)}handleUnsubscribe(e){streamPullQueue.addQueue(this.handleUnsubscribeStream.bind(this,e),e.streamId,0,e.nickname)}handleStreamBindElement(e){streamPullQueue.addQueue(this.handlePlay.bind(this,e,!1,!1),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleStreamBindBigElement(e){streamPullQueue.addQueue(this.handlePlayInBIg.bind(this,e),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleUnsubscribeStream(e){var t,r,i;return __awaiter(this,void 0,void 0,(function*(){if(e.stream&&((null===(r=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===r?void 0:r.call(t))||e.hasPulled)){e.hasPulled=!1,e.pulledStreamType="small",e.isInBig=!1;try{null===(i=e.stream)||void 0===i||i.stop()}catch(e){}yield this.unsubscribe(e.stream).then((()=>{var t,r;e.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(e.stream)),e.isSubScribedWatcher.next(!1),info("取消订阅流成功","",e.userId,[e.nickname,e.isDisplay,e.isCurrentDisplay,null===(r=e.stream)||void 0===r?void 0:r.getStreamId()])})).catch((()=>{error$1("unsubscribe error")}))}}))}handleSubscribeSteam(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){try{e.hasPulled&&e.stream.isSubscribed()?e.isDisplay?null===(t=e.stream)||void 0===t||t.unmuteVideo().then((()=>{info("stream unmute video success","unmute-video",e.userId,["streamId => ",e.streamId])})):null===(r=e.stream)||void 0===r||r.muteVideo().then((()=>{info("stream mute video success","mute-video",e.userId,["streamId => ",e.streamId])})):(info("开始订阅","订阅",e.userId,[e.streamId]),e.hasPulled=!0,yield this.subscribe(e.stream,subscribeOptions).then((()=>{var t,r;info("订阅流结束","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId,"display =>",e.isDisplay]),e.isDisplay||null===(t=e.stream)||void 0===t||t.muteVideo(),e.stream&&e.audioEnable&&(null===(r=this.audioPlayer)||void 0===r||r.addStream(e.stream,!0)),e.pullFailedNum=0,e.isSubScribedWatcher.next(!0),this.bmStreamVm.addToRecorder(e.stream),e.isDisplay&&e.videoEnable&&checkStreamIsNormal(e)})).catch((t=>{var r,i;if(error$1("订阅流失败","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId," error => ",JSON.stringify(t)]),e.hasPulled=!1,e.pulledStreamType="small",e.pullFailedNum+=1,null===(r=e.player)||void 0===r||r.destroy(),e.pullFailedNum<=3)this.handlePulledFailed(e);else{e.pullFailedNum=0;const r=e.isShare;try{null===(i=e.stream)||void 0===i||i.destroy()}catch(t){}e.updateStream(void 0,!1,this.bmStreamVm),info("subscribe stream failed, need to reQuery stream","",e.userId,["streamId =>",e.streamId,"hasStream => ",!!e.stream,"isWeb => ",e.isWeb,"isScreen => ",r,"bloudStreamState =>",JSON.stringify(e.bloudStream)]),e.bloudStream&&this.addUser2Queue({id:e.userId,isWeb:e.isWeb,isScreen:r})}})))}catch(t){e.hasPulled=!1,e.pulledStreamType="small",console.error("订阅流失败","",e.userId,e.nickname,"错误 =>",t)}}))}handleChangeStreamType(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){e.isLocal||e.pulledStreamType!==e.pulledStreamGoal&&(null===(t=e.stream)||void 0===t?void 0:t.isSubscribed())&&((null===(r=e.stream)||void 0===r?void 0:r.isSubscribed())||e.hasPulled)&&(e.pulledStreamType=e.pulledStreamGoal,yield this.boomCore.brtcClient.setRemoteVideoStreamType(e.stream,e.pulledStreamGoal).catch((t=>{error$1("大小流切换失败","",e.userId,["error => ",JSON.stringify(t)])})),info("大小流切换结束","",e.userId,["nickname =>",e.nickname," isInBig => ",e.isInBig," pulledStreamGoal => ",e.pulledStreamGoal,"pulledStreamType => ",e.pulledStreamType]))}))}handlePlay(e,t,r=!0){var i,s,o;return __awaiter(this,void 0,void 0,(function*(){this.streamModelExits(e)&&(e.isLocal?e.isShare||t||(yield e.play(),yield e.playInBig()):e.stream&&(null===(i=e.stream)||void 0===i?void 0:i.isSubscribed())&&(t&&!e.isShare||e.play(),e.stream&&e.audioEnable&&((null===(s=this.audioPlayer)||void 0===s?void 0:s.playMap.has(e.stream))||null===(o=this.audioPlayer)||void 0===o||o.addStream(e.stream)),r&&e.playInBig()))}))}handlePlayInBIg(e){return __awaiter(this,void 0,void 0,(function*(){this.streamModelExits(e)&&(yield e.playInBig())}))}handlePulledFailed(e){const t=e.userId;(e.isShare?this.bmStreamVm.shareStreamModels.has(t):this.bmStreamVm.streamModels.has(t))&&streamPullQueue.addQueue(this.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}handleStreamConnectError(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){const{stream:i,isLocal:s}=e;info("handleStreamConnectError","","",["nickname =>",i.nickname,"streamId => ",i.streamId,"isShare =>",i.isShare,"isLocal => ",s]),i.stream&&(i.stream.stop(),null===(t=this.audioPlayer)||void 0===t||t.removeStream(i.stream)),null===(r=i.player)||void 0===r||r.destroy(),s?i.stream&&(i.isShare?this.bmStreamVm.localShareError.next(br()):this.bmStreamVm.localStreamConnectErrorWatcher.next(Nr$1()),this.netConnecting&&this.networkState.brtc&&this.networkState.bloud?i.isShare?(info("Local share stream has problem, now ,republish"),handleShareStreamFailed(this,this.bmStreamVm)):(info("brtc 网络正常,重新推流"),i.stream&&(yield this.republishLocalStream(i.stream))):(error$1("brtc 网络还没恢复,等恢复了在重新推流 ","",i.userId,["nickname =>",i.nickname,"streamId => ",i.streamId,"isShare =>",i.isShare]),this.streamConnectedErrorQueue.push(e))):this.netConnecting&&this.networkState.brtc?(i.hasPulled=!1,i.pulledStreamType="small",streamPullQueue.addQueue(this.handleQueueTask.bind(this,i),i.streamId,0,i.nickname)):(error$1("brtc 网络还没恢复,等恢复了在重新拉流 ","",i.userId,["nickname =>",i.nickname]),this.streamConnectedErrorQueue.push(e))}))}toggleAudienceSpeaking(e,t){e.permission.setAudio(t),this.updateUser(e.userId,{permission:e.permission.get()})}updateUserIsGuest(e,t){return __awaiter(this,void 0,void 0,(function*(){e.permission.setSubscribe(t),yield this.updateUser(e.userId,{permission:e.permission.get()})}))}managerChangeToGuest(e){this.userVM.managerChangeToGuest(e)}moveUserRoom(e,t=!1,r=!1){return this.boomCore.client.moveUserRoom(e,t,r)}getParticipantNotice(e){this.participantNotice=e}setCustomUrl(e){this.boomCore.setCustomUrl(e)}handleRePushSelf(){var e,t;return __awaiter(this,void 0,void 0,(function*(){const r=null===(t=null===(e=this.getLocalParticipant())||void 0===e?void 0:e.getMainStreamModel())||void 0===t?void 0:t.stream;r&&(yield this.republishLocalStream(r))}))}handleResetOtherStreamStatus(){info("brtc sync-room-completed"),this.audioPlayer.clear(),this.bmStreamVm.streamModels.forEach((e=>{var t;if(!e.isLocal){e.hasPulled=!1,e.pulledStreamType="small";try{e.stream&&e.stream.stop(),null===(t=e.stream)||void 0===t||t.destroy()}catch(e){}e.updateStream(void 0,!1,this.bmStreamVm)}})),this.bmStreamVm.shareStreamModels.forEach((e=>{var t,r;if(!e.isLocal){e.hasPulled=!1,e.pulledStreamType="small";const i=e.getUser();try{null===(t=e.stream)||void 0===t||t.stop(),null===(r=e.stream)||void 0===r||r.destroy()}catch(e){}i.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`)}})),this.bmStreamVm.shareStreamModels.clear(),this.bmStreamVm.shareStreamModelsWatcher.next(Array.from(this.bmStreamVm.shareStreamModels.values())),this.networkState.brtc=!0,setTimeout((()=>{this.brtcNetEnableWatcher.next(!0),this.streamWSReconnectWatcher.next(!0)}),2e3),handleReconnectedStream(this)}addUser2Queue(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(e.force&&this.processUser(new Map([[e.id,e]])),e.isScreen)this.streamQueue.addUsers([e]);else{const r=this.bmStreamVm.streamModels.get(e.id);r&&!r.isLocal&&(r.stream||r&&((null===(t=r.bloudStream)||void 0===t?void 0:t.audio)||r.bloudStream&&r.isDisplay)&&this.streamQueue.addUsers([e]))}}))}queryBrtcStreams(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.boomCore.brtcClient.queryUsers(e)}))}handleAddStreams(e){e.forEach((e=>{if(isShareStream(e)){const t=this.bmStreamVm.shareStreamModels.get(transShareScreen2User(e.getUserId().toString()));(!t||t&&!t.stream)&&((null==t?void 0:t.player)&&t.player.destroy(),this.bmStreamVm.remoteStreamPublished(e))}else{const t=this.bmStreamVm.streamModels.get(e.getUserId().toString());t&&!t.stream&&((null==t?void 0:t.player)&&t.player.destroy(),this.bmStreamVm.remoteStreamPublished(e))}}))}getForceUser(e){return __awaiter(this,void 0,void 0,(function*(){const{users:t}=yield this.boomCore.queryUsers([e]);this.userVM.addBcUsersMap(t,!0),this.userVM.getForceUserWatcher.next(!0)}))}getVersion(){return PackageJson.version}}window.BoomMeeting=BMRoom,window.BoomError=s,window.BOOMLogger=kt$1,exports.Logger=kt$1,exports.default=BMRoom,Object.defineProperty(exports,"__esModule",{value:!0})}));