aliyun-rtc-sdk 7.2.7 → 7.2.8-beta.3

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.
@@ -1,15 +1,15 @@
1
- (function(W,J){typeof exports=="object"&&typeof module!="undefined"?J(exports,require("aliyun-rts-sdk"),require("eventemitter3")):typeof define=="function"&&define.amd?define(["exports","aliyun-rts-sdk","eventemitter3"],J):J((W=typeof globalThis!="undefined"?globalThis:W||self).AliRtcEngine={},W.AliyunRts,W.EventEmitter)})(this,function(W,J,ne){var ht,ii,re,jt,$t,it,z,On;"use strict";var rt=(a=>(a.EnableNonOnePcDefaultJoinMode="h5_enable_non_one_pc_default_join_mode",a))(rt||{}),yt=(a=>(a.prod="rs.rtn.aliyuncs.com",a.pre="prs.rtn.aliyuncs.com",a))(yt||{}),lt=(a=>(a.pre="pre",a.prod="prod",a))(lt||{}),Rt=(a=>(a.AliRtcSdkCommunication="communication",a.AliRtcSdkInteractiveLive="interactive_live",a.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",a))(Rt||{}),mt=(a=>(a.AliRtcSdkInteractive="interactive",a.AliRtcSdkLive="live",a))(mt||{}),ze=(a=>(a[a.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",a[a.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",a[a.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",a[a.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",a[a.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",a[a.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",a[a.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",a))(ze||{}),De=(a=>(a[a.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",a[a.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",a[a.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",a[a.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",a[a.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",a[a.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",a[a.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",a[a.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",a[a.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",a[a.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",a[a.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",a[a.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",a))(De||{}),se=(a=>(a[a.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",a[a.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",a[a.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",a[a.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",a[a.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",a[a.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",a))(se||{}),Et=(a=>(a[a.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",a[a.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",a[a.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",a[a.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",a[a.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",a[a.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",a[a.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",a[a.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",a[a.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",a[a.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",a[a.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",a[a.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",a[a.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",a))(Et||{}),Xi=(a=>(a[a.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",a[a.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",a[a.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",a))(Xi||{}),zt=(a=>(a[a.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",a[a.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",a[a.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",a))(zt||{}),le=(a=>(a[a.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",a[a.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",a[a.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",a[a.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",a))(le||{}),ee=(a=>(a[a.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",a[a.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",a[a.AliRtcStatePublishing=2]="AliRtcStatePublishing",a[a.AliRtcStatePublished=3]="AliRtcStatePublished",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(ee||{}),oe=(a=>(a[a.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",a[a.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",a[a.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",a[a.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(oe||{}),Ke=(a=>(a[a.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",a[a.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",a[a.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",a))(Ke||{}),pi=(a=>(a[a.CAMERA_INVALID=-1]="CAMERA_INVALID",a[a.CAMERA_REAR=0]="CAMERA_REAR",a[a.CAMERA_FRONT=1]="CAMERA_FRONT",a))(pi||{}),Qe=(a=>(a[a.AliRtcNetworkExcellent=0]="AliRtcNetworkExcellent",a[a.AliRtcNetworkGood=1]="AliRtcNetworkGood",a[a.AliRtcNetworkPoor=2]="AliRtcNetworkPoor",a[a.AliRtcNetworkBad=3]="AliRtcNetworkBad",a[a.AliRtcNetworkVeryBad=4]="AliRtcNetworkVeryBad",a[a.AliRtcNetworkDisconnected=5]="AliRtcNetworkDisconnected",a[a.AliRtcNetworkUnknown=6]="AliRtcNetworkUnknown",a))(Qe||{}),Ce=(a=>(a.PullStreamStats="remoteStat",a.RtsSubscribeExceeds="rtsSubscribeExceeds",a.UserJoined="userJoined",a.UserLeft="userLeft",a.Bye="bye",a.MuteAudio="muteAudio",a.UnmuteAudio="unmuteAudio",a.MuteVideo="muteVideo",a.UnmuteVideo="unmuteVideo",a.MuteScreen="muteScreen",a.UnmuteScreen="unmuteScreen",a.Error="error",a))(Ce||{}),Ze=(a=>(a.Local="local-device-status-change",a.Remote="remote-device-status-change",a))(Ze||{}),M=(a=>(a.Audio="sophon_audio",a.VideoLarge="sophon_video_camera_large",a.VideoSmall="sophon_video_camera_small",a.Screen="sophon_video_screen_share",a.Data="sophon_data",a))(M||{}),Yi=(a=>(a.Audio="rts audio",a.VideoLarge="rts video",a))(Yi||{}),Mt=(a=>(a.Add="add",a.Delete="delete",a.Replace="replace",a.Stop="stop",a.UnPublish="unpublish",a))(Mt||{}),mi=(a=>(a[a.Camera=0]="Camera",a[a.Screen=1]="Screen",a[a.Image=2]="Image",a))(mi||{}),Pi=(a=>(a[a.Microphone=0]="Microphone",a[a.Screen=1]="Screen",a[a.Mixed=2]="Mixed",a))(Pi||{}),me=(a=>(a.InRoom="inRoom",a.Join="join",a.Publish="publish",a.User="user",a.Resume="resume",a.Retry="retry",a.Reconnect="reconnect",a))(me||{}),Tt=(a=>(a[a.MANUAL=0]="MANUAL",a[a.JOIN_CHANNEL=1]="JOIN_CHANNEL",a[a.ROLE_CHANGE=2]="ROLE_CHANGE",a[a.RECONNECT=3]="RECONNECT",a))(Tt||{}),B=(a=>(a[a.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",a[a.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",a[a.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",a[a.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",a[a.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",a[a.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",a[a.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",a[a.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",a[a.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",a[a.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",a[a.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",a[a.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",a[a.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",a[a.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",a[a.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",a[a.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",a[a.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",a[a.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",a[a.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",a[a.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",a[a.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",a[a.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",a[a.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",a[a.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",a[a.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",a[a.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",a[a.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",a[a.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",a[a.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",a[a.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",a[a.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",a[a.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",a[a.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",a[a.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",a[a.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",a[a.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",a[a.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",a[a.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",a[a.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",a[a.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",a[a.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",a[a.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",a[a.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",a[a.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",a[a.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",a[a.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",a[a.ERR_INNER=-1]="ERR_INNER",a[a.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",a[a.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",a[a.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",a[a.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",a[a.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",a[a.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",a[a.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",a[a.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",a[a.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",a[a.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",a[a.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",a[a.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",a))(B||{});class V extends Error{constructor(e,t,i){super(t);m(this,"_code");m(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof V?e:new V((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new V(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function es(a){var s;if(((s=a==null?void 0:a.nodeName)==null?void 0:s.toLowerCase())==="video")return a.setAttribute("playsinline",""),a;if(typeof a=="string"){let e=document.getElementById(a);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new V(B.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new V(B.ERR_INVALID_ARGUMENTS,"element not founded")}throw new V(B.ERR_INVALID_ARGUMENTS,"element id should be string")}function Qi(a){var e;const s=[];if(Array.isArray(a))a.forEach(t=>{try{s.push(es(t))}catch(i){}});else if(typeof a=="string"||((e=a==null?void 0:a.nodeName)==null?void 0:e.toLowerCase())==="video")try{s.push(es(a))}catch(t){}return s}function Nt(a){return new Promise(s=>setTimeout(s,a))}function ts(a,s,e=1e3,t=i=>!0){return E(this,null,function*(){let i=0;for(;i<s;)try{return yield a(i)}catch(r){if(i++,i>=s||!t(r))throw r||void 0;yield new Promise(n=>setTimeout(n,e))}})}function Zi(a,s){let e=s;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${a}&ali_prefer_media_server=${e}`:a}function Kt(a,s){var e;try{const{archCfgs:t}=a;if(!t||!Array.isArray(t))return;const i=t.find(r=>r.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[s]:void 0}catch(t){return}}function ai(a,s){try{const{config:e}=a;return e?e==null?void 0:e[s]:void 0}catch(e){return}}function Kn(a){const s=a.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
2
- `);return s.includes(`a=rtcp-rsize\r
3
- `)?s:s.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
4
- `)}function er(a,s){return a>50||s>500?Qe.AliRtcNetworkVeryBad:a>30||s>350?Qe.AliRtcNetworkBad:a>20||s>200?Qe.AliRtcNetworkPoor:a>10||s>100?Qe.AliRtcNetworkGood:a>=0||s>=0?Qe.AliRtcNetworkExcellent:Qe.AliRtcNetworkUnknown}function is(a){return!!a&&[M.VideoLarge,M.VideoSmall,M.Screen].includes(a)}function rs(a){return a===M.Audio}for(var tr,qe=[],ir=0;ir<256;++ir)qe.push((ir+256).toString(16).slice(1));var Jn=new Uint8Array(16);function qn(){if(!tr&&!(tr=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return tr(Jn)}const ss={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function dt(a,s,e){if(ss.randomUUID&&!s&&!a)return ss.randomUUID();var t=(a=a||{}).random||(a.rng||qn)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,s){e=e||0;for(var i=0;i<16;++i)s[e+i]=t[i];return s}return function(r,n=0){return(qe[r[n+0]]+qe[r[n+1]]+qe[r[n+2]]+qe[r[n+3]]+"-"+qe[r[n+4]]+qe[r[n+5]]+"-"+qe[r[n+6]]+qe[r[n+7]]+"-"+qe[r[n+8]]+qe[r[n+9]]+"-"+qe[r[n+10]]+qe[r[n+11]]+qe[r[n+12]]+qe[r[n+13]]+qe[r[n+14]]+qe[r[n+15]]).toLowerCase()}(t)}const gi="7.2.7";class ke{static getVersionNumber(){let s=gi.split("."),e="";return s.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(s){let e=[];if(s)for(let t in s)e.push(t+"="+s[t]);return e.join("&")}static getQueryParams(s){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===s)return decodeURIComponent(i[1])}}static createCallid(s=""){const e=dt();return s&&e&&e.length>s.length?`${s}${e.substring(s.length)}`:e}static checkSubOptionsValid(s){if(s){const{audio:e,video:t,screen:i}=s;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return E(this,null,function*(){const s=yt.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${s}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(s){let e;if(s instanceof Error)e=s.message;else if(typeof s=="string")e=s;else try{e=JSON.stringify(s)}catch(t){e="undefined"}return e}static paramArrayToString(s){let e="";for(let t=0;t<s.length;t++)e!==""&&(e+=" "),e+=ke.toString(s[t]);return e}static removeQueryString(s){if(!s)return s;let e=s.indexOf("?");return e>0?s.substring(0,e):s}}function as(a,s,e){Object.defineProperty(a,s,{writable:!0,enumerable:!0,configurable:!0,value:e})}function ns(a,s,e,t){t?t(()=>{as(a,s,e)}):as(a,s,e)}Array(32);var Di=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Gn(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}function Xn(a){if(a.__esModule)return a;var s=a.default;if(typeof s=="function"){var e=function t(){return this instanceof t?Reflect.construct(s,arguments,this.constructor):s.apply(this,arguments)};e.prototype=s.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(a).forEach(function(t){var i=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return a[t]}})}),e}var os={exports:{}},cs={exports:{}};const Yn=Xn(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var ls;function ge(){return ls||(ls=1,function(a){a.exports=function(){var s=s||function(e,t){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&Di!==void 0&&Di.crypto&&(i=Di.crypto),!i)try{i=Yn}catch(b){}var r=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(b){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(b){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function b(){}return function(v){var R;return b.prototype=v,R=new b,b.prototype=null,R}}(),c={},o=c.lib={},l=o.Base={extend:function(b){var v=n(this);return b&&v.mixIn(b),v.hasOwnProperty("init")&&this.init!==v.init||(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){var b=this.extend();return b.init.apply(b,arguments),b},init:function(){},mixIn:function(b){for(var v in b)b.hasOwnProperty(v)&&(this[v]=b[v]);b.hasOwnProperty("toString")&&(this.toString=b.toString)},clone:function(){return this.init.prototype.extend(this)}},d=o.WordArray=l.extend({init:function(b,v){b=this.words=b||[],this.sigBytes=v!=t?v:4*b.length},toString:function(b){return(b||p).stringify(this)},concat:function(b){var v=this.words,R=b.words,_=this.sigBytes,y=b.sigBytes;if(this.clamp(),_%4)for(var A=0;A<y;A++){var w=R[A>>>2]>>>24-A%4*8&255;v[_+A>>>2]|=w<<24-(_+A)%4*8}else for(var T=0;T<y;T+=4)v[_+T>>>2]=R[T>>>2];return this.sigBytes+=y,this},clamp:function(){var b=this.words,v=this.sigBytes;b[v>>>2]&=4294967295<<32-v%4*8,b.length=e.ceil(v/4)},clone:function(){var b=l.clone.call(this);return b.words=this.words.slice(0),b},random:function(b){for(var v=[],R=0;R<b;R+=4)v.push(r());return new d.init(v,b)}}),u=c.enc={},p=u.Hex={stringify:function(b){for(var v=b.words,R=b.sigBytes,_=[],y=0;y<R;y++){var A=v[y>>>2]>>>24-y%4*8&255;_.push((A>>>4).toString(16)),_.push((15&A).toString(16))}return _.join("")},parse:function(b){for(var v=b.length,R=[],_=0;_<v;_+=2)R[_>>>3]|=parseInt(b.substr(_,2),16)<<24-_%8*4;return new d.init(R,v/2)}},h=u.Latin1={stringify:function(b){for(var v=b.words,R=b.sigBytes,_=[],y=0;y<R;y++){var A=v[y>>>2]>>>24-y%4*8&255;_.push(String.fromCharCode(A))}return _.join("")},parse:function(b){for(var v=b.length,R=[],_=0;_<v;_++)R[_>>>2]|=(255&b.charCodeAt(_))<<24-_%4*8;return new d.init(R,v)}},f=u.Utf8={stringify:function(b){try{return decodeURIComponent(escape(h.stringify(b)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(b){return h.parse(unescape(encodeURIComponent(b)))}},g=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(b){typeof b=="string"&&(b=f.parse(b)),this._data.concat(b),this._nDataBytes+=b.sigBytes},_process:function(b){var v,R=this._data,_=R.words,y=R.sigBytes,A=this.blockSize,w=y/(4*A),T=(w=b?e.ceil(w):e.max((0|w)-this._minBufferSize,0))*A,I=e.min(4*T,y);if(T){for(var P=0;P<T;P+=A)this._doProcessBlock(_,P);v=_.splice(0,T),R.sigBytes-=I}return new d.init(v,I)},clone:function(){var b=l.clone.call(this);return b._data=this._data.clone(),b},_minBufferSize:0});o.Hasher=g.extend({cfg:l.extend(),init:function(b){this.cfg=this.cfg.extend(b),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(b){return this._append(b),this._process(),this},finalize:function(b){return b&&this._append(b),this._doFinalize()},blockSize:16,_createHelper:function(b){return function(v,R){return new b.init(R).finalize(v)}},_createHmacHelper:function(b){return function(v,R){return new S.HMAC.init(b,R).finalize(v)}}});var S=c.algo={};return c}(Math);return s}()}(cs)),cs.exports}var ds,us={exports:{}};function Mi(){return ds||(ds=1,function(a){a.exports=function(s){return i=(t=s).lib,r=i.Base,n=i.WordArray,(c=t.x64={}).Word=r.extend({init:function(o,l){this.high=o,this.low=l}}),c.WordArray=r.extend({init:function(o,l){o=this.words=o||[],this.sigBytes=l!=e?l:8*o.length},toX32:function(){for(var o=this.words,l=o.length,d=[],u=0;u<l;u++){var p=o[u];d.push(p.high),d.push(p.low)}return n.create(d,this.sigBytes)},clone:function(){for(var o=r.clone.call(this),l=o.words=this.words.slice(0),d=l.length,u=0;u<d;u++)l[u]=l[u].clone();return o}}),s;var e,t,i,r,n,c}(ge())}(us)),us.exports}var hs,ps={exports:{}};function Qn(){return hs||(hs=1,function(a){a.exports=function(s){return function(){if(typeof ArrayBuffer=="function"){var e=s.lib.WordArray,t=e.init,i=e.init=function(r){if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),(r instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&r instanceof Uint8ClampedArray||r instanceof Int16Array||r instanceof Uint16Array||r instanceof Int32Array||r instanceof Uint32Array||r instanceof Float32Array||r instanceof Float64Array)&&(r=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),r instanceof Uint8Array){for(var n=r.byteLength,c=[],o=0;o<n;o++)c[o>>>2]|=r[o]<<24-o%4*8;t.call(this,c,n)}else t.apply(this,arguments)};i.prototype=e}}(),s.lib.WordArray}(ge())}(ps)),ps.exports}var ms,gs={exports:{}};function Zn(){return ms||(ms=1,function(a){a.exports=function(s){return function(){var e=s,t=e.lib.WordArray,i=e.enc;function r(n){return n<<8&4278255360|n>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var u=c[d>>>2]>>>16-d%4*8&65535;l.push(String.fromCharCode(u))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=n.charCodeAt(l)<<16-l%2*16;return t.create(o,2*c)}},i.Utf16LE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var u=r(c[d>>>2]>>>16-d%4*8&65535);l.push(String.fromCharCode(u))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=r(n.charCodeAt(l)<<16-l%2*16);return t.create(o,2*c)}}}(),s.enc.Utf16}(ge())}(gs)),gs.exports}var fs,Ss={exports:{}};function Jt(){return fs||(fs=1,function(a){a.exports=function(s){return function(){var e=s,t=e.lib.WordArray;function i(r,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var u=c[r.charCodeAt(d-1)]<<d%4*2|c[r.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=u<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64={stringify:function(r){var n=r.words,c=r.sigBytes,o=this._map;r.clamp();for(var l=[],d=0;d<c;d+=3)for(var u=(n[d>>>2]>>>24-d%4*8&255)<<16|(n[d+1>>>2]>>>24-(d+1)%4*8&255)<<8|n[d+2>>>2]>>>24-(d+2)%4*8&255,p=0;p<4&&d+.75*p<c;p++)l.push(o.charAt(u>>>6*(3-p)&63));var h=o.charAt(64);if(h)for(;l.length%4;)l.push(h);return l.join("")},parse:function(r){var n=r.length,c=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var l=0;l<c.length;l++)o[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var u=r.indexOf(d);u!==-1&&(n=u)}return i(r,n,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),s.enc.Base64}(ge())}(Ss)),Ss.exports}var bs,vs={exports:{}};function eo(){return bs||(bs=1,function(a){a.exports=function(s){return function(){var e=s,t=e.lib.WordArray;function i(r,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var u=c[r.charCodeAt(d-1)]<<d%4*2|c[r.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=u<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64url={stringify:function(r,n){n===void 0&&(n=!0);var c=r.words,o=r.sigBytes,l=n?this._safe_map:this._map;r.clamp();for(var d=[],u=0;u<o;u+=3)for(var p=(c[u>>>2]>>>24-u%4*8&255)<<16|(c[u+1>>>2]>>>24-(u+1)%4*8&255)<<8|c[u+2>>>2]>>>24-(u+2)%4*8&255,h=0;h<4&&u+.75*h<o;h++)d.push(l.charAt(p>>>6*(3-h)&63));var f=l.charAt(64);if(f)for(;d.length%4;)d.push(f);return d.join("")},parse:function(r,n){n===void 0&&(n=!0);var c=r.length,o=n?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<o.length;d++)l[o.charCodeAt(d)]=d}var u=o.charAt(64);if(u){var p=r.indexOf(u);p!==-1&&(c=p)}return i(r,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),s.enc.Base64url}(ge())}(vs)),vs.exports}var ys,Rs={exports:{}};function qt(){return ys||(ys=1,function(a){a.exports=function(s){return function(e){var t=s,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.algo,o=[];(function(){for(var f=0;f<64;f++)o[f]=4294967296*e.abs(e.sin(f+1))|0})();var l=c.MD5=n.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(f,g){for(var S=0;S<16;S++){var b=g+S,v=f[b];f[b]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8)}var R=this._hash.words,_=f[g+0],y=f[g+1],A=f[g+2],w=f[g+3],T=f[g+4],I=f[g+5],P=f[g+6],D=f[g+7],U=f[g+8],q=f[g+9],Y=f[g+10],G=f[g+11],$=f[g+12],Z=f[g+13],te=f[g+14],fe=f[g+15],N=R[0],x=R[1],L=R[2],O=R[3];N=d(N,x,L,O,_,7,o[0]),O=d(O,N,x,L,y,12,o[1]),L=d(L,O,N,x,A,17,o[2]),x=d(x,L,O,N,w,22,o[3]),N=d(N,x,L,O,T,7,o[4]),O=d(O,N,x,L,I,12,o[5]),L=d(L,O,N,x,P,17,o[6]),x=d(x,L,O,N,D,22,o[7]),N=d(N,x,L,O,U,7,o[8]),O=d(O,N,x,L,q,12,o[9]),L=d(L,O,N,x,Y,17,o[10]),x=d(x,L,O,N,G,22,o[11]),N=d(N,x,L,O,$,7,o[12]),O=d(O,N,x,L,Z,12,o[13]),L=d(L,O,N,x,te,17,o[14]),N=u(N,x=d(x,L,O,N,fe,22,o[15]),L,O,y,5,o[16]),O=u(O,N,x,L,P,9,o[17]),L=u(L,O,N,x,G,14,o[18]),x=u(x,L,O,N,_,20,o[19]),N=u(N,x,L,O,I,5,o[20]),O=u(O,N,x,L,Y,9,o[21]),L=u(L,O,N,x,fe,14,o[22]),x=u(x,L,O,N,T,20,o[23]),N=u(N,x,L,O,q,5,o[24]),O=u(O,N,x,L,te,9,o[25]),L=u(L,O,N,x,w,14,o[26]),x=u(x,L,O,N,U,20,o[27]),N=u(N,x,L,O,Z,5,o[28]),O=u(O,N,x,L,A,9,o[29]),L=u(L,O,N,x,D,14,o[30]),N=p(N,x=u(x,L,O,N,$,20,o[31]),L,O,I,4,o[32]),O=p(O,N,x,L,U,11,o[33]),L=p(L,O,N,x,G,16,o[34]),x=p(x,L,O,N,te,23,o[35]),N=p(N,x,L,O,y,4,o[36]),O=p(O,N,x,L,T,11,o[37]),L=p(L,O,N,x,D,16,o[38]),x=p(x,L,O,N,Y,23,o[39]),N=p(N,x,L,O,Z,4,o[40]),O=p(O,N,x,L,_,11,o[41]),L=p(L,O,N,x,w,16,o[42]),x=p(x,L,O,N,P,23,o[43]),N=p(N,x,L,O,q,4,o[44]),O=p(O,N,x,L,$,11,o[45]),L=p(L,O,N,x,fe,16,o[46]),N=h(N,x=p(x,L,O,N,A,23,o[47]),L,O,_,6,o[48]),O=h(O,N,x,L,D,10,o[49]),L=h(L,O,N,x,te,15,o[50]),x=h(x,L,O,N,I,21,o[51]),N=h(N,x,L,O,$,6,o[52]),O=h(O,N,x,L,w,10,o[53]),L=h(L,O,N,x,Y,15,o[54]),x=h(x,L,O,N,y,21,o[55]),N=h(N,x,L,O,U,6,o[56]),O=h(O,N,x,L,fe,10,o[57]),L=h(L,O,N,x,P,15,o[58]),x=h(x,L,O,N,Z,21,o[59]),N=h(N,x,L,O,T,6,o[60]),O=h(O,N,x,L,G,10,o[61]),L=h(L,O,N,x,A,15,o[62]),x=h(x,L,O,N,q,21,o[63]),R[0]=R[0]+N|0,R[1]=R[1]+x|0,R[2]=R[2]+L|0,R[3]=R[3]+O|0},_doFinalize:function(){var f=this._data,g=f.words,S=8*this._nDataBytes,b=8*f.sigBytes;g[b>>>5]|=128<<24-b%32;var v=e.floor(S/4294967296),R=S;g[15+(b+64>>>9<<4)]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),g[14+(b+64>>>9<<4)]=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),f.sigBytes=4*(g.length+1),this._process();for(var _=this._hash,y=_.words,A=0;A<4;A++){var w=y[A];y[A]=16711935&(w<<8|w>>>24)|4278255360&(w<<24|w>>>8)}return _},clone:function(){var f=n.clone.call(this);return f._hash=this._hash.clone(),f}});function d(f,g,S,b,v,R,_){var y=f+(g&S|~g&b)+v+_;return(y<<R|y>>>32-R)+g}function u(f,g,S,b,v,R,_){var y=f+(g&b|S&~b)+v+_;return(y<<R|y>>>32-R)+g}function p(f,g,S,b,v,R,_){var y=f+(g^S^b)+v+_;return(y<<R|y>>>32-R)+g}function h(f,g,S,b,v,R,_){var y=f+(S^(g|~b))+v+_;return(y<<R|y>>>32-R)+g}t.MD5=n._createHelper(l),t.HmacMD5=n._createHmacHelper(l)}(Math),s.MD5}(ge())}(Rs)),Rs.exports}var As,ws={exports:{}};function _s(){return As||(As=1,function(a){a.exports=function(s){return t=(e=s).lib,i=t.WordArray,r=t.Hasher,n=e.algo,c=[],o=n.SHA1=r.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(l,d){for(var u=this._hash.words,p=u[0],h=u[1],f=u[2],g=u[3],S=u[4],b=0;b<80;b++){if(b<16)c[b]=0|l[d+b];else{var v=c[b-3]^c[b-8]^c[b-14]^c[b-16];c[b]=v<<1|v>>>31}var R=(p<<5|p>>>27)+S+c[b];R+=b<20?1518500249+(h&f|~h&g):b<40?1859775393+(h^f^g):b<60?(h&f|h&g|f&g)-1894007588:(h^f^g)-899497514,S=g,g=f,f=h<<30|h>>>2,h=p,p=R}u[0]=u[0]+p|0,u[1]=u[1]+h|0,u[2]=u[2]+f|0,u[3]=u[3]+g|0,u[4]=u[4]+S|0},_doFinalize:function(){var l=this._data,d=l.words,u=8*this._nDataBytes,p=8*l.sigBytes;return d[p>>>5]|=128<<24-p%32,d[14+(p+64>>>9<<4)]=Math.floor(u/4294967296),d[15+(p+64>>>9<<4)]=u,l.sigBytes=4*d.length,this._process(),this._hash},clone:function(){var l=r.clone.call(this);return l._hash=this._hash.clone(),l}}),e.SHA1=r._createHelper(o),e.HmacSHA1=r._createHmacHelper(o),s.SHA1;var e,t,i,r,n,c,o}(ge())}(ws)),ws.exports}var Es,Ts={exports:{}};function rr(){return Es||(Es=1,function(a){a.exports=function(s){return function(e){var t=s,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.algo,o=[],l=[];(function(){function p(S){for(var b=e.sqrt(S),v=2;v<=b;v++)if(!(S%v))return!1;return!0}function h(S){return 4294967296*(S-(0|S))|0}for(var f=2,g=0;g<64;)p(f)&&(g<8&&(o[g]=h(e.pow(f,.5))),l[g]=h(e.pow(f,1/3)),g++),f++})();var d=[],u=c.SHA256=n.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(p,h){for(var f=this._hash.words,g=f[0],S=f[1],b=f[2],v=f[3],R=f[4],_=f[5],y=f[6],A=f[7],w=0;w<64;w++){if(w<16)d[w]=0|p[h+w];else{var T=d[w-15],I=(T<<25|T>>>7)^(T<<14|T>>>18)^T>>>3,P=d[w-2],D=(P<<15|P>>>17)^(P<<13|P>>>19)^P>>>10;d[w]=I+d[w-7]+D+d[w-16]}var U=g&S^g&b^S&b,q=(g<<30|g>>>2)^(g<<19|g>>>13)^(g<<10|g>>>22),Y=A+((R<<26|R>>>6)^(R<<21|R>>>11)^(R<<7|R>>>25))+(R&_^~R&y)+l[w]+d[w];A=y,y=_,_=R,R=v+Y|0,v=b,b=S,S=g,g=Y+(q+U)|0}f[0]=f[0]+g|0,f[1]=f[1]+S|0,f[2]=f[2]+b|0,f[3]=f[3]+v|0,f[4]=f[4]+R|0,f[5]=f[5]+_|0,f[6]=f[6]+y|0,f[7]=f[7]+A|0},_doFinalize:function(){var p=this._data,h=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return h[g>>>5]|=128<<24-g%32,h[14+(g+64>>>9<<4)]=e.floor(f/4294967296),h[15+(g+64>>>9<<4)]=f,p.sigBytes=4*h.length,this._process(),this._hash},clone:function(){var p=n.clone.call(this);return p._hash=this._hash.clone(),p}});t.SHA256=n._createHelper(u),t.HmacSHA256=n._createHmacHelper(u)}(Math),s.SHA256}(ge())}(Ts)),Ts.exports}var Is,to={exports:{}},Cs,ks={exports:{}};function Ps(){return Cs||(Cs=1,function(a){a.exports=function(s){return function(){var e=s,t=e.lib.Hasher,i=e.x64,r=i.Word,n=i.WordArray,c=e.algo;function o(){return r.create.apply(r,arguments)}var l=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],d=[];(function(){for(var p=0;p<80;p++)d[p]=o()})();var u=c.SHA512=t.extend({_doReset:function(){this._hash=new n.init([new r.init(1779033703,4089235720),new r.init(3144134277,2227873595),new r.init(1013904242,4271175723),new r.init(2773480762,1595750129),new r.init(1359893119,2917565137),new r.init(2600822924,725511199),new r.init(528734635,4215389547),new r.init(1541459225,327033209)])},_doProcessBlock:function(p,h){for(var f=this._hash.words,g=f[0],S=f[1],b=f[2],v=f[3],R=f[4],_=f[5],y=f[6],A=f[7],w=g.high,T=g.low,I=S.high,P=S.low,D=b.high,U=b.low,q=v.high,Y=v.low,G=R.high,$=R.low,Z=_.high,te=_.low,fe=y.high,N=y.low,x=A.high,L=A.low,O=w,ue=T,Me=I,K=P,Se=D,Le=U,_e=q,Pe=Y,be=G,Ee=$,he=Z,Ne=te,Re=fe,Ge=N,ot=x,ce=L,ae=0;ae<80;ae++){var ie,ve,Ue=d[ae];if(ae<16)ve=Ue.high=0|p[h+2*ae],ie=Ue.low=0|p[h+2*ae+1];else{var pe=d[ae-15],We=pe.high,Q=pe.low,xe=(We>>>1|Q<<31)^(We>>>8|Q<<24)^We>>>7,ct=(Q>>>1|We<<31)^(Q>>>8|We<<24)^(Q>>>7|We<<25),Oe=d[ae-2],wt=Oe.high,Dt=Oe.low,_t=(wt>>>19|Dt<<13)^(wt<<3|Dt>>>29)^wt>>>6,Wt=(Dt>>>19|wt<<13)^(Dt<<3|wt>>>29)^(Dt>>>6|wt<<26),Ci=d[ae-7],qi=Ci.high,rl=Ci.low,Vn=d[ae-16],sl=Vn.high,Un=Vn.low;ve=(ve=(ve=xe+qi+((ie=ct+rl)>>>0<ct>>>0?1:0))+_t+((ie+=Wt)>>>0<Wt>>>0?1:0))+sl+((ie+=Un)>>>0<Un>>>0?1:0),Ue.high=ve,Ue.low=ie}var si,al=be&he^~be&Re,Bn=Ee&Ne^~Ee&Ge,nl=O&Me^O&Se^Me&Se,ol=ue&K^ue&Le^K&Le,cl=(O>>>28|ue<<4)^(O<<30|ue>>>2)^(O<<25|ue>>>7),Hn=(ue>>>28|O<<4)^(ue<<30|O>>>2)^(ue<<25|O>>>7),ll=(be>>>14|Ee<<18)^(be>>>18|Ee<<14)^(be<<23|Ee>>>9),dl=(Ee>>>14|be<<18)^(Ee>>>18|be<<14)^(Ee<<23|be>>>9),Fn=l[ae],ul=Fn.high,jn=Fn.low,ki=ot+ll+((si=ce+dl)>>>0<ce>>>0?1:0),$n=Hn+ol;ot=Re,ce=Ge,Re=he,Ge=Ne,he=be,Ne=Ee,be=_e+(ki=(ki=(ki=ki+al+((si+=Bn)>>>0<Bn>>>0?1:0))+ul+((si+=jn)>>>0<jn>>>0?1:0))+ve+((si+=ie)>>>0<ie>>>0?1:0))+((Ee=Pe+si|0)>>>0<Pe>>>0?1:0)|0,_e=Se,Pe=Le,Se=Me,Le=K,Me=O,K=ue,O=ki+(cl+nl+($n>>>0<Hn>>>0?1:0))+((ue=si+$n|0)>>>0<si>>>0?1:0)|0}T=g.low=T+ue,g.high=w+O+(T>>>0<ue>>>0?1:0),P=S.low=P+K,S.high=I+Me+(P>>>0<K>>>0?1:0),U=b.low=U+Le,b.high=D+Se+(U>>>0<Le>>>0?1:0),Y=v.low=Y+Pe,v.high=q+_e+(Y>>>0<Pe>>>0?1:0),$=R.low=$+Ee,R.high=G+be+($>>>0<Ee>>>0?1:0),te=_.low=te+Ne,_.high=Z+he+(te>>>0<Ne>>>0?1:0),N=y.low=N+Ge,y.high=fe+Re+(N>>>0<Ge>>>0?1:0),L=A.low=L+ce,A.high=x+ot+(L>>>0<ce>>>0?1:0)},_doFinalize:function(){var p=this._data,h=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return h[g>>>5]|=128<<24-g%32,h[30+(g+128>>>10<<5)]=Math.floor(f/4294967296),h[31+(g+128>>>10<<5)]=f,p.sigBytes=4*h.length,this._process(),this._hash.toX32()},clone:function(){var p=t.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:32});e.SHA512=t._createHelper(u),e.HmacSHA512=t._createHmacHelper(u)}(),s.SHA512}(ge(),Mi())}(ks)),ks.exports}var Ds,io={exports:{}},Ms,Ns={exports:{}};function ro(){return Ms||(Ms=1,function(a){a.exports=function(s){return function(e){var t=s,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.x64.Word,o=t.algo,l=[],d=[],u=[];(function(){for(var f=1,g=0,S=0;S<24;S++){l[f+5*g]=(S+1)*(S+2)/2%64;var b=(2*f+3*g)%5;f=g%5,g=b}for(f=0;f<5;f++)for(g=0;g<5;g++)d[f+5*g]=g+(2*f+3*g)%5*5;for(var v=1,R=0;R<24;R++){for(var _=0,y=0,A=0;A<7;A++){if(1&v){var w=(1<<A)-1;w<32?y^=1<<w:_^=1<<w-32}128&v?v=v<<1^113:v<<=1}u[R]=c.create(_,y)}})();var p=[];(function(){for(var f=0;f<25;f++)p[f]=c.create()})();var h=o.SHA3=n.extend({cfg:n.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],g=0;g<25;g++)f[g]=new c.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,g){for(var S=this._state,b=this.blockSize/2,v=0;v<b;v++){var R=f[g+2*v],_=f[g+2*v+1];R=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),_=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8),(L=S[v]).high^=_,L.low^=R}for(var y=0;y<24;y++){for(var A=0;A<5;A++){for(var w=0,T=0,I=0;I<5;I++)w^=(L=S[A+5*I]).high,T^=L.low;var P=p[A];P.high=w,P.low=T}for(A=0;A<5;A++){var D=p[(A+4)%5],U=p[(A+1)%5],q=U.high,Y=U.low;for(w=D.high^(q<<1|Y>>>31),T=D.low^(Y<<1|q>>>31),I=0;I<5;I++)(L=S[A+5*I]).high^=w,L.low^=T}for(var G=1;G<25;G++){var $=(L=S[G]).high,Z=L.low,te=l[G];te<32?(w=$<<te|Z>>>32-te,T=Z<<te|$>>>32-te):(w=Z<<te-32|$>>>64-te,T=$<<te-32|Z>>>64-te);var fe=p[d[G]];fe.high=w,fe.low=T}var N=p[0],x=S[0];for(N.high=x.high,N.low=x.low,A=0;A<5;A++)for(I=0;I<5;I++){var L=S[G=A+5*I],O=p[G],ue=p[(A+1)%5+5*I],Me=p[(A+2)%5+5*I];L.high=O.high^~ue.high&Me.high,L.low=O.low^~ue.low&Me.low}L=S[0];var K=u[y];L.high^=K.high,L.low^=K.low}},_doFinalize:function(){var f=this._data,g=f.words;this._nDataBytes;var S=8*f.sigBytes,b=32*this.blockSize;g[S>>>5]|=1<<24-S%32,g[(e.ceil((S+1)/b)*b>>>5)-1]|=128,f.sigBytes=4*g.length,this._process();for(var v=this._state,R=this.cfg.outputLength/8,_=R/8,y=[],A=0;A<_;A++){var w=v[A],T=w.high,I=w.low;T=16711935&(T<<8|T>>>24)|4278255360&(T<<24|T>>>8),I=16711935&(I<<8|I>>>24)|4278255360&(I<<24|I>>>8),y.push(I),y.push(T)}return new r.init(y,R)},clone:function(){for(var f=n.clone.call(this),g=f._state=this._state.slice(0),S=0;S<25;S++)g[S]=g[S].clone();return f}});t.SHA3=n._createHelper(h),t.HmacSHA3=n._createHmacHelper(h)}(Math),s.SHA3}(ge(),Mi())}(Ns)),Ns.exports}var Ls,so={exports:{}},xs,Os={exports:{}};function sr(){return xs||(xs=1,function(a){a.exports=function(s){var e,t,i;t=(e=s).lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(r,n){r=this._hasher=new r.init,typeof n=="string"&&(n=i.parse(n));var c=r.blockSize,o=4*c;n.sigBytes>o&&(n=r.finalize(n)),n.clamp();for(var l=this._oKey=n.clone(),d=this._iKey=n.clone(),u=l.words,p=d.words,h=0;h<c;h++)u[h]^=1549556828,p[h]^=909522486;l.sigBytes=d.sigBytes=o,this.reset()},reset:function(){var r=this._hasher;r.reset(),r.update(this._iKey)},update:function(r){return this._hasher.update(r),this},finalize:function(r){var n=this._hasher,c=n.finalize(r);return n.reset(),n.finalize(this._oKey.clone().concat(c))}})}(ge())}(Os)),Os.exports}var Vs,ao={exports:{}},Us,Bs={exports:{}};function Vt(){return Us||(Us=1,function(a){a.exports=function(s){return t=(e=s).lib,i=t.Base,r=t.WordArray,n=e.algo,c=n.MD5,o=n.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:c,iterations:1}),init:function(l){this.cfg=this.cfg.extend(l)},compute:function(l,d){for(var u,p=this.cfg,h=p.hasher.create(),f=r.create(),g=f.words,S=p.keySize,b=p.iterations;g.length<S;){u&&h.update(u),u=h.update(l).finalize(d),h.reset();for(var v=1;v<b;v++)u=h.finalize(u),h.reset();f.concat(u)}return f.sigBytes=4*S,f}}),e.EvpKDF=function(l,d,u){return o.create(u).compute(l,d)},s.EvpKDF;var e,t,i,r,n,c,o}(ge(),_s(),sr())}(Bs)),Bs.exports}var Hs,Fs={exports:{}};function Je(){return Hs||(Hs=1,function(a){a.exports=function(s){s.lib.Cipher||function(e){var t=s,i=t.lib,r=i.Base,n=i.WordArray,c=i.BufferedBlockAlgorithm,o=t.enc;o.Utf8;var l=o.Base64,d=t.algo.EvpKDF,u=i.Cipher=c.extend({cfg:r.extend(),createEncryptor:function(y,A){return this.create(this._ENC_XFORM_MODE,y,A)},createDecryptor:function(y,A){return this.create(this._DEC_XFORM_MODE,y,A)},init:function(y,A,w){this.cfg=this.cfg.extend(w),this._xformMode=y,this._key=A,this.reset()},reset:function(){c.reset.call(this),this._doReset()},process:function(y){return this._append(y),this._process()},finalize:function(y){return y&&this._append(y),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function y(A){return typeof A=="string"?_:v}return function(A){return{encrypt:function(w,T,I){return y(T).encrypt(A,w,T,I)},decrypt:function(w,T,I){return y(T).decrypt(A,w,T,I)}}}}()});i.StreamCipher=u.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var p=t.mode={},h=i.BlockCipherMode=r.extend({createEncryptor:function(y,A){return this.Encryptor.create(y,A)},createDecryptor:function(y,A){return this.Decryptor.create(y,A)},init:function(y,A){this._cipher=y,this._iv=A}}),f=p.CBC=function(){var y=h.extend();function A(w,T,I){var P,D=this._iv;D?(P=D,this._iv=e):P=this._prevBlock;for(var U=0;U<I;U++)w[T+U]^=P[U]}return y.Encryptor=y.extend({processBlock:function(w,T){var I=this._cipher,P=I.blockSize;A.call(this,w,T,P),I.encryptBlock(w,T),this._prevBlock=w.slice(T,T+P)}}),y.Decryptor=y.extend({processBlock:function(w,T){var I=this._cipher,P=I.blockSize,D=w.slice(T,T+P);I.decryptBlock(w,T),A.call(this,w,T,P),this._prevBlock=D}}),y}(),g=(t.pad={}).Pkcs7={pad:function(y,A){for(var w=4*A,T=w-y.sigBytes%w,I=T<<24|T<<16|T<<8|T,P=[],D=0;D<T;D+=4)P.push(I);var U=n.create(P,T);y.concat(U)},unpad:function(y){var A=255&y.words[y.sigBytes-1>>>2];y.sigBytes-=A}};i.BlockCipher=u.extend({cfg:u.cfg.extend({mode:f,padding:g}),reset:function(){var y;u.reset.call(this);var A=this.cfg,w=A.iv,T=A.mode;this._xformMode==this._ENC_XFORM_MODE?y=T.createEncryptor:(y=T.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==y?this._mode.init(this,w&&w.words):(this._mode=y.call(T,this,w&&w.words),this._mode.__creator=y)},_doProcessBlock:function(y,A){this._mode.processBlock(y,A)},_doFinalize:function(){var y,A=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(A.pad(this._data,this.blockSize),y=this._process(!0)):(y=this._process(!0),A.unpad(y)),y},blockSize:4});var S=i.CipherParams=r.extend({init:function(y){this.mixIn(y)},toString:function(y){return(y||this.formatter).stringify(this)}}),b=(t.format={}).OpenSSL={stringify:function(y){var A=y.ciphertext,w=y.salt;return(w?n.create([1398893684,1701076831]).concat(w).concat(A):A).toString(l)},parse:function(y){var A,w=l.parse(y),T=w.words;return T[0]==1398893684&&T[1]==1701076831&&(A=n.create(T.slice(2,4)),T.splice(0,4),w.sigBytes-=16),S.create({ciphertext:w,salt:A})}},v=i.SerializableCipher=r.extend({cfg:r.extend({format:b}),encrypt:function(y,A,w,T){T=this.cfg.extend(T);var I=y.createEncryptor(w,T),P=I.finalize(A),D=I.cfg;return S.create({ciphertext:P,key:w,iv:D.iv,algorithm:y,mode:D.mode,padding:D.padding,blockSize:y.blockSize,formatter:T.format})},decrypt:function(y,A,w,T){return T=this.cfg.extend(T),A=this._parse(A,T.format),y.createDecryptor(w,T).finalize(A.ciphertext)},_parse:function(y,A){return typeof y=="string"?A.parse(y,this):y}}),R=(t.kdf={}).OpenSSL={execute:function(y,A,w,T,I){if(T||(T=n.random(8)),I)P=d.create({keySize:A+w,hasher:I}).compute(y,T);else var P=d.create({keySize:A+w}).compute(y,T);var D=n.create(P.words.slice(A),4*w);return P.sigBytes=4*A,S.create({key:P,iv:D,salt:T})}},_=i.PasswordBasedCipher=v.extend({cfg:v.cfg.extend({kdf:R}),encrypt:function(y,A,w,T){var I=(T=this.cfg.extend(T)).kdf.execute(w,y.keySize,y.ivSize,T.salt,T.hasher);T.iv=I.iv;var P=v.encrypt.call(this,y,A,I.key,T);return P.mixIn(I),P},decrypt:function(y,A,w,T){T=this.cfg.extend(T),A=this._parse(A,T.format);var I=T.kdf.execute(w,y.keySize,y.ivSize,A.salt,T.hasher);return T.iv=I.iv,v.decrypt.call(this,y,A,I.key,T)}})}()}(ge(),Vt())}(Fs)),Fs.exports}var js,$s={exports:{}};function no(){return js||(js=1,function(a){a.exports=function(s){return s.mode.CFB=function(){var e=s.lib.BlockCipherMode.extend();function t(i,r,n,c){var o,l=this._iv;l?(o=l.slice(0),this._iv=void 0):o=this._prevBlock,c.encryptBlock(o,0);for(var d=0;d<n;d++)i[r+d]^=o[d]}return e.Encryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize;t.call(this,i,r,c,n),this._prevBlock=i.slice(r,r+c)}}),e.Decryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize,o=i.slice(r,r+c);t.call(this,i,r,c,n),this._prevBlock=o}}),e}(),s.mode.CFB}(ge(),Je())}($s)),$s.exports}var Ws,zs={exports:{}};function oo(){return Ws||(Ws=1,function(a){a.exports=function(s){return s.mode.CTR=(e=s.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._counter;o&&(l=this._counter=o.slice(0),this._iv=void 0);var d=l.slice(0);n.encryptBlock(d,0),l[c-1]=l[c-1]+1|0;for(var u=0;u<c;u++)i[r+u]^=d[u]}}),e.Decryptor=t,e),s.mode.CTR;var e,t}(ge(),Je())}(zs)),zs.exports}var Ks,Js={exports:{}};function co(){return Ks||(Ks=1,function(a){a.exports=function(s){return s.mode.CTRGladman=function(){var e=s.lib.BlockCipherMode.extend();function t(n){if(255&~(n>>24))n+=1<<24;else{var c=n>>16&255,o=n>>8&255,l=255&n;c===255?(c=0,o===255?(o=0,l===255?l=0:++l):++o):++c,n=0,n+=c<<16,n+=o<<8,n+=l}return n}function i(n){return(n[0]=t(n[0]))===0&&(n[1]=t(n[1])),n}var r=e.Encryptor=e.extend({processBlock:function(n,c){var o=this._cipher,l=o.blockSize,d=this._iv,u=this._counter;d&&(u=this._counter=d.slice(0),this._iv=void 0),i(u);var p=u.slice(0);o.encryptBlock(p,0);for(var h=0;h<l;h++)n[c+h]^=p[h]}});return e.Decryptor=r,e}(),s.mode.CTRGladman}(ge(),Je())}(Js)),Js.exports}var qs,Gs={exports:{}};function lo(){return qs||(qs=1,function(a){a.exports=function(s){return s.mode.OFB=(e=s.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._keystream;o&&(l=this._keystream=o.slice(0),this._iv=void 0),n.encryptBlock(l,0);for(var d=0;d<c;d++)i[r+d]^=l[d]}}),e.Decryptor=t,e),s.mode.OFB;var e,t}(ge(),Je())}(Gs)),Gs.exports}var Xs,uo={exports:{}},Ys,ho={exports:{}},Qs,po={exports:{}},Zs,mo={exports:{}},ea,go={exports:{}},ta,fo={exports:{}},ia,So={exports:{}},ra,bo={exports:{}},sa,aa={exports:{}};function vo(){return sa||(sa=1,function(a){a.exports=function(s){return function(){var e=s,t=e.lib,i=t.WordArray,r=t.BlockCipher,n=e.algo,c=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],l=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],u=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],p=n.DES=r.extend({_doReset:function(){for(var S=this._key.words,b=[],v=0;v<56;v++){var R=c[v]-1;b[v]=S[R>>>5]>>>31-R%32&1}for(var _=this._subKeys=[],y=0;y<16;y++){var A=_[y]=[],w=l[y];for(v=0;v<24;v++)A[v/6|0]|=b[(o[v]-1+w)%28]<<31-v%6,A[4+(v/6|0)]|=b[28+(o[v+24]-1+w)%28]<<31-v%6;for(A[0]=A[0]<<1|A[0]>>>31,v=1;v<7;v++)A[v]=A[v]>>>4*(v-1)+3;A[7]=A[7]<<5|A[7]>>>27}var T=this._invSubKeys=[];for(v=0;v<16;v++)T[v]=_[15-v]},encryptBlock:function(S,b){this._doCryptBlock(S,b,this._subKeys)},decryptBlock:function(S,b){this._doCryptBlock(S,b,this._invSubKeys)},_doCryptBlock:function(S,b,v){this._lBlock=S[b],this._rBlock=S[b+1],h.call(this,4,252645135),h.call(this,16,65535),f.call(this,2,858993459),f.call(this,8,16711935),h.call(this,1,1431655765);for(var R=0;R<16;R++){for(var _=v[R],y=this._lBlock,A=this._rBlock,w=0,T=0;T<8;T++)w|=d[T][((A^_[T])&u[T])>>>0];this._lBlock=A,this._rBlock=y^w}var I=this._lBlock;this._lBlock=this._rBlock,this._rBlock=I,h.call(this,1,1431655765),f.call(this,8,16711935),f.call(this,2,858993459),h.call(this,16,65535),h.call(this,4,252645135),S[b]=this._lBlock,S[b+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function h(S,b){var v=(this._lBlock>>>S^this._rBlock)&b;this._rBlock^=v,this._lBlock^=v<<S}function f(S,b){var v=(this._rBlock>>>S^this._lBlock)&b;this._lBlock^=v,this._rBlock^=v<<S}e.DES=r._createHelper(p);var g=n.TripleDES=r.extend({_doReset:function(){var S=this._key.words;if(S.length!==2&&S.length!==4&&S.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var b=S.slice(0,2),v=S.length<4?S.slice(0,2):S.slice(2,4),R=S.length<6?S.slice(0,2):S.slice(4,6);this._des1=p.createEncryptor(i.create(b)),this._des2=p.createEncryptor(i.create(v)),this._des3=p.createEncryptor(i.create(R))},encryptBlock:function(S,b){this._des1.encryptBlock(S,b),this._des2.decryptBlock(S,b),this._des3.encryptBlock(S,b)},decryptBlock:function(S,b){this._des3.decryptBlock(S,b),this._des2.encryptBlock(S,b),this._des1.decryptBlock(S,b)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=r._createHelper(g)}(),s.TripleDES}(ge(),Jt(),qt(),Vt(),Je())}(aa)),aa.exports}var na,yo={exports:{}},oa,Ro={exports:{}},ca,Ao={exports:{}},la,da={exports:{}};function wo(){return la||(la=1,function(a){a.exports=function(s){return function(){var e=s,t=e.lib.BlockCipher,i=e.algo;const r=16,n=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],c=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function l(f,g){let S=g>>24&255,b=g>>16&255,v=g>>8&255,R=255&g,_=f.sbox[0][S]+f.sbox[1][b];return _^=f.sbox[2][v],_+=f.sbox[3][R],_}function d(f,g,S){let b,v=g,R=S;for(let _=0;_<r;++_)v^=f.pbox[_],R=l(f,v)^R,b=v,v=R,R=b;return b=v,v=R,R=b,R^=f.pbox[r],v^=f.pbox[r+1],{left:v,right:R}}function u(f,g,S){let b,v=g,R=S;for(let _=r+1;_>1;--_)v^=f.pbox[_],R=l(f,v)^R,b=v,v=R,R=b;return b=v,v=R,R=b,R^=f.pbox[1],v^=f.pbox[0],{left:v,right:R}}function p(f,g,S){for(let y=0;y<4;y++){f.sbox[y]=[];for(let A=0;A<256;A++)f.sbox[y][A]=c[y][A]}let b=0;for(let y=0;y<r+2;y++)f.pbox[y]=n[y]^g[b],b++,b>=S&&(b=0);let v=0,R=0,_=0;for(let y=0;y<r+2;y+=2)_=d(f,v,R),v=_.left,R=_.right,f.pbox[y]=v,f.pbox[y+1]=R;for(let y=0;y<4;y++)for(let A=0;A<256;A+=2)_=d(f,v,R),v=_.left,R=_.right,f.sbox[y][A]=v,f.sbox[y][A+1]=R;return!0}var h=i.Blowfish=t.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,g=f.words,S=f.sigBytes/4;p(o,g,S)}},encryptBlock:function(f,g){var S=d(o,f[g],f[g+1]);f[g]=S.left,f[g+1]=S.right},decryptBlock:function(f,g){var S=u(o,f[g],f[g+1]);f[g]=S.left,f[g+1]=S.right},blockSize:2,keySize:4,ivSize:2});e.Blowfish=t._createHelper(h)}(),s.Blowfish}(ge(),Jt(),qt(),Vt(),Je())}(da)),da.exports}(function(a){a.exports=function(s){return s}(ge(),Mi(),Qn(),Zn(),Jt(),eo(),qt(),_s(),rr(),Is||(Is=1,function(s){s.exports=function(e){return i=(t=e).lib.WordArray,r=t.algo,n=r.SHA256,c=r.SHA224=n.extend({_doReset:function(){this._hash=new i.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=n._doFinalize.call(this);return o.sigBytes-=4,o}}),t.SHA224=n._createHelper(c),t.HmacSHA224=n._createHmacHelper(c),e.SHA224;var t,i,r,n,c}(ge(),rr())}(to)),Ps(),Ds||(Ds=1,function(s){s.exports=function(e){return i=(t=e).x64,r=i.Word,n=i.WordArray,c=t.algo,o=c.SHA512,l=c.SHA384=o.extend({_doReset:function(){this._hash=new n.init([new r.init(3418070365,3238371032),new r.init(1654270250,914150663),new r.init(2438529370,812702999),new r.init(355462360,4144912697),new r.init(1731405415,4290775857),new r.init(2394180231,1750603025),new r.init(3675008525,1694076839),new r.init(1203062813,3204075428)])},_doFinalize:function(){var d=o._doFinalize.call(this);return d.sigBytes-=16,d}}),t.SHA384=o._createHelper(l),t.HmacSHA384=o._createHmacHelper(l),e.SHA384;var t,i,r,n,c,o,l}(ge(),Mi(),Ps())}(io)),ro(),Ls||(Ls=1,function(s){s.exports=function(e){return function(){var t=e,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.algo,o=r.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),l=r.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),d=r.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),u=r.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),p=r.create([0,1518500249,1859775393,2400959708,2840853838]),h=r.create([1352829926,1548603684,1836072691,2053994217,0]),f=c.RIPEMD160=n.extend({_doReset:function(){this._hash=r.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(y,A){for(var w=0;w<16;w++){var T=A+w,I=y[T];y[T]=16711935&(I<<8|I>>>24)|4278255360&(I<<24|I>>>8)}var P,D,U,q,Y,G,$,Z,te,fe,N,x=this._hash.words,L=p.words,O=h.words,ue=o.words,Me=l.words,K=d.words,Se=u.words;for(G=P=x[0],$=D=x[1],Z=U=x[2],te=q=x[3],fe=Y=x[4],w=0;w<80;w+=1)N=P+y[A+ue[w]]|0,N+=w<16?g(D,U,q)+L[0]:w<32?S(D,U,q)+L[1]:w<48?b(D,U,q)+L[2]:w<64?v(D,U,q)+L[3]:R(D,U,q)+L[4],N=(N=_(N|=0,K[w]))+Y|0,P=Y,Y=q,q=_(U,10),U=D,D=N,N=G+y[A+Me[w]]|0,N+=w<16?R($,Z,te)+O[0]:w<32?v($,Z,te)+O[1]:w<48?b($,Z,te)+O[2]:w<64?S($,Z,te)+O[3]:g($,Z,te)+O[4],N=(N=_(N|=0,Se[w]))+fe|0,G=fe,fe=te,te=_(Z,10),Z=$,$=N;N=x[1]+U+te|0,x[1]=x[2]+q+fe|0,x[2]=x[3]+Y+G|0,x[3]=x[4]+P+$|0,x[4]=x[0]+D+Z|0,x[0]=N},_doFinalize:function(){var y=this._data,A=y.words,w=8*this._nDataBytes,T=8*y.sigBytes;A[T>>>5]|=128<<24-T%32,A[14+(T+64>>>9<<4)]=16711935&(w<<8|w>>>24)|4278255360&(w<<24|w>>>8),y.sigBytes=4*(A.length+1),this._process();for(var I=this._hash,P=I.words,D=0;D<5;D++){var U=P[D];P[D]=16711935&(U<<8|U>>>24)|4278255360&(U<<24|U>>>8)}return I},clone:function(){var y=n.clone.call(this);return y._hash=this._hash.clone(),y}});function g(y,A,w){return y^A^w}function S(y,A,w){return y&A|~y&w}function b(y,A,w){return(y|~A)^w}function v(y,A,w){return y&w|A&~w}function R(y,A,w){return y^(A|~w)}function _(y,A){return y<<A|y>>>32-A}t.RIPEMD160=n._createHelper(f),t.HmacRIPEMD160=n._createHmacHelper(f)}(),e.RIPEMD160}(ge())}(so)),sr(),Vs||(Vs=1,function(s){s.exports=function(e){return r=(i=(t=e).lib).Base,n=i.WordArray,o=(c=t.algo).SHA256,l=c.HMAC,d=c.PBKDF2=r.extend({cfg:r.extend({keySize:4,hasher:o,iterations:25e4}),init:function(u){this.cfg=this.cfg.extend(u)},compute:function(u,p){for(var h=this.cfg,f=l.create(h.hasher,u),g=n.create(),S=n.create([1]),b=g.words,v=S.words,R=h.keySize,_=h.iterations;b.length<R;){var y=f.update(p).finalize(S);f.reset();for(var A=y.words,w=A.length,T=y,I=1;I<_;I++){T=f.finalize(T),f.reset();for(var P=T.words,D=0;D<w;D++)A[D]^=P[D]}g.concat(y),v[0]++}return g.sigBytes=4*R,g}}),t.PBKDF2=function(u,p,h){return d.create(h).compute(u,p)},e.PBKDF2;var t,i,r,n,c,o,l,d}(ge(),rr(),sr())}(ao)),Vt(),Je(),no(),oo(),co(),lo(),Xs||(Xs=1,function(s){s.exports=function(e){return e.mode.ECB=((t=e.lib.BlockCipherMode.extend()).Encryptor=t.extend({processBlock:function(i,r){this._cipher.encryptBlock(i,r)}}),t.Decryptor=t.extend({processBlock:function(i,r){this._cipher.decryptBlock(i,r)}}),t),e.mode.ECB;var t}(ge(),Je())}(uo)),Ys||(Ys=1,function(s){s.exports=function(e){return e.pad.AnsiX923={pad:function(t,i){var r=t.sigBytes,n=4*i,c=n-r%n,o=r+c-1;t.clamp(),t.words[o>>>2]|=c<<24-o%4*8,t.sigBytes+=c},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Ansix923}(ge(),Je())}(ho)),Qs||(Qs=1,function(s){s.exports=function(e){return e.pad.Iso10126={pad:function(t,i){var r=4*i,n=r-t.sigBytes%r;t.concat(e.lib.WordArray.random(n-1)).concat(e.lib.WordArray.create([n<<24],1))},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Iso10126}(ge(),Je())}(po)),Zs||(Zs=1,function(s){s.exports=function(e){return e.pad.Iso97971={pad:function(t,i){t.concat(e.lib.WordArray.create([2147483648],1)),e.pad.ZeroPadding.pad(t,i)},unpad:function(t){e.pad.ZeroPadding.unpad(t),t.sigBytes--}},e.pad.Iso97971}(ge(),Je())}(mo)),ea||(ea=1,function(s){s.exports=function(e){return e.pad.ZeroPadding={pad:function(t,i){var r=4*i;t.clamp(),t.sigBytes+=r-(t.sigBytes%r||r)},unpad:function(t){var i=t.words,r=t.sigBytes-1;for(r=t.sigBytes-1;r>=0;r--)if(i[r>>>2]>>>24-r%4*8&255){t.sigBytes=r+1;break}}},e.pad.ZeroPadding}(ge(),Je())}(go)),ta||(ta=1,function(s){s.exports=function(e){return e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding}(ge(),Je())}(fo)),ia||(ia=1,function(s){s.exports=function(e){return i=(t=e).lib.CipherParams,r=t.enc.Hex,t.format.Hex={stringify:function(n){return n.ciphertext.toString(r)},parse:function(n){var c=r.parse(n);return i.create({ciphertext:c})}},e.format.Hex;var t,i,r}(ge(),Je())}(So)),ra||(ra=1,function(s){s.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,r=t.algo,n=[],c=[],o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[];(function(){for(var v=[],R=0;R<256;R++)v[R]=R<128?R<<1:R<<1^283;var _=0,y=0;for(R=0;R<256;R++){var A=y^y<<1^y<<2^y<<3^y<<4;A=A>>>8^255&A^99,n[_]=A,c[A]=_;var w=v[_],T=v[w],I=v[T],P=257*v[A]^16843008*A;o[_]=P<<24|P>>>8,l[_]=P<<16|P>>>16,d[_]=P<<8|P>>>24,u[_]=P,P=16843009*I^65537*T^257*w^16843008*_,p[A]=P<<24|P>>>8,h[A]=P<<16|P>>>16,f[A]=P<<8|P>>>24,g[A]=P,_?(_=w^v[v[v[I^w]]],y^=v[v[y]]):_=y=1}})();var S=[0,1,2,4,8,16,32,64,128,27,54],b=r.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var v=this._keyPriorReset=this._key,R=v.words,_=v.sigBytes/4,y=4*((this._nRounds=_+6)+1),A=this._keySchedule=[],w=0;w<y;w++)w<_?A[w]=R[w]:(P=A[w-1],w%_?_>6&&w%_==4&&(P=n[P>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P]):(P=n[(P=P<<8|P>>>24)>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P],P^=S[w/_|0]<<24),A[w]=A[w-_]^P);for(var T=this._invKeySchedule=[],I=0;I<y;I++){if(w=y-I,I%4)var P=A[w];else P=A[w-4];T[I]=I<4||w<=4?P:p[n[P>>>24]]^h[n[P>>>16&255]]^f[n[P>>>8&255]]^g[n[255&P]]}}},encryptBlock:function(v,R){this._doCryptBlock(v,R,this._keySchedule,o,l,d,u,n)},decryptBlock:function(v,R){var _=v[R+1];v[R+1]=v[R+3],v[R+3]=_,this._doCryptBlock(v,R,this._invKeySchedule,p,h,f,g,c),_=v[R+1],v[R+1]=v[R+3],v[R+3]=_},_doCryptBlock:function(v,R,_,y,A,w,T,I){for(var P=this._nRounds,D=v[R]^_[0],U=v[R+1]^_[1],q=v[R+2]^_[2],Y=v[R+3]^_[3],G=4,$=1;$<P;$++){var Z=y[D>>>24]^A[U>>>16&255]^w[q>>>8&255]^T[255&Y]^_[G++],te=y[U>>>24]^A[q>>>16&255]^w[Y>>>8&255]^T[255&D]^_[G++],fe=y[q>>>24]^A[Y>>>16&255]^w[D>>>8&255]^T[255&U]^_[G++],N=y[Y>>>24]^A[D>>>16&255]^w[U>>>8&255]^T[255&q]^_[G++];D=Z,U=te,q=fe,Y=N}Z=(I[D>>>24]<<24|I[U>>>16&255]<<16|I[q>>>8&255]<<8|I[255&Y])^_[G++],te=(I[U>>>24]<<24|I[q>>>16&255]<<16|I[Y>>>8&255]<<8|I[255&D])^_[G++],fe=(I[q>>>24]<<24|I[Y>>>16&255]<<16|I[D>>>8&255]<<8|I[255&U])^_[G++],N=(I[Y>>>24]<<24|I[D>>>16&255]<<16|I[U>>>8&255]<<8|I[255&q])^_[G++],v[R]=Z,v[R+1]=te,v[R+2]=fe,v[R+3]=N},keySize:8});t.AES=i._createHelper(b)}(),e.AES}(ge(),Jt(),qt(),Vt(),Je())}(bo)),vo(),na||(na=1,function(s){s.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,r=t.algo,n=r.RC4=i.extend({_doReset:function(){for(var l=this._key,d=l.words,u=l.sigBytes,p=this._S=[],h=0;h<256;h++)p[h]=h;h=0;for(var f=0;h<256;h++){var g=h%u,S=d[g>>>2]>>>24-g%4*8&255;f=(f+p[h]+S)%256;var b=p[h];p[h]=p[f],p[f]=b}this._i=this._j=0},_doProcessBlock:function(l,d){l[d]^=c.call(this)},keySize:8,ivSize:0});function c(){for(var l=this._S,d=this._i,u=this._j,p=0,h=0;h<4;h++){u=(u+l[d=(d+1)%256])%256;var f=l[d];l[d]=l[u],l[u]=f,p|=l[(l[d]+l[u])%256]<<24-8*h}return this._i=d,this._j=u,p}t.RC4=i._createHelper(n);var o=r.RC4Drop=n.extend({cfg:n.cfg.extend({drop:192}),_doReset:function(){n._doReset.call(this);for(var l=this.cfg.drop;l>0;l--)c.call(this)}});t.RC4Drop=i._createHelper(o)}(),e.RC4}(ge(),Jt(),qt(),Vt(),Je())}(yo)),oa||(oa=1,function(s){s.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,r=t.algo,n=[],c=[],o=[],l=r.Rabbit=i.extend({_doReset:function(){for(var u=this._key.words,p=this.cfg.iv,h=0;h<4;h++)u[h]=16711935&(u[h]<<8|u[h]>>>24)|4278255360&(u[h]<<24|u[h]>>>8);var f=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],g=this._C=[u[2]<<16|u[2]>>>16,4294901760&u[0]|65535&u[1],u[3]<<16|u[3]>>>16,4294901760&u[1]|65535&u[2],u[0]<<16|u[0]>>>16,4294901760&u[2]|65535&u[3],u[1]<<16|u[1]>>>16,4294901760&u[3]|65535&u[0]];for(this._b=0,h=0;h<4;h++)d.call(this);for(h=0;h<8;h++)g[h]^=f[h+4&7];if(p){var S=p.words,b=S[0],v=S[1],R=16711935&(b<<8|b>>>24)|4278255360&(b<<24|b>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,A=_<<16|65535&R;for(g[0]^=R,g[1]^=y,g[2]^=_,g[3]^=A,g[4]^=R,g[5]^=y,g[6]^=_,g[7]^=A,h=0;h<4;h++)d.call(this)}},_doProcessBlock:function(u,p){var h=this._X;d.call(this),n[0]=h[0]^h[5]>>>16^h[3]<<16,n[1]=h[2]^h[7]>>>16^h[5]<<16,n[2]=h[4]^h[1]>>>16^h[7]<<16,n[3]=h[6]^h[3]>>>16^h[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),u[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var u=this._X,p=this._C,h=0;h<8;h++)c[h]=p[h];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,h=0;h<8;h++){var f=u[h]+p[h],g=65535&f,S=f>>>16,b=((g*g>>>17)+g*S>>>15)+S*S,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[h]=b^v}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.Rabbit=i._createHelper(l)}(),e.Rabbit}(ge(),Jt(),qt(),Vt(),Je())}(Ro)),ca||(ca=1,function(s){s.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,r=t.algo,n=[],c=[],o=[],l=r.RabbitLegacy=i.extend({_doReset:function(){var u=this._key.words,p=this.cfg.iv,h=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],f=this._C=[u[2]<<16|u[2]>>>16,4294901760&u[0]|65535&u[1],u[3]<<16|u[3]>>>16,4294901760&u[1]|65535&u[2],u[0]<<16|u[0]>>>16,4294901760&u[2]|65535&u[3],u[1]<<16|u[1]>>>16,4294901760&u[3]|65535&u[0]];this._b=0;for(var g=0;g<4;g++)d.call(this);for(g=0;g<8;g++)f[g]^=h[g+4&7];if(p){var S=p.words,b=S[0],v=S[1],R=16711935&(b<<8|b>>>24)|4278255360&(b<<24|b>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,A=_<<16|65535&R;for(f[0]^=R,f[1]^=y,f[2]^=_,f[3]^=A,f[4]^=R,f[5]^=y,f[6]^=_,f[7]^=A,g=0;g<4;g++)d.call(this)}},_doProcessBlock:function(u,p){var h=this._X;d.call(this),n[0]=h[0]^h[5]>>>16^h[3]<<16,n[1]=h[2]^h[7]>>>16^h[5]<<16,n[2]=h[4]^h[1]>>>16^h[7]<<16,n[3]=h[6]^h[3]>>>16^h[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),u[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var u=this._X,p=this._C,h=0;h<8;h++)c[h]=p[h];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,h=0;h<8;h++){var f=u[h]+p[h],g=65535&f,S=f>>>16,b=((g*g>>>17)+g*S>>>15)+S*S,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[h]=b^v}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.RabbitLegacy=i._createHelper(l)}(),e.RabbitLegacy}(ge(),Jt(),qt(),Vt(),Je())}(Ao)),wo())})(os);const Gt=Gn(os.exports);function _o(a){return s=this,e=null,t=function*(){const i=new Date;if(a.refreshSTSTokenInterval||(a.refreshSTSTokenInterval=3e5),!a.stsTokenFreshTime||+i-a.stsTokenFreshTime>=a.refreshSTSTokenInterval){a.stsTokenFreshTime=i;try{yield a.refreshSTSToken()}catch(r){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
5
- `+r)}}return null},new Promise((i,r)=>{var n=l=>{try{o(t.next(l))}catch(d){r(d)}},c=l=>{try{o(t.throw(l))}catch(d){r(d)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,c);o((t=t.apply(s,e)).next())});var s,e,t}function ar(a){return{transString:function(s){let e={},t=0,i=!1;for(let r in s)r!=="time"&&r!=="__time__"||typeof s[r]!="number"?typeof s[r]=="object"?e[r]=JSON.stringify(s[r]):e[r]=String(s[r]):(t=s[r],i=!0);return e.__time__=i?t:Math.floor(new Date().getTime()/1e3),e},process:function(s,e){return t=this,i=null,r=function*(){yield _o(a);let n=s.slice(s.indexOf("/logstores")),c=e.length,o=(l=e,Gt.MD5(l).toString().toUpperCase());var l;let d=new Date().toUTCString(),u=new Map,p=new Map([["Content-Type","application/json"],["Content-MD5",o],["x-log-bodyrawsize",c.toString()]]);a.securityToken&&p.set("x-acs-security-token",a.securityToken),function(f,g,S,b,v,R,_,y){var A;let w="";R.set("x-log-apiversion","0.6.0"),R.set("x-log-signaturemethod","hmac-sha1"),w+=f+`
1
+ (function(z,K){typeof exports=="object"&&typeof module!="undefined"?K(exports,require("aliyun-rts-sdk"),require("eventemitter3")):typeof define=="function"&&define.amd?define(["exports","aliyun-rts-sdk","eventemitter3"],K):K((z=typeof globalThis!="undefined"?globalThis:z||self).AliRtcEngine={},z.AliyunRts,z.EventEmitter)})(this,function(z,K,oe){var re,mt,li,se,Xt,Yt,it,F,Jn;"use strict";var st=(a=>(a.EnableNonOnePcDefaultJoinMode="h5_enable_non_one_pc_default_join_mode",a))(st||{});function xt(){}let hi=0,ui=!1;const ci=class ci{static getInstance(){var r;return ci.instance||(ci.instance=new AudioContext),(r=ci.instance.resume())==null||r.then(xt,xt).catch(xt),ci.instance}};m(ci,"instance");let bt=ci;const rt=()=>{var r;const a=bt.getInstance();a.state!=="running"&&a.state!=="closed"&&((r=a.resume())==null||r.then(xt,xt).catch(xt)),window.removeEventListener("mousedown",rt),window.removeEventListener("touchstart",rt)};var St=(a=>(a.prod="rs.rtn.aliyuncs.com",a.pre="prs.rtn.aliyuncs.com",a))(St||{}),wt=(a=>(a.pre="pre",a.prod="prod",a))(wt||{}),Vt=(a=>(a.AliRtcSdkCommunication="communication",a.AliRtcSdkInteractiveLive="interactive_live",a.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",a))(Vt||{}),$t=(a=>(a.AliRtcSdkInteractive="interactive",a.AliRtcSdkLive="live",a))($t||{}),Tt=(a=>(a[a.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",a[a.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",a[a.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",a[a.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",a[a.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",a[a.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",a[a.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",a))(Tt||{}),He=(a=>(a[a.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",a[a.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",a[a.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",a[a.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",a[a.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",a[a.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",a[a.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",a[a.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",a[a.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",a[a.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",a[a.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",a[a.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",a))(He||{}),ae=(a=>(a[a.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",a[a.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",a[a.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",a[a.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",a[a.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",a[a.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",a))(ae||{}),Ct=(a=>(a[a.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",a[a.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",a[a.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",a[a.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",a[a.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",a[a.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",a[a.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",a[a.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",a[a.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",a[a.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",a[a.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",a[a.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",a[a.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",a))(Ct||{}),rs=(a=>(a[a.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",a[a.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",a[a.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",a))(rs||{}),Zt=(a=>(a[a.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",a[a.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",a[a.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",a))(Zt||{}),he=(a=>(a[a.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",a[a.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",a[a.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",a[a.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",a))(he||{}),ee=(a=>(a[a.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",a[a.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",a[a.AliRtcStatePublishing=2]="AliRtcStatePublishing",a[a.AliRtcStatePublished=3]="AliRtcStatePublished",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(ee||{}),ce=(a=>(a[a.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",a[a.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",a[a.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",a[a.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(ce||{}),Je=(a=>(a[a.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",a[a.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",a[a.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",a))(Je||{}),yi=(a=>(a[a.CAMERA_INVALID=-1]="CAMERA_INVALID",a[a.CAMERA_REAR=0]="CAMERA_REAR",a[a.CAMERA_FRONT=1]="CAMERA_FRONT",a))(yi||{}),Ze=(a=>(a[a.AliRtcNetworkExcellent=0]="AliRtcNetworkExcellent",a[a.AliRtcNetworkGood=1]="AliRtcNetworkGood",a[a.AliRtcNetworkPoor=2]="AliRtcNetworkPoor",a[a.AliRtcNetworkBad=3]="AliRtcNetworkBad",a[a.AliRtcNetworkVeryBad=4]="AliRtcNetworkVeryBad",a[a.AliRtcNetworkDisconnected=5]="AliRtcNetworkDisconnected",a[a.AliRtcNetworkUnknown=6]="AliRtcNetworkUnknown",a))(Ze||{}),Pe=(a=>(a.PullStreamStats="remoteStat",a.RtsSubscribeExceeds="rtsSubscribeExceeds",a.UserJoined="userJoined",a.UserLeft="userLeft",a.Bye="bye",a.MuteAudio="muteAudio",a.UnmuteAudio="unmuteAudio",a.MuteVideo="muteVideo",a.UnmuteVideo="unmuteVideo",a.MuteScreen="muteScreen",a.UnmuteScreen="unmuteScreen",a.Error="error",a))(Pe||{}),at=(a=>(a.Local="local-device-status-change",a.Remote="remote-device-status-change",a))(at||{}),M=(a=>(a.Audio="sophon_audio",a.VideoLarge="sophon_video_camera_large",a.VideoSmall="sophon_video_camera_small",a.Screen="sophon_video_screen_share",a.Data="sophon_data",a))(M||{}),as=(a=>(a.Audio="rts audio",a.VideoLarge="rts video",a))(as||{}),Ot=(a=>(a.Add="add",a.Delete="delete",a.Replace="replace",a.Stop="stop",a.UnPublish="unpublish",a))(Ot||{}),Ri=(a=>(a[a.Camera=0]="Camera",a[a.Screen=1]="Screen",a[a.Image=2]="Image",a))(Ri||{}),Ui=(a=>(a[a.Microphone=0]="Microphone",a[a.Screen=1]="Screen",a[a.Mixed=2]="Mixed",a))(Ui||{}),ge=(a=>(a.InRoom="inRoom",a.Join="join",a.Publish="publish",a.User="user",a.Resume="resume",a.Retry="retry",a.Reconnect="reconnect",a))(ge||{}),kt=(a=>(a[a.MANUAL=0]="MANUAL",a[a.JOIN_CHANNEL=1]="JOIN_CHANNEL",a[a.ROLE_CHANGE=2]="ROLE_CHANGE",a[a.RECONNECT=3]="RECONNECT",a))(kt||{}),B=(a=>(a[a.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",a[a.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",a[a.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",a[a.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",a[a.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",a[a.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",a[a.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",a[a.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",a[a.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",a[a.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",a[a.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",a[a.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",a[a.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",a[a.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",a[a.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",a[a.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",a[a.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",a[a.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",a[a.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",a[a.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",a[a.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",a[a.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",a[a.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",a[a.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",a[a.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",a[a.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",a[a.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",a[a.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",a[a.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",a[a.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",a[a.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",a[a.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",a[a.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",a[a.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",a[a.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",a[a.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",a[a.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",a[a.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",a[a.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",a[a.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",a[a.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",a[a.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",a[a.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",a[a.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",a[a.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",a[a.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",a[a.ERR_INNER=-1]="ERR_INNER",a[a.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",a[a.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",a[a.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",a[a.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",a[a.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",a[a.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",a[a.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",a[a.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",a[a.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",a[a.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",a[a.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",a[a.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",a))(B||{});class O extends Error{constructor(e,t,i){super(t);m(this,"_code");m(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof O?e:new O((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new O(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function dr(a){var r;if(((r=a==null?void 0:a.nodeName)==null?void 0:r.toLowerCase())==="video")return a.setAttribute("playsinline",""),a;if(typeof a=="string"){let e=document.getElementById(a);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new O(B.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new O(B.ERR_INVALID_ARGUMENTS,"element not founded")}throw new O(B.ERR_INVALID_ARGUMENTS,"element id should be string")}function ns(a){var e;const r=[];if(Array.isArray(a))a.forEach(t=>{try{r.push(dr(t))}catch(i){}});else if(typeof a=="string"||((e=a==null?void 0:a.nodeName)==null?void 0:e.toLowerCase())==="video")try{r.push(dr(a))}catch(t){}return r}function Ut(a){return new Promise(r=>setTimeout(r,a))}function hr(a,r,e=1e3,t=i=>!0){return I(this,null,function*(){let i=0;for(;i<r;)try{return yield a(i)}catch(s){if(i++,i>=r||!t(s))throw s||void 0;yield new Promise(n=>setTimeout(n,e))}})}function os(a,r){let e=r;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${a}&ali_prefer_media_server=${e}`:a}function ei(a,r){var e;try{const{archCfgs:t}=a;if(!t||!Array.isArray(t))return;const i=t.find(s=>s.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[r]:void 0}catch(t){return}}function pi(a,r){try{const{config:e}=a;return e?e==null?void 0:e[r]:void 0}catch(e){return}}function so(a){const r=a.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
2
+ `);return r.includes(`a=rtcp-rsize\r
3
+ `)?r:r.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
4
+ `)}function cs(a,r){return a>50||r>500?Ze.AliRtcNetworkVeryBad:a>30||r>350?Ze.AliRtcNetworkBad:a>20||r>200?Ze.AliRtcNetworkPoor:a>10||r>100?Ze.AliRtcNetworkGood:a>=0||r>=0?Ze.AliRtcNetworkExcellent:Ze.AliRtcNetworkUnknown}function ur(a){return!!a&&[M.VideoLarge,M.VideoSmall,M.Screen].includes(a)}function pr(a){return a===M.Audio}for(var ls,qe=[],ds=0;ds<256;++ds)qe.push((ds+256).toString(16).slice(1));var ro=new Uint8Array(16);function ao(){if(!ls&&!(ls=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ls(ro)}const mr={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ut(a,r,e){if(mr.randomUUID&&!r&&!a)return mr.randomUUID();var t=(a=a||{}).random||(a.rng||ao)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,r){e=e||0;for(var i=0;i<16;++i)r[e+i]=t[i];return r}return function(s,n=0){return(qe[s[n+0]]+qe[s[n+1]]+qe[s[n+2]]+qe[s[n+3]]+"-"+qe[s[n+4]]+qe[s[n+5]]+"-"+qe[s[n+6]]+qe[s[n+7]]+"-"+qe[s[n+8]]+qe[s[n+9]]+"-"+qe[s[n+10]]+qe[s[n+11]]+qe[s[n+12]]+qe[s[n+13]]+qe[s[n+14]]+qe[s[n+15]]).toLowerCase()}(t)}const Ai="7.2.8-beta.3";class De{static getVersionNumber(){let r=Ai.split("."),e="";return r.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(r){let e=[];if(r)for(let t in r)e.push(t+"="+r[t]);return e.join("&")}static getQueryParams(r){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===r)return decodeURIComponent(i[1])}}static createCallid(r=""){const e=ut();return r&&e&&e.length>r.length?`${r}${e.substring(r.length)}`:e}static checkSubOptionsValid(r){if(r){const{audio:e,video:t,screen:i}=r;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return I(this,null,function*(){const r=St.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${r}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(r){let e;if(r instanceof Error)e=r.message;else if(typeof r=="string")e=r;else try{e=JSON.stringify(r)}catch(t){e="undefined"}return e}static paramArrayToString(r){let e="";for(let t=0;t<r.length;t++)e!==""&&(e+=" "),e+=De.toString(r[t]);return e}static removeQueryString(r){if(!r)return r;let e=r.indexOf("?");return e>0?r.substring(0,e):r}}function gr(a,r,e){Object.defineProperty(a,r,{writable:!0,enumerable:!0,configurable:!0,value:e})}function fr(a,r,e,t){t?t(()=>{gr(a,r,e)}):gr(a,r,e)}Array(32);var Bi=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function no(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}function oo(a){if(a.__esModule)return a;var r=a.default;if(typeof r=="function"){var e=function t(){return this instanceof t?Reflect.construct(r,arguments,this.constructor):r.apply(this,arguments)};e.prototype=r.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(a).forEach(function(t){var i=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return a[t]}})}),e}var br={exports:{}},Sr={exports:{}};const co=oo(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var vr;function fe(){return vr||(vr=1,function(a){a.exports=function(){var r=r||function(e,t){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&Bi!==void 0&&Bi.crypto&&(i=Bi.crypto),!i)try{i=co}catch(b){}var s=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(b){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(b){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function b(){}return function(v){var R;return b.prototype=v,R=new b,b.prototype=null,R}}(),c={},o=c.lib={},l=o.Base={extend:function(b){var v=n(this);return b&&v.mixIn(b),v.hasOwnProperty("init")&&this.init!==v.init||(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){var b=this.extend();return b.init.apply(b,arguments),b},init:function(){},mixIn:function(b){for(var v in b)b.hasOwnProperty(v)&&(this[v]=b[v]);b.hasOwnProperty("toString")&&(this.toString=b.toString)},clone:function(){return this.init.prototype.extend(this)}},d=o.WordArray=l.extend({init:function(b,v){b=this.words=b||[],this.sigBytes=v!=t?v:4*b.length},toString:function(b){return(b||p).stringify(this)},concat:function(b){var v=this.words,R=b.words,_=this.sigBytes,y=b.sigBytes;if(this.clamp(),_%4)for(var A=0;A<y;A++){var w=R[A>>>2]>>>24-A%4*8&255;v[_+A>>>2]|=w<<24-(_+A)%4*8}else for(var E=0;E<y;E+=4)v[_+E>>>2]=R[E>>>2];return this.sigBytes+=y,this},clamp:function(){var b=this.words,v=this.sigBytes;b[v>>>2]&=4294967295<<32-v%4*8,b.length=e.ceil(v/4)},clone:function(){var b=l.clone.call(this);return b.words=this.words.slice(0),b},random:function(b){for(var v=[],R=0;R<b;R+=4)v.push(s());return new d.init(v,b)}}),h=c.enc={},p=h.Hex={stringify:function(b){for(var v=b.words,R=b.sigBytes,_=[],y=0;y<R;y++){var A=v[y>>>2]>>>24-y%4*8&255;_.push((A>>>4).toString(16)),_.push((15&A).toString(16))}return _.join("")},parse:function(b){for(var v=b.length,R=[],_=0;_<v;_+=2)R[_>>>3]|=parseInt(b.substr(_,2),16)<<24-_%8*4;return new d.init(R,v/2)}},u=h.Latin1={stringify:function(b){for(var v=b.words,R=b.sigBytes,_=[],y=0;y<R;y++){var A=v[y>>>2]>>>24-y%4*8&255;_.push(String.fromCharCode(A))}return _.join("")},parse:function(b){for(var v=b.length,R=[],_=0;_<v;_++)R[_>>>2]|=(255&b.charCodeAt(_))<<24-_%4*8;return new d.init(R,v)}},f=h.Utf8={stringify:function(b){try{return decodeURIComponent(escape(u.stringify(b)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(b){return u.parse(unescape(encodeURIComponent(b)))}},g=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(b){typeof b=="string"&&(b=f.parse(b)),this._data.concat(b),this._nDataBytes+=b.sigBytes},_process:function(b){var v,R=this._data,_=R.words,y=R.sigBytes,A=this.blockSize,w=y/(4*A),E=(w=b?e.ceil(w):e.max((0|w)-this._minBufferSize,0))*A,C=e.min(4*E,y);if(E){for(var P=0;P<E;P+=A)this._doProcessBlock(_,P);v=_.splice(0,E),R.sigBytes-=C}return new d.init(v,C)},clone:function(){var b=l.clone.call(this);return b._data=this._data.clone(),b},_minBufferSize:0});o.Hasher=g.extend({cfg:l.extend(),init:function(b){this.cfg=this.cfg.extend(b),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(b){return this._append(b),this._process(),this},finalize:function(b){return b&&this._append(b),this._doFinalize()},blockSize:16,_createHelper:function(b){return function(v,R){return new b.init(R).finalize(v)}},_createHmacHelper:function(b){return function(v,R){return new S.HMAC.init(b,R).finalize(v)}}});var S=c.algo={};return c}(Math);return r}()}(Sr)),Sr.exports}var yr,Rr={exports:{}};function Hi(){return yr||(yr=1,function(a){a.exports=function(r){return i=(t=r).lib,s=i.Base,n=i.WordArray,(c=t.x64={}).Word=s.extend({init:function(o,l){this.high=o,this.low=l}}),c.WordArray=s.extend({init:function(o,l){o=this.words=o||[],this.sigBytes=l!=e?l:8*o.length},toX32:function(){for(var o=this.words,l=o.length,d=[],h=0;h<l;h++){var p=o[h];d.push(p.high),d.push(p.low)}return n.create(d,this.sigBytes)},clone:function(){for(var o=s.clone.call(this),l=o.words=this.words.slice(0),d=l.length,h=0;h<d;h++)l[h]=l[h].clone();return o}}),r;var e,t,i,s,n,c}(fe())}(Rr)),Rr.exports}var Ar,wr={exports:{}};function lo(){return Ar||(Ar=1,function(a){a.exports=function(r){return function(){if(typeof ArrayBuffer=="function"){var e=r.lib.WordArray,t=e.init,i=e.init=function(s){if(s instanceof ArrayBuffer&&(s=new Uint8Array(s)),(s instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&s instanceof Uint8ClampedArray||s instanceof Int16Array||s instanceof Uint16Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Float32Array||s instanceof Float64Array)&&(s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),s instanceof Uint8Array){for(var n=s.byteLength,c=[],o=0;o<n;o++)c[o>>>2]|=s[o]<<24-o%4*8;t.call(this,c,n)}else t.apply(this,arguments)};i.prototype=e}}(),r.lib.WordArray}(fe())}(wr)),wr.exports}var _r,Ir={exports:{}};function ho(){return _r||(_r=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray,i=e.enc;function s(n){return n<<8&4278255360|n>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var h=c[d>>>2]>>>16-d%4*8&65535;l.push(String.fromCharCode(h))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=n.charCodeAt(l)<<16-l%2*16;return t.create(o,2*c)}},i.Utf16LE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var h=s(c[d>>>2]>>>16-d%4*8&65535);l.push(String.fromCharCode(h))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=s(n.charCodeAt(l)<<16-l%2*16);return t.create(o,2*c)}}}(),r.enc.Utf16}(fe())}(Ir)),Ir.exports}var Er,Tr={exports:{}};function ti(){return Er||(Er=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(s,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var h=c[s.charCodeAt(d-1)]<<d%4*2|c[s.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=h<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64={stringify:function(s){var n=s.words,c=s.sigBytes,o=this._map;s.clamp();for(var l=[],d=0;d<c;d+=3)for(var h=(n[d>>>2]>>>24-d%4*8&255)<<16|(n[d+1>>>2]>>>24-(d+1)%4*8&255)<<8|n[d+2>>>2]>>>24-(d+2)%4*8&255,p=0;p<4&&d+.75*p<c;p++)l.push(o.charAt(h>>>6*(3-p)&63));var u=o.charAt(64);if(u)for(;l.length%4;)l.push(u);return l.join("")},parse:function(s){var n=s.length,c=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var l=0;l<c.length;l++)o[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var h=s.indexOf(d);h!==-1&&(n=h)}return i(s,n,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),r.enc.Base64}(fe())}(Tr)),Tr.exports}var Cr,kr={exports:{}};function uo(){return Cr||(Cr=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(s,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var h=c[s.charCodeAt(d-1)]<<d%4*2|c[s.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=h<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64url={stringify:function(s,n){n===void 0&&(n=!0);var c=s.words,o=s.sigBytes,l=n?this._safe_map:this._map;s.clamp();for(var d=[],h=0;h<o;h+=3)for(var p=(c[h>>>2]>>>24-h%4*8&255)<<16|(c[h+1>>>2]>>>24-(h+1)%4*8&255)<<8|c[h+2>>>2]>>>24-(h+2)%4*8&255,u=0;u<4&&h+.75*u<o;u++)d.push(l.charAt(p>>>6*(3-u)&63));var f=l.charAt(64);if(f)for(;d.length%4;)d.push(f);return d.join("")},parse:function(s,n){n===void 0&&(n=!0);var c=s.length,o=n?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<o.length;d++)l[o.charCodeAt(d)]=d}var h=o.charAt(64);if(h){var p=s.indexOf(h);p!==-1&&(c=p)}return i(s,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),r.enc.Base64url}(fe())}(kr)),kr.exports}var Pr,Dr={exports:{}};function ii(){return Pr||(Pr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=[];(function(){for(var f=0;f<64;f++)o[f]=4294967296*e.abs(e.sin(f+1))|0})();var l=c.MD5=n.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(f,g){for(var S=0;S<16;S++){var b=g+S,v=f[b];f[b]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8)}var R=this._hash.words,_=f[g+0],y=f[g+1],A=f[g+2],w=f[g+3],E=f[g+4],C=f[g+5],P=f[g+6],D=f[g+7],U=f[g+8],G=f[g+9],Y=f[g+10],q=f[g+11],W=f[g+12],Z=f[g+13],te=f[g+14],be=f[g+15],L=R[0],x=R[1],N=R[2],V=R[3];L=d(L,x,N,V,_,7,o[0]),V=d(V,L,x,N,y,12,o[1]),N=d(N,V,L,x,A,17,o[2]),x=d(x,N,V,L,w,22,o[3]),L=d(L,x,N,V,E,7,o[4]),V=d(V,L,x,N,C,12,o[5]),N=d(N,V,L,x,P,17,o[6]),x=d(x,N,V,L,D,22,o[7]),L=d(L,x,N,V,U,7,o[8]),V=d(V,L,x,N,G,12,o[9]),N=d(N,V,L,x,Y,17,o[10]),x=d(x,N,V,L,q,22,o[11]),L=d(L,x,N,V,W,7,o[12]),V=d(V,L,x,N,Z,12,o[13]),N=d(N,V,L,x,te,17,o[14]),L=h(L,x=d(x,N,V,L,be,22,o[15]),N,V,y,5,o[16]),V=h(V,L,x,N,P,9,o[17]),N=h(N,V,L,x,q,14,o[18]),x=h(x,N,V,L,_,20,o[19]),L=h(L,x,N,V,C,5,o[20]),V=h(V,L,x,N,Y,9,o[21]),N=h(N,V,L,x,be,14,o[22]),x=h(x,N,V,L,E,20,o[23]),L=h(L,x,N,V,G,5,o[24]),V=h(V,L,x,N,te,9,o[25]),N=h(N,V,L,x,w,14,o[26]),x=h(x,N,V,L,U,20,o[27]),L=h(L,x,N,V,Z,5,o[28]),V=h(V,L,x,N,A,9,o[29]),N=h(N,V,L,x,D,14,o[30]),L=p(L,x=h(x,N,V,L,W,20,o[31]),N,V,C,4,o[32]),V=p(V,L,x,N,U,11,o[33]),N=p(N,V,L,x,q,16,o[34]),x=p(x,N,V,L,te,23,o[35]),L=p(L,x,N,V,y,4,o[36]),V=p(V,L,x,N,E,11,o[37]),N=p(N,V,L,x,D,16,o[38]),x=p(x,N,V,L,Y,23,o[39]),L=p(L,x,N,V,Z,4,o[40]),V=p(V,L,x,N,_,11,o[41]),N=p(N,V,L,x,w,16,o[42]),x=p(x,N,V,L,P,23,o[43]),L=p(L,x,N,V,G,4,o[44]),V=p(V,L,x,N,W,11,o[45]),N=p(N,V,L,x,be,16,o[46]),L=u(L,x=p(x,N,V,L,A,23,o[47]),N,V,_,6,o[48]),V=u(V,L,x,N,D,10,o[49]),N=u(N,V,L,x,te,15,o[50]),x=u(x,N,V,L,C,21,o[51]),L=u(L,x,N,V,W,6,o[52]),V=u(V,L,x,N,w,10,o[53]),N=u(N,V,L,x,Y,15,o[54]),x=u(x,N,V,L,y,21,o[55]),L=u(L,x,N,V,U,6,o[56]),V=u(V,L,x,N,be,10,o[57]),N=u(N,V,L,x,P,15,o[58]),x=u(x,N,V,L,Z,21,o[59]),L=u(L,x,N,V,E,6,o[60]),V=u(V,L,x,N,q,10,o[61]),N=u(N,V,L,x,A,15,o[62]),x=u(x,N,V,L,G,21,o[63]),R[0]=R[0]+L|0,R[1]=R[1]+x|0,R[2]=R[2]+N|0,R[3]=R[3]+V|0},_doFinalize:function(){var f=this._data,g=f.words,S=8*this._nDataBytes,b=8*f.sigBytes;g[b>>>5]|=128<<24-b%32;var v=e.floor(S/4294967296),R=S;g[15+(b+64>>>9<<4)]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),g[14+(b+64>>>9<<4)]=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),f.sigBytes=4*(g.length+1),this._process();for(var _=this._hash,y=_.words,A=0;A<4;A++){var w=y[A];y[A]=16711935&(w<<8|w>>>24)|4278255360&(w<<24|w>>>8)}return _},clone:function(){var f=n.clone.call(this);return f._hash=this._hash.clone(),f}});function d(f,g,S,b,v,R,_){var y=f+(g&S|~g&b)+v+_;return(y<<R|y>>>32-R)+g}function h(f,g,S,b,v,R,_){var y=f+(g&b|S&~b)+v+_;return(y<<R|y>>>32-R)+g}function p(f,g,S,b,v,R,_){var y=f+(g^S^b)+v+_;return(y<<R|y>>>32-R)+g}function u(f,g,S,b,v,R,_){var y=f+(S^(g|~b))+v+_;return(y<<R|y>>>32-R)+g}t.MD5=n._createHelper(l),t.HmacMD5=n._createHmacHelper(l)}(Math),r.MD5}(fe())}(Dr)),Dr.exports}var Mr,Lr={exports:{}};function Nr(){return Mr||(Mr=1,function(a){a.exports=function(r){return t=(e=r).lib,i=t.WordArray,s=t.Hasher,n=e.algo,c=[],o=n.SHA1=s.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(l,d){for(var h=this._hash.words,p=h[0],u=h[1],f=h[2],g=h[3],S=h[4],b=0;b<80;b++){if(b<16)c[b]=0|l[d+b];else{var v=c[b-3]^c[b-8]^c[b-14]^c[b-16];c[b]=v<<1|v>>>31}var R=(p<<5|p>>>27)+S+c[b];R+=b<20?1518500249+(u&f|~u&g):b<40?1859775393+(u^f^g):b<60?(u&f|u&g|f&g)-1894007588:(u^f^g)-899497514,S=g,g=f,f=u<<30|u>>>2,u=p,p=R}h[0]=h[0]+p|0,h[1]=h[1]+u|0,h[2]=h[2]+f|0,h[3]=h[3]+g|0,h[4]=h[4]+S|0},_doFinalize:function(){var l=this._data,d=l.words,h=8*this._nDataBytes,p=8*l.sigBytes;return d[p>>>5]|=128<<24-p%32,d[14+(p+64>>>9<<4)]=Math.floor(h/4294967296),d[15+(p+64>>>9<<4)]=h,l.sigBytes=4*d.length,this._process(),this._hash},clone:function(){var l=s.clone.call(this);return l._hash=this._hash.clone(),l}}),e.SHA1=s._createHelper(o),e.HmacSHA1=s._createHmacHelper(o),r.SHA1;var e,t,i,s,n,c,o}(fe())}(Lr)),Lr.exports}var xr,Vr={exports:{}};function hs(){return xr||(xr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=[],l=[];(function(){function p(S){for(var b=e.sqrt(S),v=2;v<=b;v++)if(!(S%v))return!1;return!0}function u(S){return 4294967296*(S-(0|S))|0}for(var f=2,g=0;g<64;)p(f)&&(g<8&&(o[g]=u(e.pow(f,.5))),l[g]=u(e.pow(f,1/3)),g++),f++})();var d=[],h=c.SHA256=n.extend({_doReset:function(){this._hash=new s.init(o.slice(0))},_doProcessBlock:function(p,u){for(var f=this._hash.words,g=f[0],S=f[1],b=f[2],v=f[3],R=f[4],_=f[5],y=f[6],A=f[7],w=0;w<64;w++){if(w<16)d[w]=0|p[u+w];else{var E=d[w-15],C=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,P=d[w-2],D=(P<<15|P>>>17)^(P<<13|P>>>19)^P>>>10;d[w]=C+d[w-7]+D+d[w-16]}var U=g&S^g&b^S&b,G=(g<<30|g>>>2)^(g<<19|g>>>13)^(g<<10|g>>>22),Y=A+((R<<26|R>>>6)^(R<<21|R>>>11)^(R<<7|R>>>25))+(R&_^~R&y)+l[w]+d[w];A=y,y=_,_=R,R=v+Y|0,v=b,b=S,S=g,g=Y+(G+U)|0}f[0]=f[0]+g|0,f[1]=f[1]+S|0,f[2]=f[2]+b|0,f[3]=f[3]+v|0,f[4]=f[4]+R|0,f[5]=f[5]+_|0,f[6]=f[6]+y|0,f[7]=f[7]+A|0},_doFinalize:function(){var p=this._data,u=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return u[g>>>5]|=128<<24-g%32,u[14+(g+64>>>9<<4)]=e.floor(f/4294967296),u[15+(g+64>>>9<<4)]=f,p.sigBytes=4*u.length,this._process(),this._hash},clone:function(){var p=n.clone.call(this);return p._hash=this._hash.clone(),p}});t.SHA256=n._createHelper(h),t.HmacSHA256=n._createHmacHelper(h)}(Math),r.SHA256}(fe())}(Vr)),Vr.exports}var Or,po={exports:{}},Ur,Br={exports:{}};function Hr(){return Ur||(Ur=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.Hasher,i=e.x64,s=i.Word,n=i.WordArray,c=e.algo;function o(){return s.create.apply(s,arguments)}var l=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],d=[];(function(){for(var p=0;p<80;p++)d[p]=o()})();var h=c.SHA512=t.extend({_doReset:function(){this._hash=new n.init([new s.init(1779033703,4089235720),new s.init(3144134277,2227873595),new s.init(1013904242,4271175723),new s.init(2773480762,1595750129),new s.init(1359893119,2917565137),new s.init(2600822924,725511199),new s.init(528734635,4215389547),new s.init(1541459225,327033209)])},_doProcessBlock:function(p,u){for(var f=this._hash.words,g=f[0],S=f[1],b=f[2],v=f[3],R=f[4],_=f[5],y=f[6],A=f[7],w=g.high,E=g.low,C=S.high,P=S.low,D=b.high,U=b.low,G=v.high,Y=v.low,q=R.high,W=R.low,Z=_.high,te=_.low,be=y.high,L=y.low,x=A.high,N=A.low,V=w,ue=E,Le=C,J=P,ve=D,xe=U,Ee=G,Me=Y,ye=q,Te=W,pe=Z,Ne=te,we=be,Xe=L,dt=x,le=N,ne=0;ne<80;ne++){var ie,Re,Be=d[ne];if(ne<16)Re=Be.high=0|p[u+2*ne],ie=Be.low=0|p[u+2*ne+1];else{var me=d[ne-15],Ke=me.high,Q=me.low,Ve=(Ke>>>1|Q<<31)^(Ke>>>8|Q<<24)^Ke>>>7,ht=(Q>>>1|Ke<<31)^(Q>>>8|Ke<<24)^(Q>>>7|Ke<<25),Oe=d[ne-2],It=Oe.high,Nt=Oe.low,Et=(It>>>19|Nt<<13)^(It<<3|Nt>>>29)^It>>>6,Qt=(Nt>>>19|It<<13)^(Nt<<3|It>>>29)^(Nt>>>6|It<<26),Vi=d[ne-7],is=Vi.high,ul=Vi.low,Gn=d[ne-16],pl=Gn.high,qn=Gn.low;Re=(Re=(Re=Ve+is+((ie=ht+ul)>>>0<ht>>>0?1:0))+Et+((ie+=Qt)>>>0<Qt>>>0?1:0))+pl+((ie+=qn)>>>0<qn>>>0?1:0),Be.high=Re,Be.low=ie}var di,ml=ye&pe^~ye&we,Xn=Te&Ne^~Te&Xe,gl=V&Le^V&ve^Le&ve,fl=ue&J^ue&xe^J&xe,bl=(V>>>28|ue<<4)^(V<<30|ue>>>2)^(V<<25|ue>>>7),Yn=(ue>>>28|V<<4)^(ue<<30|V>>>2)^(ue<<25|V>>>7),Sl=(ye>>>14|Te<<18)^(ye>>>18|Te<<14)^(ye<<23|Te>>>9),vl=(Te>>>14|ye<<18)^(Te>>>18|ye<<14)^(Te<<23|ye>>>9),Qn=l[ne],yl=Qn.high,Zn=Qn.low,Oi=dt+Sl+((di=le+vl)>>>0<le>>>0?1:0),eo=Yn+fl;dt=we,le=Xe,we=pe,Xe=Ne,pe=ye,Ne=Te,ye=Ee+(Oi=(Oi=(Oi=Oi+ml+((di+=Xn)>>>0<Xn>>>0?1:0))+yl+((di+=Zn)>>>0<Zn>>>0?1:0))+Re+((di+=ie)>>>0<ie>>>0?1:0))+((Te=Me+di|0)>>>0<Me>>>0?1:0)|0,Ee=ve,Me=xe,ve=Le,xe=J,Le=V,J=ue,V=Oi+(bl+gl+(eo>>>0<Yn>>>0?1:0))+((ue=di+eo|0)>>>0<di>>>0?1:0)|0}E=g.low=E+ue,g.high=w+V+(E>>>0<ue>>>0?1:0),P=S.low=P+J,S.high=C+Le+(P>>>0<J>>>0?1:0),U=b.low=U+xe,b.high=D+ve+(U>>>0<xe>>>0?1:0),Y=v.low=Y+Me,v.high=G+Ee+(Y>>>0<Me>>>0?1:0),W=R.low=W+Te,R.high=q+ye+(W>>>0<Te>>>0?1:0),te=_.low=te+Ne,_.high=Z+pe+(te>>>0<Ne>>>0?1:0),L=y.low=L+Xe,y.high=be+we+(L>>>0<Xe>>>0?1:0),N=A.low=N+le,A.high=x+dt+(N>>>0<le>>>0?1:0)},_doFinalize:function(){var p=this._data,u=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return u[g>>>5]|=128<<24-g%32,u[30+(g+128>>>10<<5)]=Math.floor(f/4294967296),u[31+(g+128>>>10<<5)]=f,p.sigBytes=4*u.length,this._process(),this._hash.toX32()},clone:function(){var p=t.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:32});e.SHA512=t._createHelper(h),e.HmacSHA512=t._createHmacHelper(h)}(),r.SHA512}(fe(),Hi())}(Br)),Br.exports}var Fr,mo={exports:{}},jr,$r={exports:{}};function go(){return jr||(jr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.x64.Word,o=t.algo,l=[],d=[],h=[];(function(){for(var f=1,g=0,S=0;S<24;S++){l[f+5*g]=(S+1)*(S+2)/2%64;var b=(2*f+3*g)%5;f=g%5,g=b}for(f=0;f<5;f++)for(g=0;g<5;g++)d[f+5*g]=g+(2*f+3*g)%5*5;for(var v=1,R=0;R<24;R++){for(var _=0,y=0,A=0;A<7;A++){if(1&v){var w=(1<<A)-1;w<32?y^=1<<w:_^=1<<w-32}128&v?v=v<<1^113:v<<=1}h[R]=c.create(_,y)}})();var p=[];(function(){for(var f=0;f<25;f++)p[f]=c.create()})();var u=o.SHA3=n.extend({cfg:n.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],g=0;g<25;g++)f[g]=new c.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,g){for(var S=this._state,b=this.blockSize/2,v=0;v<b;v++){var R=f[g+2*v],_=f[g+2*v+1];R=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),_=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8),(N=S[v]).high^=_,N.low^=R}for(var y=0;y<24;y++){for(var A=0;A<5;A++){for(var w=0,E=0,C=0;C<5;C++)w^=(N=S[A+5*C]).high,E^=N.low;var P=p[A];P.high=w,P.low=E}for(A=0;A<5;A++){var D=p[(A+4)%5],U=p[(A+1)%5],G=U.high,Y=U.low;for(w=D.high^(G<<1|Y>>>31),E=D.low^(Y<<1|G>>>31),C=0;C<5;C++)(N=S[A+5*C]).high^=w,N.low^=E}for(var q=1;q<25;q++){var W=(N=S[q]).high,Z=N.low,te=l[q];te<32?(w=W<<te|Z>>>32-te,E=Z<<te|W>>>32-te):(w=Z<<te-32|W>>>64-te,E=W<<te-32|Z>>>64-te);var be=p[d[q]];be.high=w,be.low=E}var L=p[0],x=S[0];for(L.high=x.high,L.low=x.low,A=0;A<5;A++)for(C=0;C<5;C++){var N=S[q=A+5*C],V=p[q],ue=p[(A+1)%5+5*C],Le=p[(A+2)%5+5*C];N.high=V.high^~ue.high&Le.high,N.low=V.low^~ue.low&Le.low}N=S[0];var J=h[y];N.high^=J.high,N.low^=J.low}},_doFinalize:function(){var f=this._data,g=f.words;this._nDataBytes;var S=8*f.sigBytes,b=32*this.blockSize;g[S>>>5]|=1<<24-S%32,g[(e.ceil((S+1)/b)*b>>>5)-1]|=128,f.sigBytes=4*g.length,this._process();for(var v=this._state,R=this.cfg.outputLength/8,_=R/8,y=[],A=0;A<_;A++){var w=v[A],E=w.high,C=w.low;E=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8),C=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8),y.push(C),y.push(E)}return new s.init(y,R)},clone:function(){for(var f=n.clone.call(this),g=f._state=this._state.slice(0),S=0;S<25;S++)g[S]=g[S].clone();return f}});t.SHA3=n._createHelper(u),t.HmacSHA3=n._createHmacHelper(u)}(Math),r.SHA3}(fe(),Hi())}($r)),$r.exports}var Wr,fo={exports:{}},zr,Kr={exports:{}};function us(){return zr||(zr=1,function(a){a.exports=function(r){var e,t,i;t=(e=r).lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(s,n){s=this._hasher=new s.init,typeof n=="string"&&(n=i.parse(n));var c=s.blockSize,o=4*c;n.sigBytes>o&&(n=s.finalize(n)),n.clamp();for(var l=this._oKey=n.clone(),d=this._iKey=n.clone(),h=l.words,p=d.words,u=0;u<c;u++)h[u]^=1549556828,p[u]^=909522486;l.sigBytes=d.sigBytes=o,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var n=this._hasher,c=n.finalize(s);return n.reset(),n.finalize(this._oKey.clone().concat(c))}})}(fe())}(Kr)),Kr.exports}var Jr,bo={exports:{}},Gr,qr={exports:{}};function Wt(){return Gr||(Gr=1,function(a){a.exports=function(r){return t=(e=r).lib,i=t.Base,s=t.WordArray,n=e.algo,c=n.MD5,o=n.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:c,iterations:1}),init:function(l){this.cfg=this.cfg.extend(l)},compute:function(l,d){for(var h,p=this.cfg,u=p.hasher.create(),f=s.create(),g=f.words,S=p.keySize,b=p.iterations;g.length<S;){h&&u.update(h),h=u.update(l).finalize(d),u.reset();for(var v=1;v<b;v++)h=u.finalize(h),u.reset();f.concat(h)}return f.sigBytes=4*S,f}}),e.EvpKDF=function(l,d,h){return o.create(h).compute(l,d)},r.EvpKDF;var e,t,i,s,n,c,o}(fe(),Nr(),us())}(qr)),qr.exports}var Xr,Yr={exports:{}};function Ge(){return Xr||(Xr=1,function(a){a.exports=function(r){r.lib.Cipher||function(e){var t=r,i=t.lib,s=i.Base,n=i.WordArray,c=i.BufferedBlockAlgorithm,o=t.enc;o.Utf8;var l=o.Base64,d=t.algo.EvpKDF,h=i.Cipher=c.extend({cfg:s.extend(),createEncryptor:function(y,A){return this.create(this._ENC_XFORM_MODE,y,A)},createDecryptor:function(y,A){return this.create(this._DEC_XFORM_MODE,y,A)},init:function(y,A,w){this.cfg=this.cfg.extend(w),this._xformMode=y,this._key=A,this.reset()},reset:function(){c.reset.call(this),this._doReset()},process:function(y){return this._append(y),this._process()},finalize:function(y){return y&&this._append(y),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function y(A){return typeof A=="string"?_:v}return function(A){return{encrypt:function(w,E,C){return y(E).encrypt(A,w,E,C)},decrypt:function(w,E,C){return y(E).decrypt(A,w,E,C)}}}}()});i.StreamCipher=h.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var p=t.mode={},u=i.BlockCipherMode=s.extend({createEncryptor:function(y,A){return this.Encryptor.create(y,A)},createDecryptor:function(y,A){return this.Decryptor.create(y,A)},init:function(y,A){this._cipher=y,this._iv=A}}),f=p.CBC=function(){var y=u.extend();function A(w,E,C){var P,D=this._iv;D?(P=D,this._iv=e):P=this._prevBlock;for(var U=0;U<C;U++)w[E+U]^=P[U]}return y.Encryptor=y.extend({processBlock:function(w,E){var C=this._cipher,P=C.blockSize;A.call(this,w,E,P),C.encryptBlock(w,E),this._prevBlock=w.slice(E,E+P)}}),y.Decryptor=y.extend({processBlock:function(w,E){var C=this._cipher,P=C.blockSize,D=w.slice(E,E+P);C.decryptBlock(w,E),A.call(this,w,E,P),this._prevBlock=D}}),y}(),g=(t.pad={}).Pkcs7={pad:function(y,A){for(var w=4*A,E=w-y.sigBytes%w,C=E<<24|E<<16|E<<8|E,P=[],D=0;D<E;D+=4)P.push(C);var U=n.create(P,E);y.concat(U)},unpad:function(y){var A=255&y.words[y.sigBytes-1>>>2];y.sigBytes-=A}};i.BlockCipher=h.extend({cfg:h.cfg.extend({mode:f,padding:g}),reset:function(){var y;h.reset.call(this);var A=this.cfg,w=A.iv,E=A.mode;this._xformMode==this._ENC_XFORM_MODE?y=E.createEncryptor:(y=E.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==y?this._mode.init(this,w&&w.words):(this._mode=y.call(E,this,w&&w.words),this._mode.__creator=y)},_doProcessBlock:function(y,A){this._mode.processBlock(y,A)},_doFinalize:function(){var y,A=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(A.pad(this._data,this.blockSize),y=this._process(!0)):(y=this._process(!0),A.unpad(y)),y},blockSize:4});var S=i.CipherParams=s.extend({init:function(y){this.mixIn(y)},toString:function(y){return(y||this.formatter).stringify(this)}}),b=(t.format={}).OpenSSL={stringify:function(y){var A=y.ciphertext,w=y.salt;return(w?n.create([1398893684,1701076831]).concat(w).concat(A):A).toString(l)},parse:function(y){var A,w=l.parse(y),E=w.words;return E[0]==1398893684&&E[1]==1701076831&&(A=n.create(E.slice(2,4)),E.splice(0,4),w.sigBytes-=16),S.create({ciphertext:w,salt:A})}},v=i.SerializableCipher=s.extend({cfg:s.extend({format:b}),encrypt:function(y,A,w,E){E=this.cfg.extend(E);var C=y.createEncryptor(w,E),P=C.finalize(A),D=C.cfg;return S.create({ciphertext:P,key:w,iv:D.iv,algorithm:y,mode:D.mode,padding:D.padding,blockSize:y.blockSize,formatter:E.format})},decrypt:function(y,A,w,E){return E=this.cfg.extend(E),A=this._parse(A,E.format),y.createDecryptor(w,E).finalize(A.ciphertext)},_parse:function(y,A){return typeof y=="string"?A.parse(y,this):y}}),R=(t.kdf={}).OpenSSL={execute:function(y,A,w,E,C){if(E||(E=n.random(8)),C)P=d.create({keySize:A+w,hasher:C}).compute(y,E);else var P=d.create({keySize:A+w}).compute(y,E);var D=n.create(P.words.slice(A),4*w);return P.sigBytes=4*A,S.create({key:P,iv:D,salt:E})}},_=i.PasswordBasedCipher=v.extend({cfg:v.cfg.extend({kdf:R}),encrypt:function(y,A,w,E){var C=(E=this.cfg.extend(E)).kdf.execute(w,y.keySize,y.ivSize,E.salt,E.hasher);E.iv=C.iv;var P=v.encrypt.call(this,y,A,C.key,E);return P.mixIn(C),P},decrypt:function(y,A,w,E){E=this.cfg.extend(E),A=this._parse(A,E.format);var C=E.kdf.execute(w,y.keySize,y.ivSize,A.salt,E.hasher);return E.iv=C.iv,v.decrypt.call(this,y,A,C.key,E)}})}()}(fe(),Wt())}(Yr)),Yr.exports}var Qr,Zr={exports:{}};function So(){return Qr||(Qr=1,function(a){a.exports=function(r){return r.mode.CFB=function(){var e=r.lib.BlockCipherMode.extend();function t(i,s,n,c){var o,l=this._iv;l?(o=l.slice(0),this._iv=void 0):o=this._prevBlock,c.encryptBlock(o,0);for(var d=0;d<n;d++)i[s+d]^=o[d]}return e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize;t.call(this,i,s,c,n),this._prevBlock=i.slice(s,s+c)}}),e.Decryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=i.slice(s,s+c);t.call(this,i,s,c,n),this._prevBlock=o}}),e}(),r.mode.CFB}(fe(),Ge())}(Zr)),Zr.exports}var ea,ta={exports:{}};function vo(){return ea||(ea=1,function(a){a.exports=function(r){return r.mode.CTR=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._counter;o&&(l=this._counter=o.slice(0),this._iv=void 0);var d=l.slice(0);n.encryptBlock(d,0),l[c-1]=l[c-1]+1|0;for(var h=0;h<c;h++)i[s+h]^=d[h]}}),e.Decryptor=t,e),r.mode.CTR;var e,t}(fe(),Ge())}(ta)),ta.exports}var ia,sa={exports:{}};function yo(){return ia||(ia=1,function(a){a.exports=function(r){return r.mode.CTRGladman=function(){var e=r.lib.BlockCipherMode.extend();function t(n){if(255&~(n>>24))n+=1<<24;else{var c=n>>16&255,o=n>>8&255,l=255&n;c===255?(c=0,o===255?(o=0,l===255?l=0:++l):++o):++c,n=0,n+=c<<16,n+=o<<8,n+=l}return n}function i(n){return(n[0]=t(n[0]))===0&&(n[1]=t(n[1])),n}var s=e.Encryptor=e.extend({processBlock:function(n,c){var o=this._cipher,l=o.blockSize,d=this._iv,h=this._counter;d&&(h=this._counter=d.slice(0),this._iv=void 0),i(h);var p=h.slice(0);o.encryptBlock(p,0);for(var u=0;u<l;u++)n[c+u]^=p[u]}});return e.Decryptor=s,e}(),r.mode.CTRGladman}(fe(),Ge())}(sa)),sa.exports}var ra,aa={exports:{}};function Ro(){return ra||(ra=1,function(a){a.exports=function(r){return r.mode.OFB=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._keystream;o&&(l=this._keystream=o.slice(0),this._iv=void 0),n.encryptBlock(l,0);for(var d=0;d<c;d++)i[s+d]^=l[d]}}),e.Decryptor=t,e),r.mode.OFB;var e,t}(fe(),Ge())}(aa)),aa.exports}var na,Ao={exports:{}},oa,wo={exports:{}},ca,_o={exports:{}},la,Io={exports:{}},da,Eo={exports:{}},ha,To={exports:{}},ua,Co={exports:{}},pa,ko={exports:{}},ma,ga={exports:{}};function Po(){return ma||(ma=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib,i=t.WordArray,s=t.BlockCipher,n=e.algo,c=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],l=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],h=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],p=n.DES=s.extend({_doReset:function(){for(var S=this._key.words,b=[],v=0;v<56;v++){var R=c[v]-1;b[v]=S[R>>>5]>>>31-R%32&1}for(var _=this._subKeys=[],y=0;y<16;y++){var A=_[y]=[],w=l[y];for(v=0;v<24;v++)A[v/6|0]|=b[(o[v]-1+w)%28]<<31-v%6,A[4+(v/6|0)]|=b[28+(o[v+24]-1+w)%28]<<31-v%6;for(A[0]=A[0]<<1|A[0]>>>31,v=1;v<7;v++)A[v]=A[v]>>>4*(v-1)+3;A[7]=A[7]<<5|A[7]>>>27}var E=this._invSubKeys=[];for(v=0;v<16;v++)E[v]=_[15-v]},encryptBlock:function(S,b){this._doCryptBlock(S,b,this._subKeys)},decryptBlock:function(S,b){this._doCryptBlock(S,b,this._invSubKeys)},_doCryptBlock:function(S,b,v){this._lBlock=S[b],this._rBlock=S[b+1],u.call(this,4,252645135),u.call(this,16,65535),f.call(this,2,858993459),f.call(this,8,16711935),u.call(this,1,1431655765);for(var R=0;R<16;R++){for(var _=v[R],y=this._lBlock,A=this._rBlock,w=0,E=0;E<8;E++)w|=d[E][((A^_[E])&h[E])>>>0];this._lBlock=A,this._rBlock=y^w}var C=this._lBlock;this._lBlock=this._rBlock,this._rBlock=C,u.call(this,1,1431655765),f.call(this,8,16711935),f.call(this,2,858993459),u.call(this,16,65535),u.call(this,4,252645135),S[b]=this._lBlock,S[b+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function u(S,b){var v=(this._lBlock>>>S^this._rBlock)&b;this._rBlock^=v,this._lBlock^=v<<S}function f(S,b){var v=(this._rBlock>>>S^this._lBlock)&b;this._lBlock^=v,this._rBlock^=v<<S}e.DES=s._createHelper(p);var g=n.TripleDES=s.extend({_doReset:function(){var S=this._key.words;if(S.length!==2&&S.length!==4&&S.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var b=S.slice(0,2),v=S.length<4?S.slice(0,2):S.slice(2,4),R=S.length<6?S.slice(0,2):S.slice(4,6);this._des1=p.createEncryptor(i.create(b)),this._des2=p.createEncryptor(i.create(v)),this._des3=p.createEncryptor(i.create(R))},encryptBlock:function(S,b){this._des1.encryptBlock(S,b),this._des2.decryptBlock(S,b),this._des3.encryptBlock(S,b)},decryptBlock:function(S,b){this._des3.decryptBlock(S,b),this._des2.encryptBlock(S,b),this._des1.decryptBlock(S,b)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=s._createHelper(g)}(),r.TripleDES}(fe(),ti(),ii(),Wt(),Ge())}(ga)),ga.exports}var fa,Do={exports:{}},ba,Mo={exports:{}},Sa,Lo={exports:{}},va,ya={exports:{}};function No(){return va||(va=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.BlockCipher,i=e.algo;const s=16,n=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],c=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function l(f,g){let S=g>>24&255,b=g>>16&255,v=g>>8&255,R=255&g,_=f.sbox[0][S]+f.sbox[1][b];return _^=f.sbox[2][v],_+=f.sbox[3][R],_}function d(f,g,S){let b,v=g,R=S;for(let _=0;_<s;++_)v^=f.pbox[_],R=l(f,v)^R,b=v,v=R,R=b;return b=v,v=R,R=b,R^=f.pbox[s],v^=f.pbox[s+1],{left:v,right:R}}function h(f,g,S){let b,v=g,R=S;for(let _=s+1;_>1;--_)v^=f.pbox[_],R=l(f,v)^R,b=v,v=R,R=b;return b=v,v=R,R=b,R^=f.pbox[1],v^=f.pbox[0],{left:v,right:R}}function p(f,g,S){for(let y=0;y<4;y++){f.sbox[y]=[];for(let A=0;A<256;A++)f.sbox[y][A]=c[y][A]}let b=0;for(let y=0;y<s+2;y++)f.pbox[y]=n[y]^g[b],b++,b>=S&&(b=0);let v=0,R=0,_=0;for(let y=0;y<s+2;y+=2)_=d(f,v,R),v=_.left,R=_.right,f.pbox[y]=v,f.pbox[y+1]=R;for(let y=0;y<4;y++)for(let A=0;A<256;A+=2)_=d(f,v,R),v=_.left,R=_.right,f.sbox[y][A]=v,f.sbox[y][A+1]=R;return!0}var u=i.Blowfish=t.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,g=f.words,S=f.sigBytes/4;p(o,g,S)}},encryptBlock:function(f,g){var S=d(o,f[g],f[g+1]);f[g]=S.left,f[g+1]=S.right},decryptBlock:function(f,g){var S=h(o,f[g],f[g+1]);f[g]=S.left,f[g+1]=S.right},blockSize:2,keySize:4,ivSize:2});e.Blowfish=t._createHelper(u)}(),r.Blowfish}(fe(),ti(),ii(),Wt(),Ge())}(ya)),ya.exports}(function(a){a.exports=function(r){return r}(fe(),Hi(),lo(),ho(),ti(),uo(),ii(),Nr(),hs(),Or||(Or=1,function(r){r.exports=function(e){return i=(t=e).lib.WordArray,s=t.algo,n=s.SHA256,c=s.SHA224=n.extend({_doReset:function(){this._hash=new i.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=n._doFinalize.call(this);return o.sigBytes-=4,o}}),t.SHA224=n._createHelper(c),t.HmacSHA224=n._createHmacHelper(c),e.SHA224;var t,i,s,n,c}(fe(),hs())}(po)),Hr(),Fr||(Fr=1,function(r){r.exports=function(e){return i=(t=e).x64,s=i.Word,n=i.WordArray,c=t.algo,o=c.SHA512,l=c.SHA384=o.extend({_doReset:function(){this._hash=new n.init([new s.init(3418070365,3238371032),new s.init(1654270250,914150663),new s.init(2438529370,812702999),new s.init(355462360,4144912697),new s.init(1731405415,4290775857),new s.init(2394180231,1750603025),new s.init(3675008525,1694076839),new s.init(1203062813,3204075428)])},_doFinalize:function(){var d=o._doFinalize.call(this);return d.sigBytes-=16,d}}),t.SHA384=o._createHelper(l),t.HmacSHA384=o._createHmacHelper(l),e.SHA384;var t,i,s,n,c,o,l}(fe(),Hi(),Hr())}(mo)),go(),Wr||(Wr=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=s.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),l=s.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),d=s.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),h=s.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),p=s.create([0,1518500249,1859775393,2400959708,2840853838]),u=s.create([1352829926,1548603684,1836072691,2053994217,0]),f=c.RIPEMD160=n.extend({_doReset:function(){this._hash=s.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(y,A){for(var w=0;w<16;w++){var E=A+w,C=y[E];y[E]=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8)}var P,D,U,G,Y,q,W,Z,te,be,L,x=this._hash.words,N=p.words,V=u.words,ue=o.words,Le=l.words,J=d.words,ve=h.words;for(q=P=x[0],W=D=x[1],Z=U=x[2],te=G=x[3],be=Y=x[4],w=0;w<80;w+=1)L=P+y[A+ue[w]]|0,L+=w<16?g(D,U,G)+N[0]:w<32?S(D,U,G)+N[1]:w<48?b(D,U,G)+N[2]:w<64?v(D,U,G)+N[3]:R(D,U,G)+N[4],L=(L=_(L|=0,J[w]))+Y|0,P=Y,Y=G,G=_(U,10),U=D,D=L,L=q+y[A+Le[w]]|0,L+=w<16?R(W,Z,te)+V[0]:w<32?v(W,Z,te)+V[1]:w<48?b(W,Z,te)+V[2]:w<64?S(W,Z,te)+V[3]:g(W,Z,te)+V[4],L=(L=_(L|=0,ve[w]))+be|0,q=be,be=te,te=_(Z,10),Z=W,W=L;L=x[1]+U+te|0,x[1]=x[2]+G+be|0,x[2]=x[3]+Y+q|0,x[3]=x[4]+P+W|0,x[4]=x[0]+D+Z|0,x[0]=L},_doFinalize:function(){var y=this._data,A=y.words,w=8*this._nDataBytes,E=8*y.sigBytes;A[E>>>5]|=128<<24-E%32,A[14+(E+64>>>9<<4)]=16711935&(w<<8|w>>>24)|4278255360&(w<<24|w>>>8),y.sigBytes=4*(A.length+1),this._process();for(var C=this._hash,P=C.words,D=0;D<5;D++){var U=P[D];P[D]=16711935&(U<<8|U>>>24)|4278255360&(U<<24|U>>>8)}return C},clone:function(){var y=n.clone.call(this);return y._hash=this._hash.clone(),y}});function g(y,A,w){return y^A^w}function S(y,A,w){return y&A|~y&w}function b(y,A,w){return(y|~A)^w}function v(y,A,w){return y&w|A&~w}function R(y,A,w){return y^(A|~w)}function _(y,A){return y<<A|y>>>32-A}t.RIPEMD160=n._createHelper(f),t.HmacRIPEMD160=n._createHmacHelper(f)}(),e.RIPEMD160}(fe())}(fo)),us(),Jr||(Jr=1,function(r){r.exports=function(e){return s=(i=(t=e).lib).Base,n=i.WordArray,o=(c=t.algo).SHA256,l=c.HMAC,d=c.PBKDF2=s.extend({cfg:s.extend({keySize:4,hasher:o,iterations:25e4}),init:function(h){this.cfg=this.cfg.extend(h)},compute:function(h,p){for(var u=this.cfg,f=l.create(u.hasher,h),g=n.create(),S=n.create([1]),b=g.words,v=S.words,R=u.keySize,_=u.iterations;b.length<R;){var y=f.update(p).finalize(S);f.reset();for(var A=y.words,w=A.length,E=y,C=1;C<_;C++){E=f.finalize(E),f.reset();for(var P=E.words,D=0;D<w;D++)A[D]^=P[D]}g.concat(y),v[0]++}return g.sigBytes=4*R,g}}),t.PBKDF2=function(h,p,u){return d.create(u).compute(h,p)},e.PBKDF2;var t,i,s,n,c,o,l,d}(fe(),hs(),us())}(bo)),Wt(),Ge(),So(),vo(),yo(),Ro(),na||(na=1,function(r){r.exports=function(e){return e.mode.ECB=((t=e.lib.BlockCipherMode.extend()).Encryptor=t.extend({processBlock:function(i,s){this._cipher.encryptBlock(i,s)}}),t.Decryptor=t.extend({processBlock:function(i,s){this._cipher.decryptBlock(i,s)}}),t),e.mode.ECB;var t}(fe(),Ge())}(Ao)),oa||(oa=1,function(r){r.exports=function(e){return e.pad.AnsiX923={pad:function(t,i){var s=t.sigBytes,n=4*i,c=n-s%n,o=s+c-1;t.clamp(),t.words[o>>>2]|=c<<24-o%4*8,t.sigBytes+=c},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Ansix923}(fe(),Ge())}(wo)),ca||(ca=1,function(r){r.exports=function(e){return e.pad.Iso10126={pad:function(t,i){var s=4*i,n=s-t.sigBytes%s;t.concat(e.lib.WordArray.random(n-1)).concat(e.lib.WordArray.create([n<<24],1))},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Iso10126}(fe(),Ge())}(_o)),la||(la=1,function(r){r.exports=function(e){return e.pad.Iso97971={pad:function(t,i){t.concat(e.lib.WordArray.create([2147483648],1)),e.pad.ZeroPadding.pad(t,i)},unpad:function(t){e.pad.ZeroPadding.unpad(t),t.sigBytes--}},e.pad.Iso97971}(fe(),Ge())}(Io)),da||(da=1,function(r){r.exports=function(e){return e.pad.ZeroPadding={pad:function(t,i){var s=4*i;t.clamp(),t.sigBytes+=s-(t.sigBytes%s||s)},unpad:function(t){var i=t.words,s=t.sigBytes-1;for(s=t.sigBytes-1;s>=0;s--)if(i[s>>>2]>>>24-s%4*8&255){t.sigBytes=s+1;break}}},e.pad.ZeroPadding}(fe(),Ge())}(Eo)),ha||(ha=1,function(r){r.exports=function(e){return e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding}(fe(),Ge())}(To)),ua||(ua=1,function(r){r.exports=function(e){return i=(t=e).lib.CipherParams,s=t.enc.Hex,t.format.Hex={stringify:function(n){return n.ciphertext.toString(s)},parse:function(n){var c=s.parse(n);return i.create({ciphertext:c})}},e.format.Hex;var t,i,s}(fe(),Ge())}(Co)),pa||(pa=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,s=t.algo,n=[],c=[],o=[],l=[],d=[],h=[],p=[],u=[],f=[],g=[];(function(){for(var v=[],R=0;R<256;R++)v[R]=R<128?R<<1:R<<1^283;var _=0,y=0;for(R=0;R<256;R++){var A=y^y<<1^y<<2^y<<3^y<<4;A=A>>>8^255&A^99,n[_]=A,c[A]=_;var w=v[_],E=v[w],C=v[E],P=257*v[A]^16843008*A;o[_]=P<<24|P>>>8,l[_]=P<<16|P>>>16,d[_]=P<<8|P>>>24,h[_]=P,P=16843009*C^65537*E^257*w^16843008*_,p[A]=P<<24|P>>>8,u[A]=P<<16|P>>>16,f[A]=P<<8|P>>>24,g[A]=P,_?(_=w^v[v[v[C^w]]],y^=v[v[y]]):_=y=1}})();var S=[0,1,2,4,8,16,32,64,128,27,54],b=s.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var v=this._keyPriorReset=this._key,R=v.words,_=v.sigBytes/4,y=4*((this._nRounds=_+6)+1),A=this._keySchedule=[],w=0;w<y;w++)w<_?A[w]=R[w]:(P=A[w-1],w%_?_>6&&w%_==4&&(P=n[P>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P]):(P=n[(P=P<<8|P>>>24)>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P],P^=S[w/_|0]<<24),A[w]=A[w-_]^P);for(var E=this._invKeySchedule=[],C=0;C<y;C++){if(w=y-C,C%4)var P=A[w];else P=A[w-4];E[C]=C<4||w<=4?P:p[n[P>>>24]]^u[n[P>>>16&255]]^f[n[P>>>8&255]]^g[n[255&P]]}}},encryptBlock:function(v,R){this._doCryptBlock(v,R,this._keySchedule,o,l,d,h,n)},decryptBlock:function(v,R){var _=v[R+1];v[R+1]=v[R+3],v[R+3]=_,this._doCryptBlock(v,R,this._invKeySchedule,p,u,f,g,c),_=v[R+1],v[R+1]=v[R+3],v[R+3]=_},_doCryptBlock:function(v,R,_,y,A,w,E,C){for(var P=this._nRounds,D=v[R]^_[0],U=v[R+1]^_[1],G=v[R+2]^_[2],Y=v[R+3]^_[3],q=4,W=1;W<P;W++){var Z=y[D>>>24]^A[U>>>16&255]^w[G>>>8&255]^E[255&Y]^_[q++],te=y[U>>>24]^A[G>>>16&255]^w[Y>>>8&255]^E[255&D]^_[q++],be=y[G>>>24]^A[Y>>>16&255]^w[D>>>8&255]^E[255&U]^_[q++],L=y[Y>>>24]^A[D>>>16&255]^w[U>>>8&255]^E[255&G]^_[q++];D=Z,U=te,G=be,Y=L}Z=(C[D>>>24]<<24|C[U>>>16&255]<<16|C[G>>>8&255]<<8|C[255&Y])^_[q++],te=(C[U>>>24]<<24|C[G>>>16&255]<<16|C[Y>>>8&255]<<8|C[255&D])^_[q++],be=(C[G>>>24]<<24|C[Y>>>16&255]<<16|C[D>>>8&255]<<8|C[255&U])^_[q++],L=(C[Y>>>24]<<24|C[D>>>16&255]<<16|C[U>>>8&255]<<8|C[255&G])^_[q++],v[R]=Z,v[R+1]=te,v[R+2]=be,v[R+3]=L},keySize:8});t.AES=i._createHelper(b)}(),e.AES}(fe(),ti(),ii(),Wt(),Ge())}(ko)),Po(),fa||(fa=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=s.RC4=i.extend({_doReset:function(){for(var l=this._key,d=l.words,h=l.sigBytes,p=this._S=[],u=0;u<256;u++)p[u]=u;u=0;for(var f=0;u<256;u++){var g=u%h,S=d[g>>>2]>>>24-g%4*8&255;f=(f+p[u]+S)%256;var b=p[u];p[u]=p[f],p[f]=b}this._i=this._j=0},_doProcessBlock:function(l,d){l[d]^=c.call(this)},keySize:8,ivSize:0});function c(){for(var l=this._S,d=this._i,h=this._j,p=0,u=0;u<4;u++){h=(h+l[d=(d+1)%256])%256;var f=l[d];l[d]=l[h],l[h]=f,p|=l[(l[d]+l[h])%256]<<24-8*u}return this._i=d,this._j=h,p}t.RC4=i._createHelper(n);var o=s.RC4Drop=n.extend({cfg:n.cfg.extend({drop:192}),_doReset:function(){n._doReset.call(this);for(var l=this.cfg.drop;l>0;l--)c.call(this)}});t.RC4Drop=i._createHelper(o)}(),e.RC4}(fe(),ti(),ii(),Wt(),Ge())}(Do)),ba||(ba=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=[],c=[],o=[],l=s.Rabbit=i.extend({_doReset:function(){for(var h=this._key.words,p=this.cfg.iv,u=0;u<4;u++)h[u]=16711935&(h[u]<<8|h[u]>>>24)|4278255360&(h[u]<<24|h[u]>>>8);var f=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],g=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];for(this._b=0,u=0;u<4;u++)d.call(this);for(u=0;u<8;u++)g[u]^=f[u+4&7];if(p){var S=p.words,b=S[0],v=S[1],R=16711935&(b<<8|b>>>24)|4278255360&(b<<24|b>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,A=_<<16|65535&R;for(g[0]^=R,g[1]^=y,g[2]^=_,g[3]^=A,g[4]^=R,g[5]^=y,g[6]^=_,g[7]^=A,u=0;u<4;u++)d.call(this)}},_doProcessBlock:function(h,p){var u=this._X;d.call(this),n[0]=u[0]^u[5]>>>16^u[3]<<16,n[1]=u[2]^u[7]>>>16^u[5]<<16,n[2]=u[4]^u[1]>>>16^u[7]<<16,n[3]=u[6]^u[3]>>>16^u[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),h[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var h=this._X,p=this._C,u=0;u<8;u++)c[u]=p[u];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,u=0;u<8;u++){var f=h[u]+p[u],g=65535&f,S=f>>>16,b=((g*g>>>17)+g*S>>>15)+S*S,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[u]=b^v}h[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,h[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,h[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,h[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,h[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,h[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,h[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,h[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.Rabbit=i._createHelper(l)}(),e.Rabbit}(fe(),ti(),ii(),Wt(),Ge())}(Mo)),Sa||(Sa=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=[],c=[],o=[],l=s.RabbitLegacy=i.extend({_doReset:function(){var h=this._key.words,p=this.cfg.iv,u=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],f=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];this._b=0;for(var g=0;g<4;g++)d.call(this);for(g=0;g<8;g++)f[g]^=u[g+4&7];if(p){var S=p.words,b=S[0],v=S[1],R=16711935&(b<<8|b>>>24)|4278255360&(b<<24|b>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,A=_<<16|65535&R;for(f[0]^=R,f[1]^=y,f[2]^=_,f[3]^=A,f[4]^=R,f[5]^=y,f[6]^=_,f[7]^=A,g=0;g<4;g++)d.call(this)}},_doProcessBlock:function(h,p){var u=this._X;d.call(this),n[0]=u[0]^u[5]>>>16^u[3]<<16,n[1]=u[2]^u[7]>>>16^u[5]<<16,n[2]=u[4]^u[1]>>>16^u[7]<<16,n[3]=u[6]^u[3]>>>16^u[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),h[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var h=this._X,p=this._C,u=0;u<8;u++)c[u]=p[u];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,u=0;u<8;u++){var f=h[u]+p[u],g=65535&f,S=f>>>16,b=((g*g>>>17)+g*S>>>15)+S*S,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[u]=b^v}h[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,h[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,h[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,h[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,h[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,h[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,h[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,h[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.RabbitLegacy=i._createHelper(l)}(),e.RabbitLegacy}(fe(),ti(),ii(),Wt(),Ge())}(Lo)),No())})(br);const si=no(br.exports);function xo(a){return r=this,e=null,t=function*(){const i=new Date;if(a.refreshSTSTokenInterval||(a.refreshSTSTokenInterval=3e5),!a.stsTokenFreshTime||+i-a.stsTokenFreshTime>=a.refreshSTSTokenInterval){a.stsTokenFreshTime=i;try{yield a.refreshSTSToken()}catch(s){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
5
+ `+s)}}return null},new Promise((i,s)=>{var n=l=>{try{o(t.next(l))}catch(d){s(d)}},c=l=>{try{o(t.throw(l))}catch(d){s(d)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,c);o((t=t.apply(r,e)).next())});var r,e,t}function ps(a){return{transString:function(r){let e={},t=0,i=!1;for(let s in r)s!=="time"&&s!=="__time__"||typeof r[s]!="number"?typeof r[s]=="object"?e[s]=JSON.stringify(r[s]):e[s]=String(r[s]):(t=r[s],i=!0);return e.__time__=i?t:Math.floor(new Date().getTime()/1e3),e},process:function(r,e){return t=this,i=null,s=function*(){yield xo(a);let n=r.slice(r.indexOf("/logstores")),c=e.length,o=(l=e,si.MD5(l).toString().toUpperCase());var l;let d=new Date().toUTCString(),h=new Map,p=new Map([["Content-Type","application/json"],["Content-MD5",o],["x-log-bodyrawsize",c.toString()]]);a.securityToken&&p.set("x-acs-security-token",a.securityToken),function(f,g,S,b,v,R,_,y){var A;let w="";R.set("x-log-apiversion","0.6.0"),R.set("x-log-signaturemethod","hmac-sha1"),w+=f+`
6
6
  `+_+`
7
7
  `+((A=R.get("Content-Type"))!=null?A:"")+`
8
8
  `+y+`
9
- `;const T=(D,U)=>D[0].localeCompare(U[0]),I=D=>D[0].startsWith("x-log-")||D[0].startsWith("x-acs-");try{const D=[...R.entries()].filter(I).sort(T).map(U=>U[0]+":"+U[1]+`
10
- `).join("");w+=D}catch(D){}w+=g,v.size>0&&(w+="?");try{w+=[...v.entries()].sort(T).map(D=>D[0]+"="+D[1]).join("&")}catch(D){}const P="LOG "+S+":"+Gt.HmacSHA1(w,b).toString(Gt.enc.Base64);R.set("Authorization",P),R.set("x-log-date",y)}("POST",n,a.accessKeyId,a.accessKeySecret,u,p,o,d);let h=Object.fromEntries(p);return{data:e,header:h}},new Promise((n,c)=>{var o=u=>{try{d(r.next(u))}catch(p){c(p)}},l=u=>{try{d(r.throw(u))}catch(p){c(p)}},d=u=>u.done?n(u.value):Promise.resolve(u.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}}}typeof window!="undefined"&&ns(window,"stsPlugin",ar);var Eo=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,To=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,Io=/[^-+\dA-Z]/g;function Ni(a,s,e,t){if(arguments.length!==1||typeof a!="string"||/\d/.test(a)||(s=a,a=void 0),(a=a||a===0?a:new Date)instanceof Date||(a=new Date(a)),isNaN(a))throw TypeError("Invalid date");var i=(s=String(ua[s]||s||ua.default)).slice(0,4);i!=="UTC:"&&i!=="GMT:"||(s=s.slice(4),e=!0,i==="GMT:"&&(t=!0));var r=function(){return e?"getUTC":"get"},n=function(){return a[r()+"Date"]()},c=function(){return a[r()+"Day"]()},o=function(){return a[r()+"Month"]()},l=function(){return a[r()+"FullYear"]()},d=function(){return a[r()+"Hours"]()},u=function(){return a[r()+"Minutes"]()},p=function(){return a[r()+"Seconds"]()},h=function(){return a[r()+"Milliseconds"]()},f=function(){return e?0:a.getTimezoneOffset()},g=function(){return Co(a)},S={d:function(){return n()},dd:function(){return ut(n())},ddd:function(){return st.dayNames[c()]},DDD:function(){return ha({y:l(),m:o(),d:n(),_:r(),dayName:st.dayNames[c()],short:!0})},dddd:function(){return st.dayNames[c()+7]},DDDD:function(){return ha({y:l(),m:o(),d:n(),_:r(),dayName:st.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return ut(o()+1)},mmm:function(){return st.monthNames[o()]},mmmm:function(){return st.monthNames[o()+12]},yy:function(){return String(l()).slice(2)},yyyy:function(){return ut(l(),4)},h:function(){return d()%12||12},hh:function(){return ut(d()%12||12)},H:function(){return d()},HH:function(){return ut(d())},M:function(){return u()},MM:function(){return ut(u())},s:function(){return p()},ss:function(){return ut(p())},l:function(){return ut(h(),3)},L:function(){return ut(Math.floor(h()/10))},t:function(){return d()<12?st.timeNames[0]:st.timeNames[1]},tt:function(){return d()<12?st.timeNames[2]:st.timeNames[3]},T:function(){return d()<12?st.timeNames[4]:st.timeNames[5]},TT:function(){return d()<12?st.timeNames[6]:st.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":Po(a)},o:function(){return(f()>0?"-":"+")+ut(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+ut(Math.floor(Math.abs(f())/60),2)+":"+ut(Math.floor(Math.abs(f())%60),2)},S:function(){return["th","st","nd","rd"][n()%10>3?0:(n()%100-n()%10!=10)*n()%10]},W:function(){return g()},WW:function(){return ut(g())},N:function(){return ko(a)}};return s.replace(Eo,function(b){return b in S?S[b]():b.slice(1,b.length-1)})}var ua={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},st={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},ut=function(a){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(a).padStart(s,"0")},ha=function(a){var s=a.y,e=a.m,t=a.d,i=a._,r=a.dayName,n=a.short,c=n!==void 0&&n,o=new Date,l=new Date;l.setDate(l[i+"Date"]()-1);var d=new Date;return d.setDate(d[i+"Date"]()+1),o[i+"FullYear"]()===s&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":l[i+"FullYear"]()===s&&l[i+"Month"]()===e&&l[i+"Date"]()===t?c?"Ysd":"Yesterday":d[i+"FullYear"]()===s&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Tmw":"Tomorrow":r},Co=function(a){var s=new Date(a.getFullYear(),a.getMonth(),a.getDate());s.setDate(s.getDate()-(s.getDay()+6)%7+3);var e=new Date(s.getFullYear(),0,4);e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=s.getTimezoneOffset()-e.getTimezoneOffset();s.setHours(s.getHours()-t);var i=(s-e)/6048e5;return 1+Math.floor(i)},ko=function(a){var s=a.getDay();return s===0&&(s=7),s},Po=function(a){return(String(a).match(To)||[""]).pop().replace(Io,"").replace(/GMT\+0000/g,"UTC")};const{BrowserUtil:Do}=J.AliRTS,Mo="EdgeHTML",pa="Blink",No="Trident",Lo="Gecko",xo="WebKit",Li=(a,s)=>{const e=s.match(a);return e&&e.length>0&&e[1]||""},Oo=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(a){if(/\sedg\//i.test(a))return{name:pa};const s=Li(/edge\/(\d+(\.?_?\d+)+)/i,a);return{name:Mo,version:s}}},{test:[/trident/i],describe(a){const s={name:No},e=Li(/trident\/(\d+(\.?_?\d+)+)/i,a);return e&&(s.version=e),s}},{test(a){const s=/gecko/i.test(a),e=/like gecko/i.test(a);return s&&!e},describe(a){const s={name:Lo},e=Li(/gecko\/(\d+(\.?_?\d+)+)/i,a);return e&&(s.version=e),s}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:pa})},{test:[/(apple)?webkit/i],describe(a){const s={name:xo},e=Li(/webkit\/(\d+(\.?_?\d+)+)/i,a);return e&&(s.version=e),s}}],nr=(a,s)=>a.find(e=>typeof e.test=="function"?e.test(s):Array.isArray(e.test)?e.test.some(t=>typeof t=="string"?s.indexOf(t)>-1:t instanceof RegExp&&t.test(s)):void 0),Vo=()=>{try{const a=navigator.userAgent||"",s=nr(Oo,a);if(s){const e=s.describe(a);return`${e.name}/${e.version||Do.browserVersion}`}}catch(a){}return navigator.userAgent},Uo=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],ma=()=>{let a="unknown";try{const s=navigator.userAgent||"",e=nr(Uo,s);if(!e)return a;a=e.describe(s)}catch(s){}return a},Bo=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],Ho=()=>{let a="Unknown";try{const s=navigator.userAgent||"",e=nr(Bo,s);if(!e)return a;a=e.describe(s)}catch(s){}return a};class ga{constructor(s){var e,t;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(e=s.time)!=null?e:10,this.count=(t=s.count)!=null?t:10,s.host.startsWith("http://")||s.host.startsWith("https://")?this.url=s.host+"/logstores/"+s.logstore+"/track":this.url="https://"+s.project+"."+s.host+"/logstores/"+s.logstore+"/track",this.opt=s,s.installUnloadHook&&typeof s.installUnloadHook=="function"&&s.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(s){const e={__logs__:s};return this.opt.tags&&(e.__tags__=this.opt.tags),this.opt.topic&&(e.__topic__=this.opt.topic),this.opt.source&&(e.__source__=this.opt.source),JSON.stringify(e)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const s=this.assemblePayload(this.arr);this.opt.sendPayload(this.url,s)}}transString(s){let e={};for(let t in s)typeof s[t]=="object"?e[t]=JSON.stringify(s[t]):e[t]=String(s[t]);return e}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const s=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){s.sendImmediateInner()},1e3*this.time)}}send(s){const e=this.transString(s);this.arr.push(e),this.sendInner()}sendImmediate(s){const e=this.transString(s);this.arr.push(e),this.sendImmediateInner()}sendBatchLogs(s){const e=s.map(t=>this.transString(t));this.arr.push(...e),this.sendInner()}sendBatchLogsImmediate(s){const e=s.map(t=>this.transString(t));this.arr.push(...e),this.sendImmediateInner()}overwriteTransString(s){this.transString=s.transString}getOpt(){return this.opt}}function fa(a,s){return new Promise((e,t)=>{const i=new window.XMLHttpRequest;i.onload=()=>{i.status>=200&&i.status<300?e():t(new Error(`HTTP ${i.status}: ${i.statusText}`))},i.onerror=()=>{t(new Error("Network error occurred"))},i.ontimeout=()=>{t(new Error("Request timeout"))},i.timeout=1e4,i.open("POST",`${a}?APIVersion=0.6.0`,!0),i.send(s)})}function Fo(a,s,e=!1){return E(this,null,function*(){try{if(e||s.length>=32768)return void(yield fa(a,s));(function(t,i){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,i)})(a,s)||(yield fa(a,s))}catch(t){const i=t instanceof Error?t:new Error(String(t));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
11
- `+i.message),console.error("Failed log data:",a)),i}})}let jo=class extends ga{constructor(s){const f=s,{maxRetries:e=10,retryDelay:t=2e3,backoffMultiplier:i=2,maxRetryDelay:r=3e5,enableLocalStorage:n=!0,maxStorageSize:c=1e3,storageKey:o="artc_reliable_logs",enableNetworkMonitor:l=!0,onNetworkChange:d=()=>{},forceXhrMode:u=!0,debug:p=!1}=f,h=Ot(f,["maxRetries","retryDelay","backoffMultiplier","maxRetryDelay","enableLocalStorage","maxStorageSize","storageKey","enableNetworkMonitor","onNetworkChange","forceXhrMode","debug"]);super(Object.assign({},h,{installUnloadHook:g=>{window.addEventListener("beforeunload",()=>{this.saveFailedLogs(),g()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.saveFailedLogs()})},sendPayload:(g,S)=>E(this,null,function*(){return Promise.resolve()})}));m(this,"reliableConfig");m(this,"failedLogs",new Map);m(this,"networkStatus","online");m(this,"retryTimer",null);m(this,"originalSendPayload",null);this.reliableConfig={maxRetries:e,retryDelay:t,backoffMultiplier:i,maxRetryDelay:r,enableLocalStorage:n,maxStorageSize:c,storageKey:o,enableNetworkMonitor:l,onNetworkChange:d,forceXhrMode:u,debug:p},this.originalSendPayload=(g,S)=>E(this,null,function*(){return Fo(g,S,u)}),this.getOpt().sendPayload=(g,S)=>E(this,null,function*(){return this.reliableSendAsync(g,S)}),this.initNetworkMonitor(),this.loadFailedLogs(),this.startRetryTimer()}reliableSendAsync(s,e){return E(this,null,function*(){const t=this.generateId();try{yield Promise.resolve(this.originalSendPayload(s,e)),this.debug(`Log ${t} sent successfully`)}catch(i){this.debug(`Log ${t} failed, adding to retry queue:`,i),this.addToFailedQueue(t,s,e,i)}})}addToFailedQueue(s,e,t,i){const r={id:s,data:{error:i.message},timestamp:Date.now(),retryCount:0,lastRetryTime:0,url:e,payload:t};this.failedLogs.set(s,r),this.scheduleRetry(r)}scheduleRetry(s){if(s.retryCount>=this.reliableConfig.maxRetries)return this.debug(`Log ${s.id} exceeded max retries, removing from queue`),void this.failedLogs.delete(s.id);const e=Math.min(this.reliableConfig.retryDelay*Math.pow(this.reliableConfig.backoffMultiplier,s.retryCount),this.reliableConfig.maxRetryDelay);this.debug(`Scheduling retry for log ${s.id} in ${e}ms (attempt ${s.retryCount+1}/${this.reliableConfig.maxRetries})`),setTimeout(()=>{this.retryLog(s)},e)}retryLog(s){return E(this,null,function*(){if(this.failedLogs.has(s.id)){s.retryCount++,s.lastRetryTime=Date.now();try{if(this.networkStatus==="offline")return this.debug(`Log ${s.id} retry skipped - network offline`),void this.scheduleRetry(s);yield this.originalSendPayload(s.url,s.payload),this.debug(`Log ${s.id} retry successful`),this.failedLogs.delete(s.id)}catch(e){this.debug(`Log ${s.id} retry failed:`,e),this.scheduleRetry(s)}}})}initNetworkMonitor(){this.reliableConfig.enableNetworkMonitor&&typeof window!="undefined"&&(this.networkStatus=navigator.onLine?"online":"offline",window.addEventListener("online",()=>{this.handleNetworkChange("online")}),window.addEventListener("offline",()=>{this.handleNetworkChange("offline")}),this.debug(`Network monitor initialized. Current status: ${this.networkStatus}`))}handleNetworkChange(s){const e=this.networkStatus;this.networkStatus=s,this.debug(`Network status changed: ${e} -> ${s}`),this.reliableConfig.onNetworkChange(s==="online"),s==="online"&&e==="offline"&&(this.debug("Network recovered, retrying failed logs"),this.retryAllFailedLogs())}retryAllFailedLogs(){this.failedLogs.size!==0&&(this.debug(`Retrying ${this.failedLogs.size} failed logs after network recovery`),Array.from(this.failedLogs.values()).forEach(s=>{setTimeout(()=>this.retryLog(s),100*Math.random())}))}startRetryTimer(){typeof window!="undefined"&&(this.retryTimer=window.setInterval(()=>{if(this.failedLogs.size>0&&this.networkStatus==="online"){const s=Date.now();Array.from(this.failedLogs.values()).forEach(e=>{s-e.lastRetryTime>this.reliableConfig.retryDelay&&this.retryLog(e)})}},this.reliableConfig.retryDelay),this.debug(`Retry timer started with interval ${this.reliableConfig.retryDelay}ms`))}loadFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined")try{const s=localStorage.getItem(this.reliableConfig.storageKey);if(s){const e=JSON.parse(s);e.forEach(t=>{this.failedLogs.set(t.id,t)}),this.debug(`Loaded ${e.length} failed logs from storage`),localStorage.removeItem(this.reliableConfig.storageKey),this.networkStatus==="online"&&this.retryAllFailedLogs()}}catch(s){this.debug("Failed to load failed logs from storage:",s)}}saveFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined"&&this.failedLogs.size!==0)try{const s=Array.from(this.failedLogs.values()).slice(-this.reliableConfig.maxStorageSize);localStorage.setItem(this.reliableConfig.storageKey,JSON.stringify(s)),this.debug(`Saved ${s.length} failed logs to storage`)}catch(s){this.debug("Failed to save failed logs to storage:",s)}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}debug(...s){this.reliableConfig.debug&&typeof console!="undefined"&&console.log("[ReliableWebTracker]",...s)}useStsPlugin(s){this.originalSendPayload=(e,t)=>E(this,null,function*(){return function(i,r,n){return E(this,null,function*(){try{i=i.slice(0,-6);const{data:c,header:o}=yield n.process(i,r);return new Promise((l,d)=>{const u=new window.XMLHttpRequest;u.onload=()=>{u.status>=200&&u.status<300?l():d(new Error(`HTTP ${u.status}: ${u.statusText}`))},u.onerror=()=>{d(new Error("Network error occurred"))},u.ontimeout=()=>{d(new Error("Request timeout"))},u.timeout=1e4,u.open("POST",i,!0);for(let p in o)u.setRequestHeader(p,o[p]);u.send(c)})}catch(c){const o=c instanceof Error?c:new Error(String(c));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
12
- `+o.message),console.error("Failed log data:",i)),o}})}(e,t,s)}),this.getOpt().sendPayload=(e,t)=>E(this,null,function*(){return this.reliableSendAsync(e,t)}),this.overwriteTransString(s)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const s=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${s} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),this.debug("WebTrackerBrowser destroyed")}};const{BrowserUtil:Sa,SystenUtil:ba}=J.AliRTS,$o=ma(),xi=6e5,va={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10},ya={host:"ap-southeast-1.log.aliyuncs.com",project:"alivc-aio-sgp",logstore:"logger",time:10,count:10};function or(){return Ni(new Date,"HH:MM:ss.l")}function Ra(){return Ni(new Date,"isoDate")}var cr=(a=>(a[a.DEBUG=0]="DEBUG",a[a.INFO=1]="INFO",a[a.API=2]="API",a[a.WARNING=3]="WARNING",a[a.ERROR=4]="ERROR",a[a.NONE=5]="NONE",a))(cr||{});class Wo{constructor(){m(this,"tracker");m(this,"stsPlugin");m(this,"stsData");m(this,"stsExpiration",Date.now());m(this,"clientId",dt());m(this,"bSesid",dt());m(this,"logLevel",3);m(this,"appId","");m(this,"sessionId","");m(this,"logCache",[]);m(this,"updateTaskTimer");m(this,"endReported",!0);m(this,"logSequence",0);m(this,"globalEnv","DEFAULT");m(this,"sendLogBeforeUnload",s=>E(this,null,function*(){if(!this.stsPlugin)return;this.logSequence+=1,s.unshift(this.getLogParams(710203,{log:`[${Ra()} ${or()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=this.globalEnv==="SEA"?ya:va,t=`https://${e.project}.${e.host}/logstores/${e.logstore}`,i={__logs__:s.map(c=>this.stsPlugin.transString(c))},{data:r,header:n}=yield this.stsPlugin.process(t,JSON.stringify(i));fetch(t,{keepalive:!0,method:"POST",headers:n,body:r})}));m(this,"logMethod",(s,e=console.log)=>(...t)=>{let i=or();this.logLevel<=s&&e(i,...t);let r=ke.paramArrayToString(t);s>0&&this.addLog(r)});m(this,"d",this.logMethod(0,console.debug));m(this,"i",this.logMethod(1));m(this,"w",this.logMethod(3,console.warn));m(this,"e",this.logMethod(4,(...s)=>{const[e,...t]=s;console.error(e,"<error>",t)}));m(this,"ev",this.logMethod(2));m(this,"a",this.logMethod(2,(...s)=>{const[e,...t]=s;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));m(this,"ar",this.logMethod(2,(...s)=>{const[e,...t]=s;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));m(this,"ae",this.logMethod(2,(...s)=>{const[e,...t]=s;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));window.addEventListener("beforeunload",()=>{this.reportEnd(!0)})}init(s){s&&(this.globalEnv=s),this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer)}reset(){this.bSesid=dt(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return E(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const s=yield this.refreshSTSToken();this.createTracker(s)}catch(s){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},xi)})}refreshSTSToken(){return E(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+xi){const s=yield this.requestSTSToken(),e=new Date(s==null?void 0:s.Expiration).getTime()||0,t=Date.now()+xi;this.stsExpiration=Math.max(e,t),this.stsData=s}return this.stsData})}requestSTSToken(){const s=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${s}`,t={Action:"AssumeSlsRoleV2",AuthInfo:Gt.MD5(e).toString(Gt.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${s}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Ni(s,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),r=`https://${this.globalEnv==="SEA"?"slsrole-intl.alicdn.com":"slsrole.alicdn.com"}/?${i}`;return fetch(r).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}createTracker(s){if(!this.tracker){const e={accessKeyId:s.AccessKeyId,accessKeySecret:s.AccessKeySecret,securityToken:s.SecurityToken,refreshSTSTokenInterval:xi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(r=>{e.accessKeyId=r.AccessKeyId,e.accessKeySecret=r.AccessKeySecret,e.securityToken=r.SecurityToken}).catch(()=>{})}},t=new jo(this.globalEnv==="SEA"?ya:va),i=ar(e);t.useStsPlugin(i),this.stsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(s){s.logLevel!==void 0&&s.logLevel>=0&&s.logLevel<=5&&(this.logLevel=s.logLevel)}setSessionID(s,e){s&&e&&(this.appId=s,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const s={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,s),this.getLogParams(710202,s)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(s=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];s?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(s,e){return X({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:$o,db:Sa.browserName,dm:Sa.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:ba.systemName,osv:ba.systemVersion,p_sesid:this.bSesid,sdk_version:gi,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:s},e||{})}sendLog(s){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:s,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(s){const e=or(),t=`[${Ra()} ${e}] ${s}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class C{static getLogger(){return this.logger||(this.logger=new Wo),this.logger}static init(s){this.getLogger().init(s)}static destroy(){this.getLogger().destroy()}static setLogLevel(s){this.getLogger().changeConfig({logLevel:s})}static setSessionID(s,e){this.getLogger().setSessionID(s,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...s){this.getLogger().a("[API]",...s)}static interfaceResult(s,e,t,...i){t?this.getLogger().ar("[ARE]",s,e,...i):this.getLogger().ae("[ARE]",s,e,...i)}static event(...s){this.getLogger().ev("[EVT]",...s)}static debug(...s){this.getLogger().d("[DBG]",...s)}static info(...s){this.getLogger().i("[INF]",...s)}static warn(...s){this.getLogger().w("[WARN]",...s)}static error(...s){this.getLogger().e("[ERR]",...s)}}m(C,"logger");const Ji=class Ji extends ne{constructor(e){super();m(this,"roomServerUrl");m(this,"label");m(this,"rtsInstance");m(this,"currentStatus",se.AliRtcConnectionStatusInit);m(this,"latestStreamInfo");m(this,"preferredL1Ip");m(this,"usePreferredL1InRetry",!0);m(this,"_remoteStream");m(this,"remoteStream");m(this,"_prevDownlinkStat");m(this,"networkQualityTimer");this.config=e;const{env:t,appId:i,currentUserId:r,targetChannelId:n,targetUserId:c,token:o,nonce:l,timestamp:d}=e,u=ke.createCallid(),p=new URLSearchParams({appid:i,channelid:n,userid:r,timestamp:d.toString(),token:o,nonce:l!=null?l:"",tid:u,pubchannelid:n,pubuserid:c}),h=t===lt.pre?yt.pre:yt.prod;this.roomServerUrl=`https://${h}/signaling/v1/querypulluri?${p.toString()}`,this.label=`${this.config.currentUserId} => ${this.config.targetChannelId} > ${this.config.targetUserId}`,this.fetchStreamUrlAndPlay()}get logName(){return`${Ji.logName}(${this.label})`}updateConnectionStatus(e){this.currentStatus!==e&&(this.currentStatus=e,this.emit("connectionStatusChange",e))}handleError(e,t){var i;C.error(`[${this.logName}]`,"Error:",e,t),this.emit("error",e,t),this.updateConnectionStatus(se.AliRtcConnectionStatusFailed),(i=this.rtsInstance)==null||i.dispose(),this.rtsInstance=void 0}fetchStreamUrlAndPlay(){return E(this,null,function*(){var e,t,i;this.updateConnectionStatus(se.AliRtcConnectionStatusConnecting);try{const r=yield fetch(this.roomServerUrl);if(!r.ok){const d=yield r.text();return void this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed, status: ${r.status} ${d}`)}const n=yield r.json();if(C.debug(`[${this.logName}]`,"Query pull uri response:",n),n.code!==0)return void this.handleError("FETCH_STREAM_URL_FAILED",`Business error, code: ${n.code}`);if(!((t=(e=n==null?void 0:n.data)==null?void 0:e.subscribe)!=null&&t.pullstreamurl)||!((i=n==null?void 0:n.data)!=null&&i.tracks))return void this.handleError("NO_STREAM_AVAILABLE","No stream available");const c=`${n.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,o=n.data.tracks.filter(d=>is(d.msid)).map(d=>d.msid),l=n.data.tracks.filter(d=>rs(d.msid)).map(d=>d.msid);if(o.length===0&&l.length===0)return void this.handleError("NO_STREAM_AVAILABLE","No tracks available");C.info(`[${this.logName}]`,"Fetch stream url success",c,o,l),this.latestStreamInfo={url:c,vMsid:o,aMsid:l},this.preferredL1Ip=n.l1ip,this.rtsInstance=J.AliRTS.createClient(),this.rtsInstance.on("reconnect",d=>{d.retryTimes>=300?this.handleError("SUBSCRIBE_FAILED","reconnect failed"):this.currentStatus!==se.AliRtcConnectionStatusReconnecting&&(C.warn(`[${this.logName}]`,"reconnecting",d),this.updateConnectionStatus(se.AliRtcConnectionStatusReconnecting))}),this.rtsInstance.on("hebtReceived",d=>{var u,p;d.recode===0&&((p=(u=d.streams)==null?void 0:u[0])==null?void 0:p.res_code)===200&&this.currentStatus===se.AliRtcConnectionStatusReconnecting&&(C.warn(`[${this.logName}]`,"reconnect success",d),this.updateConnectionStatus(se.AliRtcConnectionStatusConnected))});try{if(this._remoteStream=yield this.subscribeWithPreferredL1Fallback(c,{vMsid:o,aMsid:l,heartbeat:{interval:1e3,timeout:5e3},retryTimes:300,beforeRetry:()=>E(this,null,function*(){var u;C.info(`[${this.logName}]`,"Trying to fetch new stream url...");const d=yield fetch(this.roomServerUrl);if(d.status!==400){if(d.ok&&d.status===200){const p=yield d.json();if(C.debug(`[${this.logName}]`,"Query pull uri response:",p),p.code===0&&((u=p.data.subscribe)==null?void 0:u.pullstreamurl)&&p.data.tracks){const h=`${p.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,f=p.data.tracks.filter(S=>is(S.msid)).map(S=>S.msid),g=p.data.tracks.filter(S=>rs(S.msid)).map(S=>S.msid);if(f.length>0||g.length>0){const S=this.usePreferredL1InRetry?Zi(h,p.l1ip):h;C.info(`[${this.logName}]`,"Fetch new stream url success",S,f,g,`usePreferredL1InRetry=${this.usePreferredL1InRetry}`),this.latestStreamInfo={url:S,vMsid:f,aMsid:g}}}}return this.latestStreamInfo}{const p=yield d.text();this.handleError("FETCH_STREAM_URL_FAILED",`Fetch new stream url failed, status: ${d.status} ${p}`)}})}),C.info(`[${this.logName}]`,"Subscribe success",this._remoteStream.traceId),this.remoteStream=this.createRemoteStreamProxy(this._remoteStream),this.updateConnectionStatus(se.AliRtcConnectionStatusConnected),this.startNetworkQualityTimer(),this.config.view){let d;d=typeof this.config.view=="string"?document.getElementById(this.config.view):this.config.view,d instanceof HTMLMediaElement?this._remoteStream.play(d):this.emit("error","INVALID_VIEW_ELEMENT","view is not a media element")}}catch(d){this.handleError("SUBSCRIBE_FAILED",`Subscribe failed: ${d.message}`)}}catch(r){this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed: ${r.message}`)}})}subscribeWithPreferredL1Fallback(e,t){return E(this,null,function*(){const i=Zi(e,this.preferredL1Ip);if(i!==e){const n=window.__ali_prefer_media_server||this.preferredL1Ip;C.info(`[${this.logName}]`,"Subscribing with preferred media server, ip:",n);const c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rtsInstance.subscribe(i,t),c]);return this.latestStreamInfo.url=i,this.logCandidateProtocol("subscribe (preferred)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){C.warn(`[${this.logName}]`,"Preferred media server subscribe timeout, falling back to DNS"),this.usePreferredL1InRetry=!1;const l=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe (fallback)"),l}throw o}}const r=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe"),r})}logCandidateProtocol(e){return E(this,null,function*(){var t,i,r;try{const n=(r=(i=(t=this.rtsInstance)==null?void 0:t.commonController)==null?void 0:i.peerCore)==null?void 0:r.pc;if(!n)return void C.debug(`[${this.logName}]`,`${e} - PC not available`);const c=yield n.getStats();let o,l,d,u;c.forEach(p=>{p.type==="candidate-pair"&&p.state==="succeeded"&&p.nominated&&(o=p.localCandidateId,l=p.remoteCandidateId)}),o||l||c.forEach(p=>{p.type!=="candidate-pair"||p.state!=="succeeded"&&p.state!=="in-progress"||o||(o=p.localCandidateId,l=p.remoteCandidateId)}),c.forEach(p=>{p.type==="local-candidate"&&p.id===o&&(d=p.protocol),p.type==="remote-candidate"&&p.id===l&&(u=p.protocol)}),C.info(`[${this.logName}]`,`${e} - Candidate Protocol: local=${d||"unknown"}, remote=${u||"unknown"}`)}catch(n){C.warn(`[${this.logName}]`,`${e} - Failed to get candidate protocol:`,n)}})}createRemoteStreamProxy(e){const t=this.logName;return new Proxy(e,{get(i,r,n){const c=Reflect.get(i,r,n);return typeof c=="function"?function(...o){C.interface(`[${t}]`,`remoteStream.${String(r)} called`,o.length>0?o:"");const l=c.apply(i,o);return l instanceof Promise?l.then(d=>(C.info(`[${t}]`,`remoteStream.${String(r)} resolved`,d!==void 0?d:""),d),d=>{throw C.error(`[${t}]`,`remoteStream.${String(r)} rejected`,d),d}):l}:c}})}startNetworkQualityTimer(){this.stopNetworkQualityTimer(),this._prevDownlinkStat=void 0,this.networkQualityTimer=setInterval(()=>E(this,null,function*(){if(this.currentStatus===se.AliRtcConnectionStatusConnected)try{const e=yield this.getNetworkQuality();this.emit("networkQuality",e)}catch(e){C.warn(`[${this.logName}]`,"Failed to get network quality:",e)}}),2e3)}stopNetworkQualityTimer(){this.networkQualityTimer&&(clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0)}getNetworkQuality(){return E(this,null,function*(){var h,f,g;const e=(g=(f=(h=this.rtsInstance)==null?void 0:h.commonController)==null?void 0:f.peerCore)==null?void 0:g.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:Qe.AliRtcNetworkDisconnected};let t=0,i=0,r=0;const n=e.getReceivers();for(const S of n)(yield S.getStats()).forEach(b=>{b.type==="candidate-pair"&&typeof b.currentRoundTripTime=="number"&&(t=Math.round(1e3*b.currentRoundTripTime)),b.type!=="inbound-rtp"||b.mediaType!=="audio"&&b.mediaType!=="video"||(i+=b.packetsLost||0,r+=b.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:r},{rtt:t,loss:0,quality:Qe.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=r-o;let u=0;l>0&&d>=0&&(u=Math.round(l/(l+d)*100));const p=er(u,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:r},{rtt:t,loss:u,quality:p}})}dispose(){C.info(`[${this.logName}]`,"dispose"),this.stopNetworkQualityTimer(),this.updateConnectionStatus(se.AliRtcConnectionStatusDisconnected),this.rtsInstance&&this.rtsInstance.dispose()}};m(Ji,"logName","RemoteStreamHandler");let lr=Ji;var dr={exports:{}};(function(a,s){(function(e,t){var i="function",r="undefined",n="object",c="string",o="major",l="model",d="name",u="type",p="vendor",h="version",f="architecture",g="console",S="mobile",b="tablet",v="smarttv",R="wearable",_="embedded",y="Amazon",A="Apple",w="ASUS",T="BlackBerry",I="Browser",P="Chrome",D="Firefox",U="Google",q="Huawei",Y="LG",G="Microsoft",$="Motorola",Z="Opera",te="Samsung",fe="Sharp",N="Sony",x="Xiaomi",L="Zebra",O="Facebook",ue="Chromium OS",Me="Mac OS",K=" Browser",Se=function(ce){for(var ae={},ie=0;ie<ce.length;ie++)ae[ce[ie].toUpperCase()]=ce[ie];return ae},Le=function(ce,ae){return typeof ce===c&&_e(ae).indexOf(_e(ce))!==-1},_e=function(ce){return ce.toLowerCase()},Pe=function(ce,ae){if(typeof ce===c)return ce=ce.replace(/^\s\s*/,""),typeof ae===r?ce:ce.substring(0,500)},be=function(ce,ae){for(var ie,ve,Ue,pe,We,Q,xe=0;xe<ae.length&&!We;){var ct=ae[xe],Oe=ae[xe+1];for(ie=ve=0;ie<ct.length&&!We&&ct[ie];)if(We=ct[ie++].exec(ce))for(Ue=0;Ue<Oe.length;Ue++)Q=We[++ve],typeof(pe=Oe[Ue])===n&&pe.length>0?pe.length===2?typeof pe[1]==i?this[pe[0]]=pe[1].call(this,Q):this[pe[0]]=pe[1]:pe.length===3?typeof pe[1]!==i||pe[1].exec&&pe[1].test?this[pe[0]]=Q?Q.replace(pe[1],pe[2]):t:this[pe[0]]=Q?pe[1].call(this,Q,pe[2]):t:pe.length===4&&(this[pe[0]]=Q?pe[3].call(this,Q.replace(pe[1],pe[2])):t):this[pe]=Q||t;xe+=2}},Ee=function(ce,ae){for(var ie in ae)if(typeof ae[ie]===n&&ae[ie].length>0){for(var ve=0;ve<ae[ie].length;ve++)if(Le(ae[ie][ve],ce))return ie==="?"?t:ie}else if(Le(ae[ie],ce))return ie==="?"?t:ie;return ae.hasOwnProperty("*")?ae["*"]:ce},he={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Ne={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,h],[/opios[\/ ]+([\w\.]+)/i],[h,[d,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[d,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[d,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[d,"UC"+I]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[d,"Smart Lenovo "+I]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+I],h],[/\bfocus\/([\w\.]+)/i],[h,[d,D+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[d,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[d,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[d,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[h,[d,D]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+K],h],[/samsungbrowser\/([\w\.]+)/i],[h,[d,te+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,O],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[d,"Android "+I]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[h,Ee,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[d,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[d,D+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[d,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,_e]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",_e]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,_e]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[p,te],[u,b]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[l,[p,te],[u,S]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[p,A],[u,S]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[p,A],[u,b]],[/(macintosh);/i],[l,[p,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[p,fe],[u,S]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[p,"Honor"],[u,S]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[p,q],[u,b]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[p,q],[u,S]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[l,/_/g," "],[p,x],[u,S]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[p,x],[u,b]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[p,"OPPO"],[u,S]],[/\b(opd2\d{3}a?) bui/i],[l,[p,"OPPO"],[u,b]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[p,"Vivo"],[u,S]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[p,"Realme"],[u,S]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[p,$],[u,S]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[p,$],[u,b]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[p,Y],[u,b]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[p,Y],[u,S]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[p,"Lenovo"],[u,b]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[p,"Nokia"],[u,S]],[/(pixel c)\b/i],[l,[p,U],[u,b]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[p,U],[u,S]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[p,N],[u,S]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[p,N],[u,b]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[p,"OnePlus"],[u,S]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[p,y],[u,b]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[p,y],[u,S]],[/(playbook);[-\w\),; ]+(rim)/i],[l,p,[u,b]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[p,T],[u,S]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[p,w],[u,b]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[p,w],[u,S]],[/(nexus 9)/i],[l,[p,"HTC"],[u,b]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[l,/_/g," "],[u,S]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[l,[p,"TCL"],[u,b]],[/(itel) ((\w+))/i],[[p,_e],l,[u,Ee,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[p,"Acer"],[u,b]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[p,"Meizu"],[u,S]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[p,"Ulefone"],[u,S]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[p,"Energizer"],[u,S]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[p,"Cat"],[u,S]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[p,"Smartfren"],[u,S]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[p,"Nothing"],[u,S]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,l,[u,S]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,l,[u,b]],[/(surface duo)/i],[l,[p,G],[u,b]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[p,"Fairphone"],[u,S]],[/(u304aa)/i],[l,[p,"AT&T"],[u,S]],[/\bsie-(\w*)/i],[l,[p,"Siemens"],[u,S]],[/\b(rct\w+) b/i],[l,[p,"RCA"],[u,b]],[/\b(venue[\d ]{2,7}) b/i],[l,[p,"Dell"],[u,b]],[/\b(q(?:mv|ta)\w+) b/i],[l,[p,"Verizon"],[u,b]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[p,"Barnes & Noble"],[u,b]],[/\b(tm\d{3}\w+) b/i],[l,[p,"NuVision"],[u,b]],[/\b(k88) b/i],[l,[p,"ZTE"],[u,b]],[/\b(nx\d{3}j) b/i],[l,[p,"ZTE"],[u,S]],[/\b(gen\d{3}) b.+49h/i],[l,[p,"Swiss"],[u,S]],[/\b(zur\d{3}) b/i],[l,[p,"Swiss"],[u,b]],[/\b((zeki)?tb.*\b) b/i],[l,[p,"Zeki"],[u,b]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],l,[u,b]],[/\b(ns-?\w{0,9}) b/i],[l,[p,"Insignia"],[u,b]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[p,"NextBook"],[u,b]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],l,[u,S]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],l,[u,S]],[/\b(ph-1) /i],[l,[p,"Essential"],[u,S]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[p,"Envizen"],[u,b]],[/\b(trio[-\w\. ]+) b/i],[l,[p,"MachSpeed"],[u,b]],[/\btu_(1491) b/i],[l,[p,"Rotor"],[u,b]],[/(shield[\w ]+) b/i],[l,[p,"Nvidia"],[u,b]],[/(sprint) (\w+)/i],[p,l,[u,S]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[p,G],[u,S]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[p,L],[u,b]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[p,L],[u,S]],[/smart-tv.+(samsung)/i],[p,[u,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[p,te],[u,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Y],[u,v]],[/(apple) ?tv/i],[p,[l,A+" TV"],[u,v]],[/crkey/i],[[l,P+"cast"],[p,U],[u,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[p,y],[u,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[p,fe],[u,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[p,N],[u,v]],[/(mitv-\w{5}) bui/i],[l,[p,x],[u,v]],[/Hbbtv.*(technisat) (.*);/i],[p,l,[u,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,Pe],[l,Pe],[u,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,l,[u,g]],[/droid.+; (shield) bui/i],[l,[p,"Nvidia"],[u,g]],[/(playstation [345portablevi]+)/i],[l,[p,N],[u,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[p,G],[u,g]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[p,te],[u,R]],[/((pebble))app/i],[p,l,[u,R]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[p,A],[u,R]],[/droid.+; (glass) \d/i],[l,[p,U],[u,R]],[/droid.+; (wt63?0{2,3})\)/i],[l,[p,L],[u,R]],[/droid.+; (glass) \d/i],[l,[p,U],[u,R]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,l,[u,R]],[/; (quest( \d| pro)?)/i],[l,[p,O],[u,R]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[u,_]],[/(aeobc)\b/i],[l,[p,y],[u,_]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[u,S]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[u,b]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,b]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,S]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[h,Ee,he]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,Ee,he],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,Me],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,h],[/\(bb(10);/i],[h,[d,T]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[d,D+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,ue],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,h],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,h]]},Re=function(ce,ae){if(typeof ce===n&&(ae=ce,ce=t),!(this instanceof Re))return new Re(ce,ae).getResult();var ie=typeof e!==r&&e.navigator?e.navigator:t,ve=ce||(ie&&ie.userAgent?ie.userAgent:""),Ue=ie&&ie.userAgentData?ie.userAgentData:t,pe=ae?function(Q,xe){var ct={};for(var Oe in Q)xe[Oe]&&xe[Oe].length%2==0?ct[Oe]=xe[Oe].concat(Q[Oe]):ct[Oe]=Q[Oe];return ct}(Ne,ae):Ne,We=ie&&ie.userAgent==ve;return this.getBrowser=function(){var Q,xe={};return xe[d]=t,xe[h]=t,be.call(xe,ve,pe.browser),xe[o]=typeof(Q=xe[h])===c?Q.replace(/[^\d\.]/g,"").split(".")[0]:t,We&&ie&&ie.brave&&typeof ie.brave.isBrave==i&&(xe[d]="Brave"),xe},this.getCPU=function(){var Q={};return Q[f]=t,be.call(Q,ve,pe.cpu),Q},this.getDevice=function(){var Q={};return Q[p]=t,Q[l]=t,Q[u]=t,be.call(Q,ve,pe.device),We&&!Q[u]&&Ue&&Ue.mobile&&(Q[u]=S),We&&Q[l]=="Macintosh"&&ie&&typeof ie.standalone!==r&&ie.maxTouchPoints&&ie.maxTouchPoints>2&&(Q[l]="iPad",Q[u]=b),Q},this.getEngine=function(){var Q={};return Q[d]=t,Q[h]=t,be.call(Q,ve,pe.engine),Q},this.getOS=function(){var Q={};return Q[d]=t,Q[h]=t,be.call(Q,ve,pe.os),We&&!Q[d]&&Ue&&Ue.platform&&Ue.platform!="Unknown"&&(Q[d]=Ue.platform.replace(/chrome os/i,ue).replace(/macos/i,Me)),Q},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return ve},this.setUA=function(Q){return ve=typeof Q===c&&Q.length>500?Pe(Q,500):Q,this},this.setUA(ve),this};Re.VERSION="1.0.40",Re.BROWSER=Se([d,h,o]),Re.CPU=Se([f]),Re.DEVICE=Se([l,p,u,g,S,v,b,R,_]),Re.ENGINE=Re.OS=Se([d,h]),a.exports&&(s=a.exports=Re),s.UAParser=Re;var Ge=typeof e!==r&&(e.jQuery||e.Zepto);if(Ge&&!Ge.ua){var ot=new Re;Ge.ua=ot.getResult(),Ge.ua.get=function(){return ot.getUA()},Ge.ua.set=function(ce){ot.setUA(ce);var ae=ot.getResult();for(var ie in ae)Ge.ua[ie]=ae[ie]}}})(typeof window=="object"?window:Di)})(dr,dr.exports);var zo=dr.exports,Be=(a=>(a.KEEPALIVE="keepalive",a.JOINCHANNEL="joinchannel",a.NOTIFYJOIN="notifyjoin",a.NOTIFYSTATUS="notifystatus",a.STATUSREPORT="statusreport",a.LEAVECHANNEL="leavechannel",a.NOTIFYLEAVE="notifyleave",a.NOTIFYPUBLISH="notifypublish",a.BYE="bye",a.RECONNECT="reconnect",a.PUBLISH="publish",a.REFRESHURL="refreshurl",a.UNSUBSCRIBE="unsubscribe",a.ROLEUPDATE="roleupdate",a))(Be||{});class Oi{constructor(s,e){m(this,"authInfo");m(this,"userName");m(this,"seqIndex",0);this.authInfo=s,this.userName=typeof e=="number"?e.toString():e}get roleAuth(){if(this.authInfo.role){const{timestamp:s,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:s,nonce:e,token:t,tokenrole:i}}}static get adaptInfo(){var e,t,i,r;let s=new zo.UAParser().getResult();return{os_name:((e=s.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=s.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=s.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((r=s.device.vendor)==null?void 0:r.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:s.browser.version||"",sdk_version:"7.2.7",version:"v1"}}refreshAuthInfo(s){this.authInfo=s}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(s){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=ke.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Oi.adaptInfo,s&&(e.data=X(X({},e.data),s)),e}createLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(s){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=s,e}createPublishPackage(){let s=this.createBaseSendPackage("publish");return s.data.users=[{}],this.roleAuth&&(s.data.auth=this.roleAuth),s}createRoleUpdatePackage(){let s=this.createBaseSendPackage("roleupdate");return s.header.displayName=this.userName,s}createReconnectPackage(s){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=ke.getVersionNumber().toString(),e.header.platform="web",e.data=X(X({},e.data),s!=null?s:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let s=this.createBaseSendPackage("refreshurl");return s.header.displayName=this.userName,s}createResponsePackage(s,e){return{version:1,code:200,tid:s,msgtype:e}}createBaseSendPackage(s){var e;return++this.seqIndex,{version:1,msgtype:s,tid:dt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}const Aa="ALI_RTC_SDK_ALLOCATE_RESULT",ui=class ui{constructor(s,e,t){m(this,"result",null);m(this,"pms",null);m(this,"env");m(this,"config");m(this,"joinMode");this.env=s,this.config=e,this.joinMode=t;let i=localStorage.getItem(Aa);if(i){const r=JSON.parse(i);r.appId===e.appId&&r.expireTs-3e5>Date.now()?this.result=r.allocatedData:C.info(`[${ui.logName}]`,"allocate","cached data is invalid")}}fetchAndUpdate(){if(this.pms)return this.pms;const{appId:s,channelId:e,sessionId:t,userId:i,timestamp:r,token:n,nonce:c}=this.config,o=new URLSearchParams({appid:s,channelid:e,session:t,userid:i,timestamp:`${r}`,token:n,nonce:c!=null?c:"",adapt:"true",clitype:"2"});this.joinMode&&o.set("joinmode",this.joinMode);const l=this.env===lt.pre?yt.pre:yt.prod;return this.pms=fetch(`https://${l}/gslb/v1/allocate?${o.toString()}`,{method:"POST",body:JSON.stringify(Oi.adaptInfo)}).then(d=>d.json()).then(d=>{if(d.code===0){const u=d.data;this.result=u;const{ice_ufrag:p}=u.h5auth,[h,f]=atob(p).split("_"),g={appId:s,expireTs:1e3*parseInt(f),allocatedData:u};return C.info(`[${ui.logName}]`,"got allocate result and save",u.h5auth.ice_ufrag),localStorage.setItem(Aa,JSON.stringify(g)),u}return null}).catch(d=>(C.error(`[${ui.logName}]`,"allocate",d),null)),this.pms}};m(ui,"logName","Allocator");let fi=ui;class ur{constructor(s,e){m(this,"originTrack");m(this,"originVideo");m(this,"targetWidth");m(this,"targetHeight");m(this,"targetFrameRate");m(this,"targetCanvas");m(this,"animationFrameId");m(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=s,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(s){this.targetWidth=s.width,this.targetHeight=s.height,this.targetFrameRate=s.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(s,e,t,i){const r=e/s,n=i/t;let c=t,o=i,l=0,d=0;return n>r?(c=Math.round(o/r),l=Math.round((t-c)/2)):n<r&&(o=Math.round(c*r),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class Ko extends ur{constructor(e,t){super(e,t);m(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function wa(a,s,e){const t=a.createShader(s);if(t)return a.shaderSource(t,e),a.compileShader(t),a.getShaderParameter(t,a.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${a.getShaderInfoLog(t)}`),a.deleteShader(t),null);console.error("create shader failed")}class _a extends ur{constructor(e,t){super(e,t);m(this,"targetCtx");m(this,"targetTexture");m(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const u=wa(o,o.VERTEX_SHADER,l),p=wa(o,o.FRAGMENT_SHADER,d),h=o.createProgram();if(h&&u&&p)return o.attachShader(h,u),o.attachShader(h,p),o.linkProgram(h),o.getProgramParameter(h,o.LINK_STATUS)?h:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(h)}`),null)}(e,`
9
+ `;const E=(D,U)=>D[0].localeCompare(U[0]),C=D=>D[0].startsWith("x-log-")||D[0].startsWith("x-acs-");try{const D=[...R.entries()].filter(C).sort(E).map(U=>U[0]+":"+U[1]+`
10
+ `).join("");w+=D}catch(D){}w+=g,v.size>0&&(w+="?");try{w+=[...v.entries()].sort(E).map(D=>D[0]+"="+D[1]).join("&")}catch(D){}const P="LOG "+S+":"+si.HmacSHA1(w,b).toString(si.enc.Base64);R.set("Authorization",P),R.set("x-log-date",y)}("POST",n,a.accessKeyId,a.accessKeySecret,h,p,o,d);let u=Object.fromEntries(p);return{data:e,header:u}},new Promise((n,c)=>{var o=h=>{try{d(s.next(h))}catch(p){c(p)}},l=h=>{try{d(s.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((s=s.apply(t,i)).next())});var t,i,s}}}typeof window!="undefined"&&fr(window,"stsPlugin",ps);var Vo=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,Oo=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,Uo=/[^-+\dA-Z]/g;function Fi(a,r,e,t){if(arguments.length!==1||typeof a!="string"||/\d/.test(a)||(r=a,a=void 0),(a=a||a===0?a:new Date)instanceof Date||(a=new Date(a)),isNaN(a))throw TypeError("Invalid date");var i=(r=String(Ra[r]||r||Ra.default)).slice(0,4);i!=="UTC:"&&i!=="GMT:"||(r=r.slice(4),e=!0,i==="GMT:"&&(t=!0));var s=function(){return e?"getUTC":"get"},n=function(){return a[s()+"Date"]()},c=function(){return a[s()+"Day"]()},o=function(){return a[s()+"Month"]()},l=function(){return a[s()+"FullYear"]()},d=function(){return a[s()+"Hours"]()},h=function(){return a[s()+"Minutes"]()},p=function(){return a[s()+"Seconds"]()},u=function(){return a[s()+"Milliseconds"]()},f=function(){return e?0:a.getTimezoneOffset()},g=function(){return Bo(a)},S={d:function(){return n()},dd:function(){return pt(n())},ddd:function(){return nt.dayNames[c()]},DDD:function(){return Aa({y:l(),m:o(),d:n(),_:s(),dayName:nt.dayNames[c()],short:!0})},dddd:function(){return nt.dayNames[c()+7]},DDDD:function(){return Aa({y:l(),m:o(),d:n(),_:s(),dayName:nt.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return pt(o()+1)},mmm:function(){return nt.monthNames[o()]},mmmm:function(){return nt.monthNames[o()+12]},yy:function(){return String(l()).slice(2)},yyyy:function(){return pt(l(),4)},h:function(){return d()%12||12},hh:function(){return pt(d()%12||12)},H:function(){return d()},HH:function(){return pt(d())},M:function(){return h()},MM:function(){return pt(h())},s:function(){return p()},ss:function(){return pt(p())},l:function(){return pt(u(),3)},L:function(){return pt(Math.floor(u()/10))},t:function(){return d()<12?nt.timeNames[0]:nt.timeNames[1]},tt:function(){return d()<12?nt.timeNames[2]:nt.timeNames[3]},T:function(){return d()<12?nt.timeNames[4]:nt.timeNames[5]},TT:function(){return d()<12?nt.timeNames[6]:nt.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":Fo(a)},o:function(){return(f()>0?"-":"+")+pt(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+pt(Math.floor(Math.abs(f())/60),2)+":"+pt(Math.floor(Math.abs(f())%60),2)},S:function(){return["th","st","nd","rd"][n()%10>3?0:(n()%100-n()%10!=10)*n()%10]},W:function(){return g()},WW:function(){return pt(g())},N:function(){return Ho(a)}};return r.replace(Vo,function(b){return b in S?S[b]():b.slice(1,b.length-1)})}var Ra={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},nt={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},pt=function(a){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(a).padStart(r,"0")},Aa=function(a){var r=a.y,e=a.m,t=a.d,i=a._,s=a.dayName,n=a.short,c=n!==void 0&&n,o=new Date,l=new Date;l.setDate(l[i+"Date"]()-1);var d=new Date;return d.setDate(d[i+"Date"]()+1),o[i+"FullYear"]()===r&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":l[i+"FullYear"]()===r&&l[i+"Month"]()===e&&l[i+"Date"]()===t?c?"Ysd":"Yesterday":d[i+"FullYear"]()===r&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Tmw":"Tomorrow":s},Bo=function(a){var r=new Date(a.getFullYear(),a.getMonth(),a.getDate());r.setDate(r.getDate()-(r.getDay()+6)%7+3);var e=new Date(r.getFullYear(),0,4);e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=r.getTimezoneOffset()-e.getTimezoneOffset();r.setHours(r.getHours()-t);var i=(r-e)/6048e5;return 1+Math.floor(i)},Ho=function(a){var r=a.getDay();return r===0&&(r=7),r},Fo=function(a){return(String(a).match(Oo)||[""]).pop().replace(Uo,"").replace(/GMT\+0000/g,"UTC")};const{BrowserUtil:jo}=K.AliRTS,$o="EdgeHTML",wa="Blink",Wo="Trident",zo="Gecko",Ko="WebKit",ji=(a,r)=>{const e=r.match(a);return e&&e.length>0&&e[1]||""},Jo=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(a){if(/\sedg\//i.test(a))return{name:wa};const r=ji(/edge\/(\d+(\.?_?\d+)+)/i,a);return{name:$o,version:r}}},{test:[/trident/i],describe(a){const r={name:Wo},e=ji(/trident\/(\d+(\.?_?\d+)+)/i,a);return e&&(r.version=e),r}},{test(a){const r=/gecko/i.test(a),e=/like gecko/i.test(a);return r&&!e},describe(a){const r={name:zo},e=ji(/gecko\/(\d+(\.?_?\d+)+)/i,a);return e&&(r.version=e),r}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:wa})},{test:[/(apple)?webkit/i],describe(a){const r={name:Ko},e=ji(/webkit\/(\d+(\.?_?\d+)+)/i,a);return e&&(r.version=e),r}}],ms=(a,r)=>a.find(e=>typeof e.test=="function"?e.test(r):Array.isArray(e.test)?e.test.some(t=>typeof t=="string"?r.indexOf(t)>-1:t instanceof RegExp&&t.test(r)):void 0),Go=()=>{try{const a=navigator.userAgent||"",r=ms(Jo,a);if(r){const e=r.describe(a);return`${e.name}/${e.version||jo.browserVersion}`}}catch(a){}return navigator.userAgent},qo=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],_a=()=>{let a="unknown";try{const r=navigator.userAgent||"",e=ms(qo,r);if(!e)return a;a=e.describe(r)}catch(r){}return a},Xo=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],Yo=()=>{let a="Unknown";try{const r=navigator.userAgent||"",e=ms(Xo,r);if(!e)return a;a=e.describe(r)}catch(r){}return a};class Ia{constructor(r){var e,t;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(e=r.time)!=null?e:10,this.count=(t=r.count)!=null?t:10,r.host.startsWith("http://")||r.host.startsWith("https://")?this.url=r.host+"/logstores/"+r.logstore+"/track":this.url="https://"+r.project+"."+r.host+"/logstores/"+r.logstore+"/track",this.opt=r,r.installUnloadHook&&typeof r.installUnloadHook=="function"&&r.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(r){const e={__logs__:r};return this.opt.tags&&(e.__tags__=this.opt.tags),this.opt.topic&&(e.__topic__=this.opt.topic),this.opt.source&&(e.__source__=this.opt.source),JSON.stringify(e)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const r=this.assemblePayload(this.arr);this.opt.sendPayload(this.url,r)}}transString(r){let e={};for(let t in r)typeof r[t]=="object"?e[t]=JSON.stringify(r[t]):e[t]=String(r[t]);return e}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const r=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){r.sendImmediateInner()},1e3*this.time)}}send(r){const e=this.transString(r);this.arr.push(e),this.sendInner()}sendImmediate(r){const e=this.transString(r);this.arr.push(e),this.sendImmediateInner()}sendBatchLogs(r){const e=r.map(t=>this.transString(t));this.arr.push(...e),this.sendInner()}sendBatchLogsImmediate(r){const e=r.map(t=>this.transString(t));this.arr.push(...e),this.sendImmediateInner()}overwriteTransString(r){this.transString=r.transString}getOpt(){return this.opt}}function Ea(a,r){return new Promise((e,t)=>{const i=new window.XMLHttpRequest;i.onload=()=>{i.status>=200&&i.status<300?e():t(new Error(`HTTP ${i.status}: ${i.statusText}`))},i.onerror=()=>{t(new Error("Network error occurred"))},i.ontimeout=()=>{t(new Error("Request timeout"))},i.timeout=1e4,i.open("POST",`${a}?APIVersion=0.6.0`,!0),i.send(r)})}function Qo(a,r,e=!1){return I(this,null,function*(){try{if(e||r.length>=32768)return void(yield Ea(a,r));(function(t,i){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,i)})(a,r)||(yield Ea(a,r))}catch(t){const i=t instanceof Error?t:new Error(String(t));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
11
+ `+i.message),console.error("Failed log data:",a)),i}})}let Zo=(re=class extends Ia{constructor(e){const g=e,{maxRetries:t=10,retryDelay:i=2e3,backoffMultiplier:s=2,maxRetryDelay:n=3e5,enableLocalStorage:c=!0,maxStorageSize:o=1e3,storageKey:l="artc_reliable_logs",enableNetworkMonitor:d=!0,onNetworkChange:h=()=>{},forceXhrMode:p=!0,debug:u=!1}=g,f=jt(g,["maxRetries","retryDelay","backoffMultiplier","maxRetryDelay","enableLocalStorage","maxStorageSize","storageKey","enableNetworkMonitor","onNetworkChange","forceXhrMode","debug"]);super(Object.assign({},f,{installUnloadHook:S=>{re.unloadHooks.push(S),re.globalUnloadListenersRegistered||(re.globalUnloadListenersRegistered=!0,re.beforeUnloadHandler=()=>{re.instances.forEach(b=>{b.saveFailedLogs()}),re.unloadHooks.forEach(b=>b())},re.visibilityChangeHandler=()=>{document.visibilityState==="hidden"&&re.instances.forEach(b=>{b.saveFailedLogs()})},window.addEventListener("beforeunload",re.beforeUnloadHandler),document.addEventListener("visibilitychange",re.visibilityChangeHandler))},sendPayload:(S,b)=>I(this,null,function*(){return Promise.resolve()})}));m(this,"reliableConfig");m(this,"failedLogs",new Map);m(this,"networkStatus","online");m(this,"retryTimer",null);m(this,"originalSendPayload",null);re.instances.add(this),this.reliableConfig={maxRetries:t,retryDelay:i,backoffMultiplier:s,maxRetryDelay:n,enableLocalStorage:c,maxStorageSize:o,storageKey:l,enableNetworkMonitor:d,onNetworkChange:h,forceXhrMode:p,debug:u},this.originalSendPayload=(S,b)=>I(this,null,function*(){return Qo(S,b,p)}),this.getOpt().sendPayload=(S,b)=>I(this,null,function*(){return this.reliableSendAsync(S,b)}),this.initNetworkMonitor(),this.loadFailedLogs(),this.startRetryTimer()}reliableSendAsync(e,t){return I(this,null,function*(){const i=this.generateId();try{yield Promise.resolve(this.originalSendPayload(e,t)),this.debug(`Log ${i} sent successfully`)}catch(s){this.debug(`Log ${i} failed, adding to retry queue:`,s),this.addToFailedQueue(i,e,t,s)}})}addToFailedQueue(e,t,i,s){const n={id:e,data:{error:s.message},timestamp:Date.now(),retryCount:0,lastRetryTime:0,url:t,payload:i};this.failedLogs.set(e,n),this.scheduleRetry(n)}scheduleRetry(e){if(e.retryCount>=this.reliableConfig.maxRetries)return this.debug(`Log ${e.id} exceeded max retries, removing from queue`),void this.failedLogs.delete(e.id);const t=Math.min(this.reliableConfig.retryDelay*Math.pow(this.reliableConfig.backoffMultiplier,e.retryCount),this.reliableConfig.maxRetryDelay);this.debug(`Scheduling retry for log ${e.id} in ${t}ms (attempt ${e.retryCount+1}/${this.reliableConfig.maxRetries})`),setTimeout(()=>{this.retryLog(e)},t)}retryLog(e){return I(this,null,function*(){if(this.failedLogs.has(e.id)){e.retryCount++,e.lastRetryTime=Date.now();try{if(this.networkStatus==="offline")return this.debug(`Log ${e.id} retry skipped - network offline`),void this.scheduleRetry(e);yield this.originalSendPayload(e.url,e.payload),this.debug(`Log ${e.id} retry successful`),this.failedLogs.delete(e.id)}catch(t){this.debug(`Log ${e.id} retry failed:`,t),this.scheduleRetry(e)}}})}initNetworkMonitor(){this.reliableConfig.enableNetworkMonitor&&typeof window!="undefined"&&(this.networkStatus=navigator.onLine?"online":"offline",re.globalNetworkListenersRegistered?this.debug(`Network monitor already initialized globally. Current status: ${this.networkStatus}`):(re.globalNetworkListenersRegistered=!0,re.onlineHandler=()=>{re.instances.forEach(e=>{e.handleNetworkChange("online")})},re.offlineHandler=()=>{re.instances.forEach(e=>{e.handleNetworkChange("offline")})},window.addEventListener("online",re.onlineHandler),window.addEventListener("offline",re.offlineHandler),this.debug(`Network monitor initialized. Current status: ${this.networkStatus}`)))}handleNetworkChange(e){const t=this.networkStatus;this.networkStatus=e,this.debug(`Network status changed: ${t} -> ${e}`),this.reliableConfig.onNetworkChange(e==="online"),e==="online"&&t==="offline"&&(this.debug("Network recovered, retrying failed logs"),this.retryAllFailedLogs())}retryAllFailedLogs(){this.failedLogs.size!==0&&(this.debug(`Retrying ${this.failedLogs.size} failed logs after network recovery`),Array.from(this.failedLogs.values()).forEach(e=>{setTimeout(()=>this.retryLog(e),100*Math.random())}))}startRetryTimer(){typeof window!="undefined"&&(this.retryTimer=window.setInterval(()=>{if(this.failedLogs.size>0&&this.networkStatus==="online"){const e=Date.now();Array.from(this.failedLogs.values()).forEach(t=>{e-t.lastRetryTime>this.reliableConfig.retryDelay&&this.retryLog(t)})}},this.reliableConfig.retryDelay),this.debug(`Retry timer started with interval ${this.reliableConfig.retryDelay}ms`))}loadFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined")try{const e=localStorage.getItem(this.reliableConfig.storageKey);if(e){const t=JSON.parse(e);t.forEach(i=>{this.failedLogs.set(i.id,i)}),this.debug(`Loaded ${t.length} failed logs from storage`),localStorage.removeItem(this.reliableConfig.storageKey),this.networkStatus==="online"&&this.retryAllFailedLogs()}}catch(e){this.debug("Failed to load failed logs from storage:",e)}}saveFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined"&&this.failedLogs.size!==0)try{const e=Array.from(this.failedLogs.values()).slice(-this.reliableConfig.maxStorageSize);localStorage.setItem(this.reliableConfig.storageKey,JSON.stringify(e)),this.debug(`Saved ${e.length} failed logs to storage`)}catch(e){this.debug("Failed to save failed logs to storage:",e)}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}debug(...e){this.reliableConfig.debug&&typeof console!="undefined"&&console.log("[ReliableWebTracker]",...e)}useStsPlugin(e){this.originalSendPayload=(t,i)=>I(this,null,function*(){return function(s,n,c){return I(this,null,function*(){try{s=s.slice(0,-6);const{data:o,header:l}=yield c.process(s,n);return new Promise((d,h)=>{const p=new window.XMLHttpRequest;p.onload=()=>{p.status>=200&&p.status<300?d():h(new Error(`HTTP ${p.status}: ${p.statusText}`))},p.onerror=()=>{h(new Error("Network error occurred"))},p.ontimeout=()=>{h(new Error("Request timeout"))},p.timeout=1e4,p.open("POST",s,!0);for(let u in l)p.setRequestHeader(u,l[u]);p.send(o)})}catch(o){const l=o instanceof Error?o:new Error(String(o));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
12
+ `+l.message),console.error("Failed log data:",s)),l}})}(t,i,e)}),this.getOpt().sendPayload=(t,i)=>I(this,null,function*(){return this.reliableSendAsync(t,i)}),this.overwriteTransString(e)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const e=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${e} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),re.instances.delete(this),re.instances.size===0&&(re.beforeUnloadHandler&&(window.removeEventListener("beforeunload",re.beforeUnloadHandler),re.beforeUnloadHandler=null),re.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",re.visibilityChangeHandler),re.visibilityChangeHandler=null),re.globalUnloadListenersRegistered=!1,re.unloadHooks=[],re.onlineHandler&&(window.removeEventListener("online",re.onlineHandler),re.onlineHandler=null),re.offlineHandler&&(window.removeEventListener("offline",re.offlineHandler),re.offlineHandler=null),re.globalNetworkListenersRegistered=!1),this.debug("WebTrackerBrowser destroyed")}},m(re,"globalUnloadListenersRegistered",!1),m(re,"globalNetworkListenersRegistered",!1),m(re,"instances",new Set),m(re,"unloadHooks",[]),m(re,"beforeUnloadHandler",null),m(re,"visibilityChangeHandler",null),m(re,"onlineHandler",null),m(re,"offlineHandler",null),re);const{BrowserUtil:Ta,SystenUtil:Ca}=K.AliRTS,ec=_a(),$i=6e5,ka={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10},Pa={host:"ap-southeast-1.log.aliyuncs.com",project:"alivc-aio-sgp",logstore:"logger",time:10,count:10};function gs(){return Fi(new Date,"HH:MM:ss.l")}function Da(){return Fi(new Date,"isoDate")}var fs=(a=>(a[a.DEBUG=0]="DEBUG",a[a.INFO=1]="INFO",a[a.API=2]="API",a[a.WARNING=3]="WARNING",a[a.ERROR=4]="ERROR",a[a.NONE=5]="NONE",a))(fs||{});class Ma{constructor(){m(this,"tracker");m(this,"stsPlugin");m(this,"stsData");m(this,"stsExpiration",Date.now());m(this,"clientId",ut());m(this,"bSesid",ut());m(this,"logLevel",3);m(this,"appId","");m(this,"sessionId","");m(this,"logCache",[]);m(this,"updateTaskTimer");m(this,"endReported",!0);m(this,"logSequence",0);m(this,"globalEnv","DEFAULT");m(this,"beforeUnloadHandler",null);m(this,"sendLogBeforeUnload",r=>I(this,null,function*(){if(!this.stsPlugin)return;this.logSequence+=1,r.unshift(this.getLogParams(710203,{log:`[${Da()} ${gs()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=this.globalEnv==="SEA"?Pa:ka,t=`https://${e.project}.${e.host}/logstores/${e.logstore}`,i={__logs__:r.map(c=>this.stsPlugin.transString(c))},{data:s,header:n}=yield this.stsPlugin.process(t,JSON.stringify(i));fetch(t,{keepalive:!0,method:"POST",headers:n,body:s})}));m(this,"logMethod",(r,e=console.log)=>(...t)=>{let i=gs();this.logLevel<=r&&e(i,...t);let s=De.paramArrayToString(t);r>0&&this.addLog(s)});m(this,"d",this.logMethod(0,console.debug));m(this,"i",this.logMethod(1));m(this,"w",this.logMethod(3,console.warn));m(this,"e",this.logMethod(4,(...r)=>{const[e,...t]=r;console.error(e,"<error>",t)}));m(this,"ev",this.logMethod(2));m(this,"a",this.logMethod(2,(...r)=>{const[e,...t]=r;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));m(this,"ar",this.logMethod(2,(...r)=>{const[e,...t]=r;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));m(this,"ae",this.logMethod(2,(...r)=>{const[e,...t]=r;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));this.ensureBeforeUnloadHandler()}ensureBeforeUnloadHandler(){this.beforeUnloadHandler||(this.beforeUnloadHandler=()=>{this.reportEnd(!0)},window.addEventListener("beforeunload",this.beforeUnloadHandler))}init(r){r&&(this.globalEnv=r),this.ensureBeforeUnloadHandler(),this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.tracker&&(this.tracker.destroy(),this.tracker=void 0)}reset(){this.bSesid=ut(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return I(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const r=yield this.refreshSTSToken();this.createTracker(r)}catch(r){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},$i)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+$i){const r=yield this.requestSTSToken(),e=new Date(r==null?void 0:r.Expiration).getTime()||0,t=Date.now()+$i;this.stsExpiration=Math.max(e,t),this.stsData=r}return this.stsData})}requestSTSToken(){const r=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${r}`,t={Action:"AssumeSlsRoleV2",AuthInfo:si.MD5(e).toString(si.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${r}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Fi(r,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),s=`https://${this.globalEnv==="SEA"?"slsrole-intl.alicdn.com":"slsrole.alicdn.com"}/?${i}`;return fetch(s).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}createTracker(r){if(!this.tracker){const e={accessKeyId:r.AccessKeyId,accessKeySecret:r.AccessKeySecret,securityToken:r.SecurityToken,refreshSTSTokenInterval:$i,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(s=>{e.accessKeyId=s.AccessKeyId,e.accessKeySecret=s.AccessKeySecret,e.securityToken=s.SecurityToken}).catch(()=>{})}},t=new Zo(this.globalEnv==="SEA"?Pa:ka),i=ps(e);t.useStsPlugin(i),this.stsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(r){r.logLevel!==void 0&&r.logLevel>=0&&r.logLevel<=5&&(this.logLevel=r.logLevel)}setSessionID(r,e){r&&e&&(this.appId=r,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const r={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,r),this.getLogParams(710202,r)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(r=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];r?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(r,e){return X({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:ec,db:Ta.browserName,dm:Ta.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:Ca.systemName,osv:Ca.systemVersion,p_sesid:this.bSesid,sdk_version:Ai,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:r},e||{})}sendLog(r){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:r,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(r){const e=gs(),t=`[${Da()} ${e}] ${r}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class T{static getLogger(){if(this.activeInstanceId&&this.loggers.has(this.activeInstanceId))return this.loggers.get(this.activeInstanceId);const r=this.loggers.values().next().value;return r||new Ma}static setActiveInstance(r){this.activeInstanceId=r}static init(r,e){if(this.loggers.has(r))this.loggers.get(r).init(e);else{const t=new Ma;t.init(e),this.loggers.set(r,t)}this.activeInstanceId=r}static destroy(r){const e=this.loggers.get(r);if(e&&(e.destroy(),this.loggers.delete(r)),this.activeInstanceId===r){const t=this.loggers.keys().next().value;this.activeInstanceId=t||""}}static setLogLevel(r){this.loggers.forEach(e=>e.changeConfig({logLevel:r}))}static setSessionID(r,e){this.getLogger().setSessionID(r,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...r){this.getLogger().a("[API]",...r)}static interfaceResult(r,e,t,...i){t?this.getLogger().ar("[ARE]",r,e,...i):this.getLogger().ae("[ARE]",r,e,...i)}static event(...r){this.getLogger().ev("[EVT]",...r)}static debug(...r){this.getLogger().d("[DBG]",...r)}static info(...r){this.getLogger().i("[INF]",...r)}static warn(...r){this.getLogger().w("[WARN]",...r)}static error(...r){this.getLogger().e("[ERR]",...r)}}m(T,"loggers",new Map),m(T,"activeInstanceId","");const es=class es extends oe{constructor(e){super();m(this,"roomServerUrl");m(this,"label");m(this,"rtsInstance");m(this,"currentStatus",ae.AliRtcConnectionStatusInit);m(this,"latestStreamInfo");m(this,"preferredL1Ip");m(this,"usePreferredL1InRetry",!0);m(this,"_remoteStream");m(this,"remoteStream");m(this,"_prevDownlinkStat");m(this,"networkQualityTimer");this.config=e;const{env:t,appId:i,currentUserId:s,targetChannelId:n,targetUserId:c,token:o,nonce:l,timestamp:d}=e,h=De.createCallid(),p=new URLSearchParams({appid:i,channelid:n,userid:s,timestamp:d.toString(),token:o,nonce:l!=null?l:"",tid:h,pubchannelid:n,pubuserid:c}),u=t===wt.pre?St.pre:St.prod;this.roomServerUrl=`https://${u}/signaling/v1/querypulluri?${p.toString()}`,this.label=`${this.config.currentUserId} => ${this.config.targetChannelId} > ${this.config.targetUserId}`,this.fetchStreamUrlAndPlay()}get logName(){return`${es.logName}(${this.label})`}updateConnectionStatus(e){this.currentStatus!==e&&(this.currentStatus=e,this.emit("connectionStatusChange",e))}handleError(e,t){var i;T.error(`[${this.logName}]`,"Error:",e,t),this.emit("error",e,t),this.updateConnectionStatus(ae.AliRtcConnectionStatusFailed),(i=this.rtsInstance)==null||i.dispose(),this.rtsInstance=void 0}fetchStreamUrlAndPlay(){return I(this,null,function*(){var e,t,i;this.updateConnectionStatus(ae.AliRtcConnectionStatusConnecting);try{const s=yield fetch(this.roomServerUrl);if(!s.ok){const d=yield s.text();return void this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed, status: ${s.status} ${d}`)}const n=yield s.json();if(T.debug(`[${this.logName}]`,"Query pull uri response:",n),n.code!==0)return void this.handleError("FETCH_STREAM_URL_FAILED",`Business error, code: ${n.code}`);if(!((t=(e=n==null?void 0:n.data)==null?void 0:e.subscribe)!=null&&t.pullstreamurl)||!((i=n==null?void 0:n.data)!=null&&i.tracks))return void this.handleError("NO_STREAM_AVAILABLE","No stream available");const c=`${n.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,o=n.data.tracks.filter(d=>ur(d.msid)).map(d=>d.msid),l=n.data.tracks.filter(d=>pr(d.msid)).map(d=>d.msid);if(o.length===0&&l.length===0)return void this.handleError("NO_STREAM_AVAILABLE","No tracks available");T.info(`[${this.logName}]`,"Fetch stream url success",c,o,l),this.latestStreamInfo={url:c,vMsid:o,aMsid:l},this.preferredL1Ip=n.l1ip,this.rtsInstance=K.AliRTS.createClient(),this.rtsInstance.on("reconnect",d=>{d.retryTimes>=300?this.handleError("SUBSCRIBE_FAILED","reconnect failed"):this.currentStatus!==ae.AliRtcConnectionStatusReconnecting&&(T.warn(`[${this.logName}]`,"reconnecting",d),this.updateConnectionStatus(ae.AliRtcConnectionStatusReconnecting))}),this.rtsInstance.on("hebtReceived",d=>{var h,p;d.recode===0&&((p=(h=d.streams)==null?void 0:h[0])==null?void 0:p.res_code)===200&&this.currentStatus===ae.AliRtcConnectionStatusReconnecting&&(T.warn(`[${this.logName}]`,"reconnect success",d),this.updateConnectionStatus(ae.AliRtcConnectionStatusConnected))});try{if(this._remoteStream=yield this.subscribeWithPreferredL1Fallback(c,{vMsid:o,aMsid:l,heartbeat:{interval:1e3,timeout:5e3},retryTimes:300,beforeRetry:()=>I(this,null,function*(){var h;T.info(`[${this.logName}]`,"Trying to fetch new stream url...");const d=yield fetch(this.roomServerUrl);if(d.status!==400){if(d.ok&&d.status===200){const p=yield d.json();if(T.debug(`[${this.logName}]`,"Query pull uri response:",p),p.code===0&&((h=p.data.subscribe)==null?void 0:h.pullstreamurl)&&p.data.tracks){const u=`${p.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,f=p.data.tracks.filter(S=>ur(S.msid)).map(S=>S.msid),g=p.data.tracks.filter(S=>pr(S.msid)).map(S=>S.msid);if(f.length>0||g.length>0){const S=this.usePreferredL1InRetry?os(u,p.l1ip):u;T.info(`[${this.logName}]`,"Fetch new stream url success",S,f,g,`usePreferredL1InRetry=${this.usePreferredL1InRetry}`),this.latestStreamInfo={url:S,vMsid:f,aMsid:g}}}}return this.latestStreamInfo}{const p=yield d.text();this.handleError("FETCH_STREAM_URL_FAILED",`Fetch new stream url failed, status: ${d.status} ${p}`)}})}),T.info(`[${this.logName}]`,"Subscribe success",this._remoteStream.traceId),this.remoteStream=this.createRemoteStreamProxy(this._remoteStream),this.updateConnectionStatus(ae.AliRtcConnectionStatusConnected),this.startNetworkQualityTimer(),this.config.view){let d;d=typeof this.config.view=="string"?document.getElementById(this.config.view):this.config.view,d instanceof HTMLMediaElement?this._remoteStream.play(d):this.emit("error","INVALID_VIEW_ELEMENT","view is not a media element")}}catch(d){this.handleError("SUBSCRIBE_FAILED",`Subscribe failed: ${d.message}`)}}catch(s){this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed: ${s.message}`)}})}subscribeWithPreferredL1Fallback(e,t){return I(this,null,function*(){const i=os(e,this.preferredL1Ip);if(i!==e){const n=window.__ali_prefer_media_server||this.preferredL1Ip;T.info(`[${this.logName}]`,"Subscribing with preferred media server, ip:",n);const c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rtsInstance.subscribe(i,t),c]);return this.latestStreamInfo.url=i,this.logCandidateProtocol("subscribe (preferred)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${this.logName}]`,"Preferred media server subscribe timeout, falling back to DNS"),this.usePreferredL1InRetry=!1;const l=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe (fallback)"),l}throw o}}const s=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe"),s})}logCandidateProtocol(e){return I(this,null,function*(){var t,i,s;try{const n=(s=(i=(t=this.rtsInstance)==null?void 0:t.commonController)==null?void 0:i.peerCore)==null?void 0:s.pc;if(!n)return void T.debug(`[${this.logName}]`,`${e} - PC not available`);const c=yield n.getStats();let o,l,d,h;c.forEach(p=>{p.type==="candidate-pair"&&p.state==="succeeded"&&p.nominated&&(o=p.localCandidateId,l=p.remoteCandidateId)}),o||l||c.forEach(p=>{p.type!=="candidate-pair"||p.state!=="succeeded"&&p.state!=="in-progress"||o||(o=p.localCandidateId,l=p.remoteCandidateId)}),c.forEach(p=>{p.type==="local-candidate"&&p.id===o&&(d=p.protocol),p.type==="remote-candidate"&&p.id===l&&(h=p.protocol)}),T.info(`[${this.logName}]`,`${e} - Candidate Protocol: local=${d||"unknown"}, remote=${h||"unknown"}`)}catch(n){T.warn(`[${this.logName}]`,`${e} - Failed to get candidate protocol:`,n)}})}createRemoteStreamProxy(e){const t=this.logName;return new Proxy(e,{get(i,s,n){const c=Reflect.get(i,s,n);return typeof c=="function"?function(...o){T.interface(`[${t}]`,`remoteStream.${String(s)} called`,o.length>0?o:"");const l=c.apply(i,o);return l instanceof Promise?l.then(d=>(T.info(`[${t}]`,`remoteStream.${String(s)} resolved`,d!==void 0?d:""),d),d=>{throw T.error(`[${t}]`,`remoteStream.${String(s)} rejected`,d),d}):l}:c}})}startNetworkQualityTimer(){this.stopNetworkQualityTimer(),this._prevDownlinkStat=void 0,this.networkQualityTimer=setInterval(()=>I(this,null,function*(){if(this.currentStatus===ae.AliRtcConnectionStatusConnected)try{const e=yield this.getNetworkQuality();this.emit("networkQuality",e)}catch(e){T.warn(`[${this.logName}]`,"Failed to get network quality:",e)}}),2e3)}stopNetworkQualityTimer(){this.networkQualityTimer&&(clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0)}getNetworkQuality(){return I(this,null,function*(){var u,f,g;const e=(g=(f=(u=this.rtsInstance)==null?void 0:u.commonController)==null?void 0:f.peerCore)==null?void 0:g.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:Ze.AliRtcNetworkDisconnected};let t=0,i=0,s=0;const n=e.getReceivers();for(const S of n)(yield S.getStats()).forEach(b=>{b.type==="candidate-pair"&&typeof b.currentRoundTripTime=="number"&&(t=Math.round(1e3*b.currentRoundTripTime)),b.type!=="inbound-rtp"||b.mediaType!=="audio"&&b.mediaType!=="video"||(i+=b.packetsLost||0,s+=b.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:0,quality:Ze.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=s-o;let h=0;l>0&&d>=0&&(h=Math.round(l/(l+d)*100));const p=cs(h,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:h,quality:p}})}dispose(){T.info(`[${this.logName}]`,"dispose"),this.stopNetworkQualityTimer(),this.updateConnectionStatus(ae.AliRtcConnectionStatusDisconnected),this.rtsInstance&&this.rtsInstance.dispose()}};m(es,"logName","RemoteStreamHandler");let bs=es;var Ss={exports:{}};(function(a,r){(function(e,t){var i="function",s="undefined",n="object",c="string",o="major",l="model",d="name",h="type",p="vendor",u="version",f="architecture",g="console",S="mobile",b="tablet",v="smarttv",R="wearable",_="embedded",y="Amazon",A="Apple",w="ASUS",E="BlackBerry",C="Browser",P="Chrome",D="Firefox",U="Google",G="Huawei",Y="LG",q="Microsoft",W="Motorola",Z="Opera",te="Samsung",be="Sharp",L="Sony",x="Xiaomi",N="Zebra",V="Facebook",ue="Chromium OS",Le="Mac OS",J=" Browser",ve=function(le){for(var ne={},ie=0;ie<le.length;ie++)ne[le[ie].toUpperCase()]=le[ie];return ne},xe=function(le,ne){return typeof le===c&&Ee(ne).indexOf(Ee(le))!==-1},Ee=function(le){return le.toLowerCase()},Me=function(le,ne){if(typeof le===c)return le=le.replace(/^\s\s*/,""),typeof ne===s?le:le.substring(0,500)},ye=function(le,ne){for(var ie,Re,Be,me,Ke,Q,Ve=0;Ve<ne.length&&!Ke;){var ht=ne[Ve],Oe=ne[Ve+1];for(ie=Re=0;ie<ht.length&&!Ke&&ht[ie];)if(Ke=ht[ie++].exec(le))for(Be=0;Be<Oe.length;Be++)Q=Ke[++Re],typeof(me=Oe[Be])===n&&me.length>0?me.length===2?typeof me[1]==i?this[me[0]]=me[1].call(this,Q):this[me[0]]=me[1]:me.length===3?typeof me[1]!==i||me[1].exec&&me[1].test?this[me[0]]=Q?Q.replace(me[1],me[2]):t:this[me[0]]=Q?me[1].call(this,Q,me[2]):t:me.length===4&&(this[me[0]]=Q?me[3].call(this,Q.replace(me[1],me[2])):t):this[me]=Q||t;Ve+=2}},Te=function(le,ne){for(var ie in ne)if(typeof ne[ie]===n&&ne[ie].length>0){for(var Re=0;Re<ne[ie].length;Re++)if(xe(ne[ie][Re],le))return ie==="?"?t:ie}else if(xe(ne[ie],le))return ie==="?"?t:ie;return ne.hasOwnProperty("*")?ne["*"]:le},pe={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Ne={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,u],[/opios[\/ ]+([\w\.]+)/i],[u,[d,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[u,[d,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[u,[d,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[u,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[u,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,u],[/quark(?:pc)?\/([-\w\.]+)/i],[u,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[u,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[d,"UC"+C]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[u,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[u,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[u,[d,"Smart Lenovo "+C]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+C],u],[/\bfocus\/([\w\.]+)/i],[u,[d,D+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[d,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[d,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[d,"MIUI"+J]],[/fxios\/([\w\.-]+)/i],[u,[d,D]],[/\bqihoobrowser\/?([\w\.]*)/i],[u,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],u],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+J],u],[/samsungbrowser\/([\w\.]+)/i],[u,[d,te+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[u,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,u],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[u,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,V],u],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[u,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[d,"Android "+C]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[u,Te,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[d,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],u],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[d,D+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[d,[u,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,Ee]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",Ee]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,Ee]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[p,te],[h,b]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[l,[p,te],[h,S]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[p,A],[h,S]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[p,A],[h,b]],[/(macintosh);/i],[l,[p,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[p,be],[h,S]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[p,"Honor"],[h,S]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[p,G],[h,b]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[p,G],[h,S]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[l,/_/g," "],[p,x],[h,S]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[p,x],[h,b]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[p,"OPPO"],[h,S]],[/\b(opd2\d{3}a?) bui/i],[l,[p,"OPPO"],[h,b]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[p,"Vivo"],[h,S]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[p,"Realme"],[h,S]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[p,W],[h,S]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[p,W],[h,b]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[p,Y],[h,b]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[p,Y],[h,S]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[p,"Lenovo"],[h,b]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[p,"Nokia"],[h,S]],[/(pixel c)\b/i],[l,[p,U],[h,b]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[p,U],[h,S]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[p,L],[h,S]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[p,L],[h,b]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[p,"OnePlus"],[h,S]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[p,y],[h,b]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[p,y],[h,S]],[/(playbook);[-\w\),; ]+(rim)/i],[l,p,[h,b]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[p,E],[h,S]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[p,w],[h,b]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[p,w],[h,S]],[/(nexus 9)/i],[l,[p,"HTC"],[h,b]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[l,/_/g," "],[h,S]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[l,[p,"TCL"],[h,b]],[/(itel) ((\w+))/i],[[p,Ee],l,[h,Te,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[p,"Acer"],[h,b]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[p,"Meizu"],[h,S]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[p,"Ulefone"],[h,S]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[p,"Energizer"],[h,S]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[p,"Cat"],[h,S]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[p,"Smartfren"],[h,S]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[p,"Nothing"],[h,S]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,l,[h,S]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,l,[h,b]],[/(surface duo)/i],[l,[p,q],[h,b]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[p,"Fairphone"],[h,S]],[/(u304aa)/i],[l,[p,"AT&T"],[h,S]],[/\bsie-(\w*)/i],[l,[p,"Siemens"],[h,S]],[/\b(rct\w+) b/i],[l,[p,"RCA"],[h,b]],[/\b(venue[\d ]{2,7}) b/i],[l,[p,"Dell"],[h,b]],[/\b(q(?:mv|ta)\w+) b/i],[l,[p,"Verizon"],[h,b]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[p,"Barnes & Noble"],[h,b]],[/\b(tm\d{3}\w+) b/i],[l,[p,"NuVision"],[h,b]],[/\b(k88) b/i],[l,[p,"ZTE"],[h,b]],[/\b(nx\d{3}j) b/i],[l,[p,"ZTE"],[h,S]],[/\b(gen\d{3}) b.+49h/i],[l,[p,"Swiss"],[h,S]],[/\b(zur\d{3}) b/i],[l,[p,"Swiss"],[h,b]],[/\b((zeki)?tb.*\b) b/i],[l,[p,"Zeki"],[h,b]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],l,[h,b]],[/\b(ns-?\w{0,9}) b/i],[l,[p,"Insignia"],[h,b]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[p,"NextBook"],[h,b]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],l,[h,S]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],l,[h,S]],[/\b(ph-1) /i],[l,[p,"Essential"],[h,S]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[p,"Envizen"],[h,b]],[/\b(trio[-\w\. ]+) b/i],[l,[p,"MachSpeed"],[h,b]],[/\btu_(1491) b/i],[l,[p,"Rotor"],[h,b]],[/(shield[\w ]+) b/i],[l,[p,"Nvidia"],[h,b]],[/(sprint) (\w+)/i],[p,l,[h,S]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[p,q],[h,S]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[p,N],[h,b]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[p,N],[h,S]],[/smart-tv.+(samsung)/i],[p,[h,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[p,te],[h,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Y],[h,v]],[/(apple) ?tv/i],[p,[l,A+" TV"],[h,v]],[/crkey/i],[[l,P+"cast"],[p,U],[h,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[p,y],[h,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[p,be],[h,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[p,L],[h,v]],[/(mitv-\w{5}) bui/i],[l,[p,x],[h,v]],[/Hbbtv.*(technisat) (.*);/i],[p,l,[h,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,Me],[l,Me],[h,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,l,[h,g]],[/droid.+; (shield) bui/i],[l,[p,"Nvidia"],[h,g]],[/(playstation [345portablevi]+)/i],[l,[p,L],[h,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[p,q],[h,g]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[p,te],[h,R]],[/((pebble))app/i],[p,l,[h,R]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[p,A],[h,R]],[/droid.+; (glass) \d/i],[l,[p,U],[h,R]],[/droid.+; (wt63?0{2,3})\)/i],[l,[p,N],[h,R]],[/droid.+; (glass) \d/i],[l,[p,U],[h,R]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,l,[h,R]],[/; (quest( \d| pro)?)/i],[l,[p,V],[h,R]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[h,_]],[/(aeobc)\b/i],[l,[p,y],[h,_]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[h,S]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[h,b]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,b]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,S]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,u],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,u],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[u,Te,pe]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,Te,pe],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,Le],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,u],[/\(bb(10);/i],[u,[d,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[d,D+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,ue],u],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,u],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],u],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,u]]},we=function(le,ne){if(typeof le===n&&(ne=le,le=t),!(this instanceof we))return new we(le,ne).getResult();var ie=typeof e!==s&&e.navigator?e.navigator:t,Re=le||(ie&&ie.userAgent?ie.userAgent:""),Be=ie&&ie.userAgentData?ie.userAgentData:t,me=ne?function(Q,Ve){var ht={};for(var Oe in Q)Ve[Oe]&&Ve[Oe].length%2==0?ht[Oe]=Ve[Oe].concat(Q[Oe]):ht[Oe]=Q[Oe];return ht}(Ne,ne):Ne,Ke=ie&&ie.userAgent==Re;return this.getBrowser=function(){var Q,Ve={};return Ve[d]=t,Ve[u]=t,ye.call(Ve,Re,me.browser),Ve[o]=typeof(Q=Ve[u])===c?Q.replace(/[^\d\.]/g,"").split(".")[0]:t,Ke&&ie&&ie.brave&&typeof ie.brave.isBrave==i&&(Ve[d]="Brave"),Ve},this.getCPU=function(){var Q={};return Q[f]=t,ye.call(Q,Re,me.cpu),Q},this.getDevice=function(){var Q={};return Q[p]=t,Q[l]=t,Q[h]=t,ye.call(Q,Re,me.device),Ke&&!Q[h]&&Be&&Be.mobile&&(Q[h]=S),Ke&&Q[l]=="Macintosh"&&ie&&typeof ie.standalone!==s&&ie.maxTouchPoints&&ie.maxTouchPoints>2&&(Q[l]="iPad",Q[h]=b),Q},this.getEngine=function(){var Q={};return Q[d]=t,Q[u]=t,ye.call(Q,Re,me.engine),Q},this.getOS=function(){var Q={};return Q[d]=t,Q[u]=t,ye.call(Q,Re,me.os),Ke&&!Q[d]&&Be&&Be.platform&&Be.platform!="Unknown"&&(Q[d]=Be.platform.replace(/chrome os/i,ue).replace(/macos/i,Le)),Q},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Re},this.setUA=function(Q){return Re=typeof Q===c&&Q.length>500?Me(Q,500):Q,this},this.setUA(Re),this};we.VERSION="1.0.40",we.BROWSER=ve([d,u,o]),we.CPU=ve([f]),we.DEVICE=ve([l,p,h,g,S,v,b,R,_]),we.ENGINE=we.OS=ve([d,u]),a.exports&&(r=a.exports=we),r.UAParser=we;var Xe=typeof e!==s&&(e.jQuery||e.Zepto);if(Xe&&!Xe.ua){var dt=new we;Xe.ua=dt.getResult(),Xe.ua.get=function(){return dt.getUA()},Xe.ua.set=function(le){dt.setUA(le);var ne=dt.getResult();for(var ie in ne)Xe.ua[ie]=ne[ie]}}})(typeof window=="object"?window:Bi)})(Ss,Ss.exports);var tc=Ss.exports,Fe=(a=>(a.KEEPALIVE="keepalive",a.JOINCHANNEL="joinchannel",a.NOTIFYJOIN="notifyjoin",a.NOTIFYSTATUS="notifystatus",a.STATUSREPORT="statusreport",a.LEAVECHANNEL="leavechannel",a.NOTIFYLEAVE="notifyleave",a.NOTIFYPUBLISH="notifypublish",a.BYE="bye",a.RECONNECT="reconnect",a.PUBLISH="publish",a.REFRESHURL="refreshurl",a.UNSUBSCRIBE="unsubscribe",a.ROLEUPDATE="roleupdate",a))(Fe||{});class Wi{constructor(r,e){m(this,"authInfo");m(this,"userName");m(this,"seqIndex",0);this.authInfo=r,this.userName=typeof e=="number"?e.toString():e}get roleAuth(){if(this.authInfo.role){const{timestamp:r,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:r,nonce:e,token:t,tokenrole:i}}}static get adaptInfo(){var e,t,i,s;let r=new tc.UAParser().getResult();return{os_name:((e=r.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=r.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=r.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((s=r.device.vendor)==null?void 0:s.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:r.browser.version||"",sdk_version:"7.2.8-beta.3",version:"v1"}}refreshAuthInfo(r){this.authInfo=r}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(r){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=De.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Wi.adaptInfo,r&&(e.data=X(X({},e.data),r)),e}createLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(r){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=r,e}createPublishPackage(){let r=this.createBaseSendPackage("publish");return r.data.users=[{}],this.roleAuth&&(r.data.auth=this.roleAuth),r}createRoleUpdatePackage(){let r=this.createBaseSendPackage("roleupdate");return r.header.displayName=this.userName,r}createReconnectPackage(r){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=De.getVersionNumber().toString(),e.header.platform="web",e.data=X(X({},e.data),r!=null?r:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let r=this.createBaseSendPackage("refreshurl");return r.header.displayName=this.userName,r}createResponsePackage(r,e){return{version:1,code:200,tid:r,msgtype:e}}createBaseSendPackage(r){var e;return++this.seqIndex,{version:1,msgtype:r,tid:ut(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}const La="ALI_RTC_SDK_ALLOCATE_RESULT",Si=class Si{constructor(r,e,t){m(this,"result",null);m(this,"pms",null);m(this,"env");m(this,"config");m(this,"joinMode");this.env=r,this.config=e,this.joinMode=t;let i=localStorage.getItem(La);if(i){const s=JSON.parse(i);s.appId===e.appId&&s.expireTs-3e5>Date.now()?this.result=s.allocatedData:T.info(`[${Si.logName}]`,"allocate","cached data is invalid")}}fetchAndUpdate(){if(this.pms)return this.pms;const{appId:r,channelId:e,sessionId:t,userId:i,timestamp:s,token:n,nonce:c}=this.config,o=new URLSearchParams({appid:r,channelid:e,session:t,userid:i,timestamp:`${s}`,token:n,nonce:c!=null?c:"",adapt:"true",clitype:"2"});this.joinMode&&o.set("joinmode",this.joinMode);const l=this.env===wt.pre?St.pre:St.prod;return this.pms=fetch(`https://${l}/gslb/v1/allocate?${o.toString()}`,{method:"POST",body:JSON.stringify(Wi.adaptInfo)}).then(d=>d.json()).then(d=>{if(d.code===0){const h=d.data;this.result=h;const{ice_ufrag:p}=h.h5auth,[u,f]=atob(p).split("_"),g={appId:r,expireTs:1e3*parseInt(f),allocatedData:h};return T.info(`[${Si.logName}]`,"got allocate result and save",h.h5auth.ice_ufrag),localStorage.setItem(La,JSON.stringify(g)),h}return null}).catch(d=>(T.error(`[${Si.logName}]`,"allocate",d),null)),this.pms}};m(Si,"logName","Allocator");let wi=Si;class vs{constructor(r,e){m(this,"originTrack");m(this,"originVideo");m(this,"targetWidth");m(this,"targetHeight");m(this,"targetFrameRate");m(this,"targetCanvas");m(this,"animationFrameId");m(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=r,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(r){this.targetWidth=r.width,this.targetHeight=r.height,this.targetFrameRate=r.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(r,e,t,i){const s=e/r,n=i/t;let c=t,o=i,l=0,d=0;return n>s?(c=Math.round(o/s),l=Math.round((t-c)/2)):n<s&&(o=Math.round(c*s),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class ic extends vs{constructor(e,t){super(e,t);m(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function Na(a,r,e){const t=a.createShader(r);if(t)return a.shaderSource(t,e),a.compileShader(t),a.getShaderParameter(t,a.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${a.getShaderInfoLog(t)}`),a.deleteShader(t),null);console.error("create shader failed")}class xa extends vs{constructor(e,t){super(e,t);m(this,"targetCtx");m(this,"targetTexture");m(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const h=Na(o,o.VERTEX_SHADER,l),p=Na(o,o.FRAGMENT_SHADER,d),u=o.createProgram();if(u&&h&&p)return o.attachShader(u,h),o.attachShader(u,p),o.linkProgram(u),o.getProgramParameter(u,o.LINK_STATUS)?u:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(u)}`),null)}(e,`
13
13
  attribute vec2 a_position;
14
14
  attribute vec2 a_texCoord;
15
15
 
@@ -39,7 +39,7 @@ uniform sampler2D u_texture;
39
39
  void main() {
40
40
  gl_FragColor = texture2D(u_texture, v_texCoord);
41
41
  }
42
- `);if(!t)return void console.log("[ScalerWebGL] program is null.");e.useProgram(t);const i=e.getAttribLocation(t,"a_position"),r=e.getAttribLocation(t,"a_texCoord"),n=e.getUniformLocation(t,"u_resolution");if(!n)return void console.log("[ScalerWebGL] resolutionLocation is null.");const c=e.getUniformLocation(t,"u_texture");c?(this.locationMap={program:t,positionLocation:i,texCoordLocation:r,resolutionLocation:n,textureLocation:c},this.updateBuffer()):console.log("[ScalerWebGL] textureLocation is null.")}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender),this.originVideo.addEventListener("resize",this.updateBuffer)}startRender(){this.cancelAnimation();const e=()=>{this.targetCtx&&(this.renderTexture(),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e)))};e()}updateBuffer(){const e=this.targetCtx,t=this.locationMap.positionLocation,i=this.locationMap.texCoordLocation,r=this.locationMap.resolutionLocation;if(!e||!this.originVideo.videoWidth||!this.originVideo.videoHeight)return;const n=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight),c=function(l,d,u,p=0,h=0){const f=l.createBuffer();l.bindBuffer(l.ARRAY_BUFFER,f);const g=d+p,S=u+h,b=[p,h,g,h,p,S,p,S,g,h,g,S];return l.bufferData(l.ARRAY_BUFFER,new Float32Array(b),l.STATIC_DRAW),f}(e,n.width,n.height,n.x,n.y);e.enableVertexAttribArray(t),e.bindBuffer(e.ARRAY_BUFFER,c),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(i);const o=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,o),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,o),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0),e.uniform2f(r,this.targetWidth,this.targetHeight)}renderTexture(){const e=this.targetTexture,t=this.targetCtx,i=this.locationMap.textureLocation;e&&t&&(t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.originVideo),t.useProgram(this.locationMap.program),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(i,0),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,6))}stopRender(){this.cancelAnimation()}updateOptions(e){super.updateOptions(e),this.updateBuffer()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.removeEventListener("resize",this.updateBuffer),this.originVideo.pause(),this.originVideo.srcObject=null}}class Ea extends ur{constructor(e,t){super(e,t);m(this,"processor");m(this,"trackGenerator");m(this,"worker");this.processor=new MediaStreamTrackProcessor({track:e}),this.trackGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.startTransform()}static isSupport(){return"MediaStreamTrackProcessor"in window&&"MediaStreamTrackGenerator"in window&&"TransformStream"in window&&"VideoFrame"in window}startTransform(){const e=new Blob([`
42
+ `);if(!t)return void console.log("[ScalerWebGL] program is null.");e.useProgram(t);const i=e.getAttribLocation(t,"a_position"),s=e.getAttribLocation(t,"a_texCoord"),n=e.getUniformLocation(t,"u_resolution");if(!n)return void console.log("[ScalerWebGL] resolutionLocation is null.");const c=e.getUniformLocation(t,"u_texture");c?(this.locationMap={program:t,positionLocation:i,texCoordLocation:s,resolutionLocation:n,textureLocation:c},this.updateBuffer()):console.log("[ScalerWebGL] textureLocation is null.")}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender),this.originVideo.addEventListener("resize",this.updateBuffer)}startRender(){this.cancelAnimation();const e=()=>{this.targetCtx&&(this.renderTexture(),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e)))};e()}updateBuffer(){const e=this.targetCtx,t=this.locationMap.positionLocation,i=this.locationMap.texCoordLocation,s=this.locationMap.resolutionLocation;if(!e||!this.originVideo.videoWidth||!this.originVideo.videoHeight)return;const n=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight),c=function(l,d,h,p=0,u=0){const f=l.createBuffer();l.bindBuffer(l.ARRAY_BUFFER,f);const g=d+p,S=h+u,b=[p,u,g,u,p,S,p,S,g,u,g,S];return l.bufferData(l.ARRAY_BUFFER,new Float32Array(b),l.STATIC_DRAW),f}(e,n.width,n.height,n.x,n.y);e.enableVertexAttribArray(t),e.bindBuffer(e.ARRAY_BUFFER,c),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(i);const o=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,o),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,o),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0),e.uniform2f(s,this.targetWidth,this.targetHeight)}renderTexture(){const e=this.targetTexture,t=this.targetCtx,i=this.locationMap.textureLocation;e&&t&&(t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.originVideo),t.useProgram(this.locationMap.program),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(i,0),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,6))}stopRender(){this.cancelAnimation()}updateOptions(e){super.updateOptions(e),this.updateBuffer()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.removeEventListener("resize",this.updateBuffer),this.originVideo.pause(),this.originVideo.srcObject=null}}class Va extends vs{constructor(e,t){super(e,t);m(this,"processor");m(this,"trackGenerator");m(this,"worker");this.processor=new MediaStreamTrackProcessor({track:e}),this.trackGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.startTransform()}static isSupport(){return"MediaStreamTrackProcessor"in window&&"MediaStreamTrackGenerator"in window&&"TransformStream"in window&&"VideoFrame"in window}startTransform(){const e=new Blob([`
43
43
  var targetOptions={
44
44
  width: 320,
45
45
  height: 180,
@@ -124,14 +124,14 @@ onmessage = function(evt) {
124
124
  break;
125
125
  }
126
126
  }
127
- `],{type:"text/javascript"}),t=(window.URL||window.webkitURL).createObjectURL(e);this.worker=new Worker(t);const{readable:i}=this.processor,{writable:r}=this.trackGenerator;this.worker.postMessage({type:"startRender",readable:i,writable:r,width:this.targetWidth,height:this.targetHeight,frameRate:this.targetFrameRate},[i,r])}updateOptions(e){super.updateOptions(e),this.worker&&this.worker.postMessage(X({type:"updateOptions"},e))}dispose(){try{this.processor.readable.cancel(),this.trackGenerator.writable.close()}catch(e){}}getVideoTrack(){return this.trackGenerator}}class hr{static isSupport(){return typeof HTMLCanvasElement.prototype.captureStream=="function"}static getInstance(s,e){return Ea.isSupport()?new Ea(s,e):_a.isSupport()?new _a(s,e):new Ko(s,e)}}var Ta,Ia,Jo=Object.defineProperty,qo=Object.defineProperties,Go=Object.getOwnPropertyDescriptors,Ca=Object.getOwnPropertySymbols,Xo=Object.prototype.hasOwnProperty,Yo=Object.prototype.propertyIsEnumerable,pr=(a,s,e)=>s in a?Jo(a,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[s]=e,mr=(a,s)=>{for(var e in s||(s={}))Xo.call(s,e)&&pr(a,e,s[e]);if(Ca)for(var e of Ca(s))Yo.call(s,e)&&pr(a,e,s[e]);return a},Xt=(a,s,e)=>(pr(a,typeof s!="symbol"?s+"":s,e),e),gr={exports:{}},fr={exports:{}};function et(){if(Ia)return Ta;Ia=1,Date.now=Date.now||function(){return new Date().getTime()};var a=Date.now(),s=function(){},e={noop:s,warn:function(){var t=typeof console=="object"?console.warn:s;try{var i={warn:t};i.warn.call(i)}catch(r){return s}return t}(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:typeof window=="object"&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",daily_3:"http://arms-retcode-daily.aliyun.test/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(t){if(Object.create)return Object.create(t);var i=function(){};return i.prototype=t,new i},each:function(t,i){var r=0,n=t.length;if(this.T(t,"Array"))for(;r<n&&i.call(t[r],t[r],r)!==!1;r++);else for(r in t)if(i.call(t[r],t[r],r)===!1)break;return t},safetyCall:function(t,i,r){if(typeof t!="function")return r;try{return t.apply(this,i)}catch(n){return r}},T:function(t,i){var r=Object.prototype.toString.call(t).substring(8).replace("]","");return i?r===i:r},duration:function(){var t=Date;try{performance&&this.T(performance.now,"Function")&&(t=performance)}catch(r){t=Date}var i=t.now();return function(){return Math.round(t.now()-i)}},filterByRule:function(){var t=[].slice.call(arguments),i=t.length;if(i<2)return t[0];var r=t[i-1],n=t[0];if(!n)return"";if(!r)return n;var c=this,o=c.T(r),l=t.slice(0,i-1);return o==="Function"?c.safetyCall(r,l,n):o==="Array"?(this.each(r,function(d){l[0]=n=c.filterByRule.apply(c,[].concat(l,d))}),n):o==="Object"?n.replace(r.rule,r.target||""):n.replace(r,"")},ignoreByRule:function(t,i){if(!t||!i)return!1;if((this.isString(i)||i.source||this.T(i)==="Function")&&(i=[i]),!this.isArray(i))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var r,n=[],c=0,o=i.length;c<o;c++)if(r=i[c],this.isString(r))n.push(r.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(r&&r.source)n.push(r.source);else if(r&&this.T(r)==="Function"&&this.safetyCall(r,[t],!1)===!0)return!0;var l=new RegExp(n.join("|"),"i");return!!(n.length&&l.test&&l.test(t))},J:function(t){if(!t||typeof t!="string")return t;var i=null;try{i=JSON.parse(t)}catch(r){}return i},pick:function(t){return t===1||Math.ceil(Math.random()*t)===1},verifyConfig:function(t){if("sample"in t){var i=t.sample,r=i;i&&/^\d+(\.\d+)?%$/.test(i)&&(r=parseInt(100/parseFloat(i))),0<r&&1>r&&(r=parseInt(1/r)),r>=1&&r<=100?t.sample=r:delete t.sample}return t},on:function(t,i,r,n,c){return t.addEventListener?(c=c||!1,t.addEventListener(i,function o(l){n&&t.removeEventListener(i,o,c),r.call(this,l)},c)):t.attachEvent&&t.attachEvent("on"+i,function o(l){n&&t.detachEvent("on"+i,o),r.call(this,l)}),this},off:function(t,i,r){return r?(t.removeEventListener?t.removeEventListener(i,r):t.detachEvent&&t.detachEvent(i,r),this):this},delay:function(t,i){return i===-1?(t(),null):setTimeout(t,i||0)},ext:function(t){for(var i=1,r=arguments.length;i<r;i++){var n=arguments[i];for(var c in n)Object.prototype.hasOwnProperty.call(n,c)&&(t[c]=n[c])}return t},sub:function(t,i){var r={};return this.each(t,function(n,c){i.indexOf(c)!==-1&&(r[c]=n)}),r},uu:function(){for(var t,i,r=20,n=new Array(r),c=Date.now().toString(36).split("");r-- >0;)i=(t=36*Math.random()|0).toString(36),n[r]=t%3?i:i.toUpperCase();for(var o=0;o<8;o++)n.splice(3*o+2,0,c[o]);return n.join("")},guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var i=16*Math.random()|0;return(t==="x"?i:3&i|8).toString(16)})},seq:function(){return(a++).toString(36)},decode:function(t){try{t=decodeURIComponent(t)}catch(i){}return t},encode:function(t,i){try{t=i?encodeURIComponent(t).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(t)}catch(r){}return t},serialize:function(t){t=t||{};var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&t[r]!==void 0&&i.push(r+"="+this.encode(t[r],r==="msg"));return i.join("&")},checkAPI:function(t,i){if(!t||typeof t!="string")return!1;var r=/arms-retcode[\w-]*\.aliyuncs/.test(t);return!r&&i&&(r=/(alicdn\.com)|(mmstat\.com)/.test(t)),!r},checkAutoError:function(t){return!(!t||!t.message||/failed[\w\s]+fetch/i.test(t.message))},cutUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/\?.*$/,""):""},createFakeToString:function(t){return function(){return t+"() { [native code] }"}},checkSameOrigin:function(t,i){if(!i||!t)return!1;var r="//"+i.split("/")[2];return t===i||t.slice(0,i.length+1)===i+"/"||t===r||t.slice(0,r.length+1)===r+"/"||!/^(\/\/|http:|https:).*/.test(t)},getRandIP:function(){for(var t=[],i=0;i<4;i++){var r=Math.floor(256*Math.random());t[i]=(r>15?"":"0")+r.toString(16)}return t.join("").replace(/^0/,"1")},getSortNum:function(t){return t?(t+=1)>=1e3&&t<=9999?t:t<1e3?t+1e3:t%1e4+1e3:1e3},getRandNum:function(t){return t&&typeof t=="string"?t.length<5?this.getNum(5):t.substring(t.length-5):this.getNum(5)},getNum:function(t){for(var i=[],r=0;r<t;r++){var n=Math.floor(16*Math.random());i[r]=n.toString(16)}return i.join("")},getCurDomain:function(){return location&&location.hostname||""},getSrcType:function(t,i){var r=location&&location.host||"";if(!r)return"";var n=new URL(t).host;if(n===r)return"self";for(var c=0;c<i.length;c+=1)if(n.includes(i[c]))return"cdn";return"others"},parseFetchHeaders:function(t){if(!t)return{};var i={};try{if(typeof t.keys=="function")for(var r=t.keys(),n=r.next();!n.done;){var c=n.value;i[c]=t.get(c),n=r.next()}else i=t}catch(o){i={}}return i},parseXhrHeaders:function(t){if(!t&&typeof t!="string")return{};var i={};try{i=t.split(`\r
128
- `).reduce(function(r,n){var c=n.split(": ");return r[c[0]]=c[1],r},{})}catch(r){i={}}return i},getQuerys:function(t){if(!t)return"";var i={},r=[],n="",c="";try{var o=[];if(t.indexOf("?")>=0&&(o=t.substring(t.indexOf("?")+1,t.length).split("&")),o.length>0)for(var l in o)n=(r=o[l].split("="))[0],c=r[1],i[n]=c}catch(d){i={}}return i},getURL:function(t){if(!t)return null;var i={},r=t.length,n=t.indexOf("://");if(n<0)return null;i.protocol=t.substring(0,n+1);var c=t.indexOf("#"),o=t.indexOf("?");c<0&&(c=r),o<0&&(o=c),i.search=t.substring(o,c).substring(0,1e3);var l=t.substring(n+3,o),d=l.indexOf("/");return d<0&&(d=l.length),i.domain=l.substring(0,d).split(":")[0],i.path=l.substring(d,l.length).substring(0,1e3),i},getResType:function(t,i){if(["script","img","other"].indexOf(t)>-1)return t;if(["video"].indexOf(t)>-1)return"media";if(["document","iframe"].indexOf(t)>-1)return"doc";var r=i?this.getURL(i):null,n=r&&r.path?r.path.lastIndexOf("."):-1,c=(n>0?r.path.substr(n+1):"").toLowerCase();if(c){if(["eot","woff","woff2","ttf"].indexOf(c)>-1)return"font";if(c==="css")return"css";if(c==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(t)>-1?"api":"others"},areInOrder:function(){for(var t=1;t<arguments.length;t+=1)if(arguments[t-1]>arguments[t])return!1;return!0},getFetchSnapshot:function(t,i,r){var n,c;try{var o=(t&&typeof t[0]!="string"?t[0].url:t[0])||"",l=(t&&typeof t[0]!="string"?t[0]:t[1])||{},d=l.method.toUpperCase()==="POST"?l.body:this.getQuerys(o);n={originApi:o,method:l.method||"unknown",params:d,response:i||"",reqHeaders:this.parseFetchHeaders(l.headers||null),resHeaders:this.parseFetchHeaders(r)},c=JSON&&JSON.stringify(n)||"{}"}catch(u){c="{}"}return c},getXhrSnapshot:function(t,i,r){if(!t||!i||!r)return{};var n,c;try{var o="";r.responseType===""||r.responseType==="text"?o=r.responseText:r.responseType==="document"&&(o=r.responseXML),n={originApi:t,method:i,params:this.getQuerys(t),response:o,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof r.getAllResponseHeaders=="function"&&r.getAllResponseHeaders()||"")},c=JSON&&JSON.stringify(n)||"{}"}catch(l){c="{}"}return c},isRobot:function(){var t=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var i=navigator.userAgent.toLowerCase(),r=0;r<t.length;r++){var n=t[r];if(i.lastIndexOf(n)>=0)return!0}}catch(c){this.warn("[arms] useragent parse error")}return!1},isFunction:function(t){return typeof t=="function"},isPlainObject:function(t){return Object.prototype.toString.call(t)==="[object Object]"},isString:function(t){return Object.prototype.toString.call(t)==="[object String]"},isArray:function(t){return Object.prototype.toString.call(t)==="[object Array]"},joinRegExp:function(t){for(var i,r=[],n=0,c=t.length;n<c;n++)i=t[n],this.isString(i)?r.push(i.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):i&&i.source&&r.push(i.source);return new RegExp(r.join("|"),"i")},reWriteMethod:function(t,i,r){if(t!==null){var n=t[i];t[i]=r(n)}},checkSDKError:function(t,i){return!(!t&&!i)&&(!!new RegExp(this.selfErrKey,"i").test(t)||!!this.ignoreByRule(i,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/]))},sdkError:function(t){return{msg:t,message:this.selfErrKey}},dealParam:function(t,i,r){var n={};try{n=this.isPlainObject(t)?this.ext({key:t.key||"default",val:t.val||t.value||r},t,{begin:Date.now()}):{key:t||"default",val:i||r,begin:Date.now()}}catch(c){this.warn("[retcode] baseLog error: "+c)}return n}};return Ta=e}var ka,Pa,Da,Ma,Sr={exports:{}},br={exports:{}};function Qo(){if(Da)return br.exports;Da=1;var a=et(),s=function(){if(Pa)return ka;Pa=1;var r=et();return ka=function(n,c,o){typeof n=="object"&&(n=r.serialize(n));var l=c+n+(o?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(l,o||"&post_res="):r.warn("[arms] navigator.sendBeacon not surported")}}(),e="aokcdqn3ly@e629dabd48a9933",t=function(r,n){var c;if(n.t==="error"&&(c=r.requestQueue[0])&&c.t==="error"&&n.msg===c.msg)return n.times=c.times+1,void(r.requestQueue[0]=n);if(n.t==="behavior"){var o=r.requestQueue&&r.requestQueue.length;if(o>0&&r.requestQueue[o-1].t==="behavior"){var l=n.behavior||[];r.requestQueue[o-1].behavior.concat(l)}else r.requestQueue.push(n)}else r.requestQueue.unshift(n);return r.onReady(function(){r.requestTimmer=a.delay(function(){r.clear()},r.requestQueue[0]&&r.requestQueue[0].t==="error"?3e3:-1)}),!0},i=function(r){return this.ver="1.8.36-beta.12",this._conf=a.ext({},i.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=a.seq(),this.resetPageview(),this.setConfig(r),this.rip=a.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};return i.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},i.prototype={constructor:i,onReady:function(r){return r()},getPage:function(){var r=this._conf.page;return a.safetyCall(r,[],r+"")},setPage:function(){},setConfig:function(r){r&&typeof r=="object"&&(a.verifyConfig(r),r=this.setImgUrl(r),this._conf=a.ext({},this._conf,r))},setImgUrl:function(r){var n=r.region,c=r.imgUrl;if(n){var o=a.regionMap[n];return r.imgUrl=o||a.defaultImgUrl,r}return c&&(r.imgUrl=c),r},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(r,n,c){s(r,n||this.getConfig("imgUrl"),c)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(r){r&&typeof r=="object"&&(this._common=a.ext({},this._common,r))},resetPageview:function(){this.pageview=a.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var r=this._conf,n=r&&r.setUsername;if(typeof n=="function")try{var c=n();typeof c=="string"&&(c=c.substr(0,40),this.username=c)}catch(o){a.warn("[arms] setUsername fail",o)}return this.username},getTraceId:function(){var r=this.rip,n=Date.now(),c=a.getSortNum(this.record),o=r+n+c+a.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=o,this.record=c,{"EagleEye-TraceID":o}},getUberTraceId:function(r){var n=this.rip,c=Date.now(),o=a.getSortNum(this.record),l=a.getRandNum(this._conf.pid),d=n+c+o+a.getNum(2)+l,u=d.substring(0,16);return r=r?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{"uber-trace-id":d+":"+u+":0:"+r,traceId:d}},getB3TraceId:function(r){var n=this.rip,c=Date.now(),o=a.getSortNum(this.record),l=a.getRandNum(this._conf.pid),d=n+c+o+a.getNum(2)+l,u=d.substring(0,16);return r=r?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{b3:d+"-"+u+"-"+r+"-0","X-B3-TraceId":d,"X-B3-ParentSpanId":"0","X-B3-SpanId":u,"X-B3-Sampled":r}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(r){return r?this._conf[r]:a.ext({},this._conf)},sampling:function(r){return r===1||(typeof this.sampleCache[r]=="boolean"||(this.sampleCache[r]=a.pick(r)),this.sampleCache[r])},clear:function(r){var n;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var c=this._conf&&typeof this._conf.sendRequest=="function";n=this.requestQueue.pop();)if(n.t==="res")this.postData(n,"res");else if(n.t==="error")this.postData(n,"err");else if(n.t==="api")this.postData(n,"apiSnapshot");else if(n.t==="behavior")this.postData(n,"behavior");else if(n.t==="health"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(n);else if(n.t==="resource"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var o=JSON.stringify({resource:n.resource});delete n.resource,this.sendBeacon(n,null,o)}else n.t==="resource"?this.postData(n,"resource"):this.sendRequest(n);return r&&this.clearSelf(),this},clearSelf:function(){var r;for(clearTimeout(this.Timmer),this.Timmer=null;r=this.selfQueue.pop();)this.postData(r,"err");return this},_lg:function(r,n,c,o){var l=this,d=l._conf,u=l.getPage(),p=d.ignore||{},h=p.ignoreErrors,f=p.ignoreResErrors,g=p.ignoreUrls,S=p.ignoreApis;if(l._isRobot||a.ignoreByRule(u,g)||a.ignoreByRule(a.decode(u),g)||r==="error"&&(a.ignoreByRule(n.msg,h)||a.ignoreByRule(a.decode(n.msg),h))||r==="resourceError"&&(a.ignoreByRule(n.src,f)||a.ignoreByRule(a.decode(n.src),f))||r==="api"&&(a.ignoreByRule(n.api,S)||a.ignoreByRule(a.decode(n.api),S))||!l.checkImgUrl(d.imgUrl)||!n||d.disabled||!d.pid||o===0)return l;var b=n.dl;if(delete n.dl,n=a.ext({t:r,times:1,page:u,tag:d.tag||"",release:d.release||"",environment:d.environment,begin:Date.now(),c1:d.c1,c2:d.c2,c3:d.c3},n,l.commonInfo(),l._common,{pid:d.pid,_v:l.ver,pv_id:l.pageview,username:l.getUsername(),sampling:c||1,dl:b,z:a.seq()}),a.T(d.beforeReport)==="Function")try{if(!(n=d.beforeReport(n)))return l}catch(v){return l}return o===1?t(l,n):c&&!l.sampling(c)?l:t(l,n)},_self:function(r,n,c){var o=this,l=o._conf;if(r!=="error"||!o.checkImgUrl(l.imgUrl)||!n||l.disabled||!l.pid||c&&!o.sampling(c))return o;n=a.ext({t:r,times:1,page:a.selfErrPage,tag:l.pid,begin:Date.now()},n,{pid:e,_v:o.ver,sampling:c||1,z:a.seq()});var d=o.selfQueue[0];if(d){d.times++;try{d.err&&n.err&&d.err.msg_raw&&n.err.msg_raw&&d.err.msg_raw.split("&").indexOf(n.err.msg_raw)<0&&d.err.msg_raw.length<1e3&&(d.err.msg_raw+="&"+n.err.msg_raw)}catch(u){}}else o.selfQueue.unshift(n),o.onReady(function(){o.sdkFlag&&(o.sdkFlag=!1,o.Timmer=a.delay(function(){o.clearSelf()},1e4))})},custom:function(r,n){if(!r||typeof r!="object")return this;var c=!1,o={begin:Date.now()};return a.each(r,function(l,d){return!(c=d&&d.length<=20)&&a.warn("[retcode] invalid key: "+d),o["x-"+d]=l,c}),c?this._lg("custom",o,n||1):this}},br.exports=i,br.exports}var Na,vr={exports:{}},La,yr,xa,Rr={exports:{}};function Zo(){if(xa)return yr;xa=1;var a=et();return yr=function(s,e){var t=[],i=null,r=e&&e.location&&e.location.href,n=void 0,c=null,o=function(u,p,h){if(u!==null){var f=u[p];u[p]=h(f)}},l=function(u){var p,h,f,g,S,b=[];if(!u||typeof u.tagName!="string")return"";if(b.push(u.tagName.toLowerCase()),typeof u.id=="string"&&b.push("#".concat(u.id)),typeof(p=u.className)=="string")for(h=p.split(/\s+/),S=0;S<h.length;S++)b.push(".".concat(h[S]));var v=["type","name","title","alt","data-arms-attr"];for(S=0;S<v.length;S++)f=v[S],typeof(g=u.getAttribute(f))=="string"&&b.push("[".concat(f,'="').concat(g,'"]'));return b.join("")},d=function(u,p){return function(h){if(h&&h!==c){var f;c=h;try{f=h.target}catch(S){f="<unknown>"}if(f.length!==0){var g={type:"ui.".concat(u),data:{message:function(S){if(!S||S.nodeType!==1)return"";for(var b=S||null,v=[],R=0,_=0,y="";b&&R++<5&&!((y=l(b))==="html"||R>1&&_+3*v.length+y.length>=80);)v.push(y),_+=y.length,b=b.parentNode;return v.reverse().join(" > ")}(f)},timestamp:Date.now()};u==="click"?i&&i.addBehavior(g):u==="keypress"&&(n||i&&i.addBehavior(g),clearTimeout(n),n=setTimeout(function(){n=void 0},100))}}}};a.ext(s.prototype,{addBehavior:function(u){if(this.getConfig("behavior")&&u&&typeof u=="object"){var p={},h=u.data||{};if(u.type)p=h;else{if(typeof h.name!="string"||typeof h.message!="string")return;p.name=h.name.substr(0,20),p.message=h.message.substr(0,200)}p.message&&(p.message=a.encode(p.message));var f={type:u.type||"custom",data:p||{},timestamp:u.timestamp||Date.now(),page:u.page||e&&e.location&&e.location.pathname};return t.push(f),t=t.slice(-100)}},getBehavior:function(){return t||[]},setBehavior:function(u){return u&&(t=u),t},reportBehavior:function(u){var p=this;p.getConfig("behavior")&&(p.sendBhTimer&&(clearTimeout(p.sendBhTimer),p.sendBhTimer=void 0),p.sendBhTimer=setTimeout(function(){t&&t.length>0&&(p.behavior(t),t=[],p.sendBhTimer=void 0,u&&typeof u=="function"&&u())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!i){try{(function(){if(document&&document.referrer&&document.location){var p=document.referrer,h=document.location.href;if(p!==""){var f={type:"navigation",data:{from:p,to:h}};r=h,i&&i.addBehavior(f)}}})(),e&&e.document&&e.document.addEventListener&&(e.document.addEventListener("click",d("click"),!1),e.document.addEventListener("keypress",d("keypress"),!1)),function(){if(function(){var g=e&&e.chrome,S=g&&g.app&&g.app.runtime,b="history"in e&&!!e.history.pushState&&!!e.history.replaceState;return!S&&b}()){var p=function(g,S){var b={type:"navigation",data:{from:g,to:S}};i&&i.addBehavior(b),r=S},h=e.onpopstate;e.onpopstate=function(){for(var g=arguments.length,S=new Array(g),b=0;b<g;b++)S[b]=arguments[b];var v=e.location.href;if(p(r,v),h)return h.apply(this,S)};var f=function(g){return function(){for(var S=arguments.length,b=new Array(S),v=0;v<S;v++)b[v]=arguments[v];var R=b.length>2?b[2]:void 0;return R&&p(r,String(R)),g.apply(this,b)}};o(e.history,"pushState",f),o(e.history,"replaceState",f)}}();var u=this.getConfig("enableConsole");u&&function(p){if(e&&e.console){var h=["debug","info","warn","log","error","assert"];a.isArray(p)&&(h=p);for(var f=0;f<h.length;f++){var g=h[f];g&&a.isString(g)&&e.console[g]&&typeof e.console[g]=="function"&&o(e.console,g,function(S){var b=g;return function(){for(var v=arguments.length,R=new Array(v),_=0;_<v;_++)R[_]=arguments[_];var y={type:"console",data:{level:b,message:R}};if(i&&i.addBehavior(y),b==="error")for(var A=0;A<R.length;A++){var w=R[A];w&&w.message&&w.stack&&i&&i.errorHandler(new ErrorEvent("error",{error:w,message:w.message}))}S&&Function.prototype.apply.call(S,e.console,R)}})}}}(u)}catch(p){a.warn("[arms] error in initBehavior",p)}i=this,this.hasInitBehavior=!0}return this}})},yr}var Oa,Ar,Va,wr,Ua,Ba,Ha,_r,Fa,ja,$a,Wa,za,Er,Ka,Ja,qa,Ga={};function Tr(){return Oa||(Oa=1,Ga.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),Ga}function ec(){return Ha||(Ha=1,Ba=function(a,s,e){var t=et(),i=function(){if(Va)return Ar;Va=1;var g=et(),S=Tr().TIMING_KEYS;return Ar=function(){var b=g.win||{},v=b.performance;if(!v||typeof v!="object"||typeof v.getEntriesByType!="function")return null;var R={},_=v.timing||{},y=v.getEntriesByType("resource")||[];if(R.begin=_[S[1]]||Date.now(),typeof b.PerformanceNavigationTiming=="function"){var A=v.getEntriesByType("navigation")[0];A&&(_=A)}return g.each({dom:[10,8],load:[14,1]},function(w,T){var I=_[S[w[1]]],P=_[S[w[0]]];if(I>0&&P>0){var D=Math.round(P-I);D>=0&&D<6e5&&(R[T]=D)}}),R.res=JSON.stringify(y),R},Ar}(),r=function(){if(Ua)return wr;Ua=1;var g=et(),S=Tr().TIMING_KEYS;return wr=function(){var b=g.win||{},v=b.performance;if(!v||typeof v!="object")return null;var R={},_=v.timing||{},y=Date.now(),A=1;if(typeof b.PerformanceNavigationTiming=="function"){var w=v.getEntriesByType("navigation")[0];w&&(_=w,A=2)}g.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(U,q){var Y=_[S[U[1]]],G=_[S[U[0]]];if(A===2||Y>0&&G>0){var $=Math.round(G-Y);$>=0&&$<6e5&&(R[q]=$)}});var T=b.navigator.connection,I=v.navigation||{};R.ct=T?T.effectiveType||T.type:"";var P=T&&(T.downlink||T.downlinkMax||T.bandwidth)||null;if((P=P>999?999:P)&&(R.bandwidth=P),R.navtype=I.type===1?"Reload":"Other",A===1&&_[S[16]]>0&&_[S[1]]>0){var D=_[S[16]]-_[S[1]];D>=0&&D<36e5&&(R.fpt=D)}return A===1&&_[S[1]]>0?R.begin=_[S[1]]:A===2&&R.load>0?R.begin=y-R.load:R.begin=y,R},wr}(),n=null,c=e.documentElement,o=s.innerWidth||c.clientWidth||e.body.clientWidth,l=s.innerHeight||c.clientHeight||e.body.clientHeight,d=s.navigator.connection,u={sr:screen.width+"x"+screen.height,vp:o+"x"+l,ct:d?d.effectiveType||d.type:""},p={},h=function(g,S,b,v,R){if(S===void 0){var _,y;if(!p[g]){_=new RegExp(g+"=([^;]+)");try{y=_.exec(e.cookie)}catch(w){return t.warn("[retcode] can not get cookie:",w),null}y&&(p[g]=y[1])}return p[g]}var A=g+"="+S;A+="; path=/",b&&(A+="; max-age="+b);try{return e.cookie=A,!!e.cookie}catch(w){return t.warn("[retcode] can not set cookie: ",w),!1}},f=function(g){var S=g._conf.uid||h("_nk_")||h("_bl_uid");return S||(S=t.uu(),h("_bl_uid",S,15552e3))?S:null};return t.ext(a.prototype,{activeErrHandler:function(g){return n&&!g||(n=this),this},errorHandler:function(g){if(!g)return this;var S=g.type;if(S==="error"){var b=g.target||g.srcElement;!b||!b.tagName||g.message||g.filename||g.lineno||g.colno?this.error(g.error||{message:g.message},g):this.resourceErrorHandler(g)}else S==="unhandledrejection"&&t.T(g.reason,"Error")&&t.checkAutoError(g.reason)&&this.error(g.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(v){}return this},resourceErrorHandler:function(g){var S=this,b=g.target||g.srcElement;try{var v=S.getSrc(b),R=typeof b.tagName=="string"?b.tagName.toLowerCase():"",_=S.getXPath(b,5),y=t.getURL(v),A={src:v&&v.substring(0,1e3),node_name:R,xpath:_,res_type:t.getResType(R,v),res_name:y.path,domain:y.domain};return S._conf.enableResource&&S.fixResourceStatus&&g.timeStamp&&S.fixResourceStatus({src:v,node_name:R,res_type:t.getResType(R,v),timeStamp:g.timeStamp,domain:y.domain}),S._lg("resourceError",A),S}catch(w){return t.warn("[ARMS] resourceErrorHandler error :",w),S}},getSrc:function(g){var S=g.src||g.href;try{if(!S){var b=(typeof g.tagName=="string"?g.tagName.toLowerCase():"")==="object",v=g.getAttribute("classid")&&g.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||g.getAttribute("type")==="application/x-shockwave-flash";b&&v&&(S=g.getAttribute("data")||g.getAttribute("codebase")),S||(S=g.outerHTML||g.innerHTML)}}catch(R){S=""}return S},getXPath:function(g,S){var b=g.id?"#"+g.id:"",v=typeof g.className=="string"?"."+g.className.split(" ").join("."):"",R=(typeof g.tagName=="string"?g.tagName.toLowerCase():"")+b+v;return g.parentNode&&g.parentNode.tagName&&S-1!=0?this.getXPath(g.parentNode,S-1)+" > "+R:R},sendPerformance:function(g){var S=this;S.onReady(function(){var b=r();b&&b.load&&b.load>0&&(b.page=S.getPage(!0),g&&(b=t.ext(b,g)),b.autoSend=!0,S.performance(b))})},sendResources:function(g){var S=this;S.onReady(function(){var b=i();b&&b.load&&b.load>0&&(b.load&&b.load<=2e3||b.load&&b.load<=8e3&&Math.random()>.05||(b.page=S.getPage(!0),b.dl=location.href,g&&(b=t.ext(b,g)),S._lg("res",b,S.getConfig("sample"))))})},sendPV:function(){var g=this;g.onReady(function(){var S,b,v=(S=f(g),b=s.devicePixelRatio||1,{uid:S,dt:e.title,dl:location.href,dr:e.referrer,dpr:b.toFixed(2),de:(e.characterSet||e.defaultCharset||"").toLowerCase(),ul:c.lang,begin:Date.now()});v&&v.uid&&g._lg("pv",v,g.getConfig("pvSample"))})},commonInfo:function(){return u.uid=f(this),u.sid=function(g){if(g.session)return g.session;var S;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(S=sessionStorage.getItem("_bl_sid"))=="string"?(g.session=S,S):(S=t.uu(),g.session=S,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",S),S)}catch(b){t.warn("[ARMS] getSid error :",b)}return g.session=S=t.uu(),S}(this),u},handleUnload:function(g){var S=Date.now();if(S-this._lastUnload<200)return this;this._lastUnload=S,this.sendHealth(g),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(g){var S=this;if(!g^S.hashChangeHandler)return S;g?(S.hackHistoryState(),S.hashChangeHandler=function(b){var v=S._conf.parseHash(location.hash);v&&S.setPage(v,b!==!1)},S.stateChangeHandler=function(b){var v=S._conf.parseHash(b.detail);v&&S.setPage(v)},t.on(s,"hashchange",S.hashChangeHandler),t.on(s,"historystatechange",S.stateChangeHandler),S.hashChangeHandler(!1)):(t.off(s,"hashchange",S.hashChangeHandler),t.off(s,"historystatechange",S.stateChangeHandler),S.hashChangeHandler=null,S.stateChangeHandler=null)},initHandler:function(){var g=this;if(g.hasInitHandler)return g;var S=g._conf;return t.on(s,"beforeunload",function(){g.handleUnload(0)}),g.bindHashChange(S.enableSPA),g.activeErrHandler(!1),g.hasInitHandler=!0,g}}),t.on(s,"error",function(g){n&&n.errorHandler(g)},!1,!0).on(s,"unhandledrejection",function(g){n&&n.errorHandler(g)}),a}),Ba}function tc(){if(Fa)return _r;Fa=1;var a=et();return _r=function(s,e,t){function i(d,u,p){var h=0,f=d.tagName;if(f!=="SCRIPT"&&f!=="STYLE"&&f!=="META"&&f!=="HEAD"){var g=d.children?d.children.length:0;if(g>0)for(var S=d.children,b=g-1;b>=0;b--)h+=i(S[b],u+1,h>0);if(h<=0&&!p&&!(d.getBoundingClientRect&&d.getBoundingClientRect().top<n))return 0;h+=1+.5*u}return h}function r(d){for(var u=1;u<d.length;u++)if(d[u].score<d[u-1].score)return d.splice(u,1),r(d);return d}var n=e.innerHeight||0,c=[],o=null,l=0;a.ext(s.prototype,{initFmpObserver:function(d){var u=this;if(!u._conf||!u._conf.useFmp)return null;if(!e.MutationObserver)return a.warn("[retcode] first meaningful paint can not be retrieved"),u.sendPerformance(),null;a.on(e,"beforeunload",function(){u.endObserving(0,!0)});var p=e.MutationObserver;return(o=new p(function(){(function(h){var f=Date.now()-h,g=t.querySelector("body");if(g){var S=0;S+=i(g,1,!1),c.push({score:S,t:f})}else c.push({score:0,t:f})})(u._startTime)})).observe(document,{childList:!0,subtree:!0}),l=1,u.onReady(function(){u.endObserving(d)}),o},endObserving:function(d,u){var p,h,f,g=this;if(o&&l)if(g.fmpTimmer&&(clearTimeout(g.fmpTimmer),g.fmpTimmer=null),u||(p=g._startTime,h=d,(f=Date.now()-p)>h||f-(c&&c.length&&c[c.length-1].t||0)>1e3)){o.disconnect(),l=0,c=r(c);for(var S=null,b=1;b<c.length;b++)if(c[b].t>=c[b-1].t){var v=c[b].score-c[b-1].score;(!S||S.rate<=v)&&(S={t:c[b].t,rate:v})}S&&S.t>0&&S.t<36e5?g.sendPerformance({fmp:S.t}):g.sendPerformance()}else g.fmpTimmer=a.delay(function(){g.endObserving(d)},500)}})},_r}function ic(){if(Ja)return fr.exports;Ja=1;var a=et(),s=function(){if(Ma)return Sr.exports;Ma=1;var o=et(),l=Qo(),d=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],u=function(h){var f=(h.key||"default").split("::");return f.length>1?o.ext(h,{group:f[0],key:f[1]}):o.ext(h,{group:"default_group",key:f[0]})},p=function(h){var f;l.call(this,h);try{f=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch(g){f=Date.now()}return this._startTime=f,this};return p.prototype=o.createObject(l.prototype),o.ext(l.dftCon,{startTime:null}),o.ext(p.prototype,{constructor:p,_super:l,sum:function(h,f,g){try{var S=o.dealParam(h,f,1);return this._lg("sum",u(S),g)}catch(b){o.warn("[retcode] can not get parseStatData: "+b)}},avg:function(h,f,g){try{var S=o.dealParam(h,f,0);return this._lg("avg",u(S),g)}catch(b){o.warn("[retcode] can not get parseStatData: "+b)}},percent:function(h,f,g,S){try{return this._lg("percent",u({key:h,subkey:f,val:g||0,begin:Date.now()}),S)}catch(b){o.warn("[retcode] can not get parseStatData: "+b)}},msg:function(h,f){if(h&&!(h.length>180))return this.custom({msg:h},f)},error:function(h,f){if(!h)return o.warn("[retcode] invalid param e: "+h),this;arguments.length===1?(typeof h=="string"&&(h={message:h},f={}),typeof h=="object"&&(f=h=h.error||h)):(typeof h=="string"&&(h={message:h}),typeof f!="object"&&(f={}));var g=h.name||"CustomError",S=h.message||"",b=h.stack||"";f=f||{};var v=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if(o.checkSDKError(S,f.filename)){var R=/^Script error\.?$/,_=h.msg||h.message;if(o.ignoreByRule(_,R)||o.ignoreByRule(o.decode(_),R))return this;var y={msg:o.selfErrKey,err:{msg_raw:o.encode(h.msg||h.message)}};return this._self("error",y,1)}for(var A={begin:Date.now(),cate:g,msg:S&&S.substring(0,1e3),stack:b&&b.substring(0,1e3),file:o.removeUrlSearch(f.filename||""),line:f.lineno||"",col:f.colno||"",err:{msg_raw:o.encode(S),stack_raw:o.encode(b)},dl:v},w=["tag","c1","c2","c3"],T=0;T<w.length;T++){var I=w[T];f[I]&&(A[I]=f[I])}var P=(this.getConfig("ignore")||{}).ignoreErrors;return o.ignoreByRule(A.msg,P)||o.ignoreByRule(o.decode(A.msg),P)?this:(this.beforeSend&&this.beforeSend("error",A),this._lg("error",A,1))},behavior:function(h){if(h){var f=typeof h=="object"&&h.behavior?h:{behavior:h};return this.beforeSend&&this.beforeSend("behavior",f),this._lg("behavior",f,1)}},api:function(h,f,g,S,b,v,R,_,y,A,w,T,I,P,D,U){if(!h)return o.warn("[retcode] api is null"),this;if(h=typeof h=="string"?{api:h,success:f,time:g,code:S,msg:b,begin:v,traceId:R,pv_id:_,apiSnapshot:y,domain:A,flag:T,tag:I,c1:P,c2:D,c3:U}:o.sub(h,d),!o.checkAPI(h.api,!0))return this;h.code=h.code||"";var q=h.msg||"";if(q=typeof q=="string"?q.substring(0,1e3):q,h.msg=q,h.success=h.success?1:0,h.time=+h.time,h.begin=h.begin,h.traceId=h.traceId||"",h.pv_id=h.pv_id||"",h.domain=h.domain||"",h.flag=h.flag,h.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",h.apiSnapshot&&(typeof h.apiSnapshot=="object"&&(h.apiSnapshot=JSON.stringify(h.apiSnapshot)),typeof h.apiSnapshot!="string"&&delete h.apiSnapshot,h.apiSnapshot.length>2e3&&(h.apiSnapshot=h.apiSnapshot.substring(0,2e3))),w&&(h.traceOrigin=w),!h.api||isNaN(h.time))return o.warn("[retcode] invalid time or api"),this;var Y=(this.getConfig("ignore")||{}).ignoreApis;return o.ignoreByRule(h.api,Y)||o.ignoreByRule(o.decode(h.api),Y)||h.time<0?this:(this.beforeSend&&this.beforeSend("api",h),this._lg("api",h,h.success&&this.getConfig("sample"),h.flag))},speed:function(h,f,g){var S=this,b=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(h)?(f=typeof f!="number"?Date.now()-b:f>=b?f-b:f,S.speedCache=S.speedCache||{},S.speedCache[h]=f,S.speedCache.begin=b,clearTimeout(S.speedTimmer),S.speedTimmer=setTimeout(function(){g||(S.speedCache.page=S.getPage(!0)),S._lg("speed",S.speedCache),S.speedCache=null},5e3),S):(o.warn("[retcode] invalid point: "+h),S)},performance:function(h){if(h&&typeof h=="object"&&!this.hasSendPerf){var f={},g={},S=this.getConfig("autoSendPerf");if(h.autoSend&&S)return g=o.ext(this.perfData||{},h),this.hasSendPerf=!0,this._lg("perf",g,this.getConfig("sample"));if(h.autoSend&&!S)return delete h.autoSend,this.perfData?(g=o.ext(this.perfData||{},h),this.hasSendPerf=!0,this._lg("perf",g,this.getConfig("sample"))):void(this.perfData=h);for(var b in h)(/^t([1-9]|1[0])$/.test(b)||b==="ctti"||b==="cfpt")&&(f[b]=h[b]);if(h.autoSend===!0||!S&&(S||this.perfData))return h.autoSend!==!0&&S===!1&&this.perfData?(f=o.ext(this.perfData||{},f),this.hasSendPerf=!0,this._lg("perf",f,this.getConfig("sample"))):void 0;this.perfData=o.ext(this.perfData||{},f)}},resource:function(h,f){if(!h||!o.isPlainObject(h))return o.warn("[arms] invalid param data: "+h),this;var g=Object.keys(h),S=["begin","dom","load","res","dl"],b=!1;for(var v in S)if(g.indexOf(S[v])<0){b=!0;break}if(b)return o.warn("[arms] lack param data: "+h),this;var R={begin:h.begin||Date.now(),dom:h.dom||"",load:h.load||"",res:o.isArray(h.res)?JSON.stringify(h.res):JSON.stringify([]),dl:h.dl||""};return this._lg("res",R,f)},event:function(h,f){if(typeof h=="object"&&h&&h.key){var g={},S=["key","success","time","c1","c2","c3"];for(var b in h)S.indexOf(b)>-1&&(g[b]=h[b]);g.success=h.success===!1?0:1,this._lg("event",g,f)}}}),p._super=l,p._root=l,l.Reporter=p,Sr.exports=p,Sr.exports}(),e=function(){if(Na)return vr.exports;Na=1;var o=et(),l=typeof window=="object"?window:{},d=l.__oFetch_||l.fetch;return d=typeof d=="function"?d:void 0,vr.exports=function(u,p){var h=-1;typeof u=="object"&&(h=u.z,u=o.serialize(u));var f=p+u;if(d)return d(f,{method:"HEAD",mode:"no-cors"}).catch(o.noop);if(l.document&&l.document.createElement){var g="__request_hold_"+h,S=l[g]=new Image;S.onload=S.onerror=function(){l[g]=void 0},S.src=f,S=null}},vr.exports}(),t=function(){if(La)return Rr.exports;La=1;var o=et(),l=typeof window=="object"?window:{},d=l.__oXMLHttpRequest_||l.XMLHttpRequest;return d=typeof d=="function"?d:void 0,Rr.exports=function(u,p){try{var h=new d;h.open("POST",p,!0),h.setRequestHeader("Content-Type","text/plain"),h.send(JSON.stringify(u))}catch(f){o.warn(`[retcode] Failed to log, exception is :
129
- `+f)}},Rr.exports}(),i=a.win,r=i.document,n=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,c=function(o){var l=this;return s.call(l,o),l._initialPage=o.page&&a.safetyCall(o.page,[],o.page+"")||null,l._isRobot=a.isRobot(),l._health={errcount:0,apisucc:0,apifail:0},l.beforeSend=function(d,u){d==="error"?l._health.errcount++:d==="api"&&l._health[u.success?"apisucc":"apifail"]++},o.enableInstanceAutoSend!==!1&&(l.initHandler(),l.initHook(),l.initFmpObserver(1e4),l._conf&&l._conf.behavior&&typeof l.initBehavior=="function"&&l.initBehavior(),l._conf&&l._conf.enableResource&&typeof l.initResource=="function"&&l.initResource()),Object.defineProperty&&i.addEventListener&&Object.defineProperty(l,"pipe",{set:l.sendPipe}),l};return c.prototype=a.createObject(s.prototype),a.ext(s._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(o){return(o?a.cutUrlSearch(o.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(o){if(!o||typeof o!="object")return{};var l=o.code,d=o.msg||o.message||o.subMsg||o.errorMsg||o.ret||o.errorResponse||"";return typeof d=="object"&&(l=l||d.code,d=d.msg||d.message||d.info||d.ret||JSON.stringify(d)),{msg:d,code:l,success:!0}}}),a.ext(c.prototype,{constructor:c,_super:s,onReady:function(o){var l=this;if(l.hasReady)return o();r.readyState==="complete"?(l.hasReady=!0,o()):a.on(i,"load",function(){l.hasReady=!0,o()},!0)},getPage:function(o){var l=this._conf,d=l.page,u=location,p=u.host+u.pathname;return d&&!o?a.safetyCall(d,[],d+""):this._initialPage||a.filterByRule(l.ignoreUrlCase?p.toLowerCase():p,u.href,l.ignoreUrlPath?l.ignoreUrlPath:l.urlHelper)},setPage:function(o,l){var d=this,u=d.prevPage;if(l!==!1){if(!o||o===u)return d;d.prevPage=o,clearTimeout(d.sendPVTimmer),d.handleUnload(1),d.resetPageview(),d.sendPVTimmer=setTimeout(function(){d.sendPV()},10)}else d.prevPage=o;return d._conf.page=o,d},setConfig:function(o,l){if(o&&typeof o=="object"){a.verifyConfig(o),o=this.setImgUrl(o);var d=this._conf;if(this._conf=a.ext({},d,o),!l){var u="disableHook";u in o&&d[u]!==o[u]&&(o[u]?this.removeHook():this.addHook()),(u="enableSPA")in o&&d[u]!==o[u]&&this.bindHashChange(o[u])}}},sendRequest:function(o){e(o,this.getConfig("imgUrl"))},postData:function(o,l){var d={};d[l]=o[l],delete o[l];var u="";typeof o=="object"&&(u=a.serialize(o)),t(d,this.getConfig("imgUrl")+u+"&post_res=")},sendPipe:function(o){var l=this;if(!o||!o.length)return l;try{if(a.T(o[0])==="Array")return a.each(o,function(u){return l.sendPipe(u)});if(a.T(o)!=="Array")return l;var d=o.shift();if(!n.test(d))return l;l[d].apply(l,o)}catch(u){return a.warn("[retcode] error in sendPipe",u),l}},sendHealth:function(){var o=a.ext({},this._health);o.healthy=o.errcount>0?0:1,o.begin=Date.now();var l=o.begin-this.sBegin;o.stay=l,this._lg("health",o,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(o){o=a.ext({pid:this._conf.pid},o);var l=this.__proto__.constructor(o);return o.page&&l.sendPV(),l}}),Zo()(c,i),ec()(c,i,r),tc()(c,i,r),($a||($a=1,ja=function(o,l){var d=et(),u=null,p=d.getCurDomain(),h=function(v,R,_,y,A,w,T,I,P,D,U,q,Y){var G=d.J(A)||null,$=d.safetyCall(R,[G,y],null);if(!$)return!1;var Z=$.code||w,te=!("success"in $)||$.success;v.api(_,te,T,Z,$.msg,I,P,D,te?{}:U,p,q,Y)},f="fetch",g="__oFetch_",S="__oXMLHttpRequest_",b="XMLHttpRequest";return d.ext(o.prototype,{removeHook:function(v,R){return u&&(R||this===u)?(l[g]&&(l[f]=l[g],delete l[g]),l[S]&&(l[b]=l[S],delete l[S]),u=null,this):this},addHook:function(v){return!v&&u||(u||(function(){if(typeof l[f]=="function"){var R=l[f];l[g]=R,l[f]=function(_,y){var A=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),w=u;if(!w||!w.api||y&&(y.method==="HEAD"||y.mode==="no-cors"))return R.apply(l,A);y||(y={});var T=Date.now(),I=w._conf,P=d.duration(),D=(_&&typeof _!="string"?_.url:_)||"",U=D;D=d.cutUrlSearch(D);var q=(I.ignore||{}).ignoreApis,Y=I.parseTraceId;if(!d.checkAPI(D,!0)||d.ignoreByRule(D,q))return R.apply(l,A);D=d.filterByRule(D,U,I.ignoreApiPath?I.ignoreApiPath:I.apiHelper);var G=I.enableLinkTrace,$="",Z="",te=w.getConfig("pid"),fe=null,N=w.getConfig("sample"),x=w.getConfig("linkType"),L=1;if(N&&!w.sampling(N)&&(L=0),G){var O="";try{O=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(he){O=""}var ue=d.checkSameOrigin(U,O);if(w.getConfig("enableApiCors")||ue)if(_&&typeof _!="string")try{if(A[0].headers&&typeof A[0].headers.get=="function"&&typeof A[0].headers.append=="function")switch(x){case"arms":var Me=A[0].headers.get("EagleEye-TraceID"),K=A[0].headers.get("EagleEye-SessionID"),Se=A[0].headers.get("EagleEye-pAppName");Me?$=Me:($=w.getTraceId()["EagleEye-TraceID"],A[0].headers.append("EagleEye-TraceID",$)),K?Z=K:(Z=w.getPageviewId()["EagleEye-SessionID"],A[0].headers.append("EagleEye-SessionID",Z)),Se||A[0].headers.append("EagleEye-pAppName",te);break;case"b3":var Le=A[0].headers.get("X-B3-TraceId");if(Le)$=Le;else{var _e=w.getB3TraceId(L);A[0].headers.append("X-B3-TraceId",_e["X-B3-TraceId"]),A[0].headers.append("X-B3-ParentSpanId",_e["X-B3-ParentSpanId"]),A[0].headers.append("X-B3-SpanId",_e["X-B3-SpanId"]),A[0].headers.append("X-B3-Sampled",_e["X-B3-Sampled"]),A[0].headers.append("X-Request-ID",d.guid()),$=_e["X-B3-TraceId"]}Z=w.pageview;break;default:var Pe=A[0].headers.get("uber-trace-id");Pe?$=Pe.split(":")[0]:(Pe=w.getUberTraceId(L),A[0].headers.append("uber-trace-id",Pe["uber-trace-id"]),$=Pe.traceId),Z=w.pageview}}catch(he){d.warn(`[retcode] fetch failed to set header, exception is :
130
- `+he)}else switch(y.headers=y.headers?y.headers:{},x){case"arms":y.headers["EagleEye-TraceID"]?$=y.headers["EagleEye-TraceID"]:($=w.getTraceId()["EagleEye-TraceID"],y.headers["EagleEye-TraceID"]=$),y.headers["EagleEye-SessionID"]?Z=y.headers["EagleEye-SessionID"]:(Z=w.getPageviewId()["EagleEye-SessionID"],y.headers["EagleEye-SessionID"]=Z),y.headers["EagleEye-pAppName"]||(y.headers["EagleEye-pAppName"]=te);break;case"b3":if(y.headers["X-B3-TraceId"])$=y.headers["X-B3-TraceId"];else{var be=w.getB3TraceId(L);y.headers["X-B3-TraceId"]=be["X-B3-TraceId"],y.headers["X-B3-ParentSpanId"]=be["X-B3-ParentSpanId"],y.headers["X-B3-SpanId"]=be["X-B3-SpanId"],y.headers["X-B3-Sampled"]=be["X-B3-Sampled"],y.headers["X-Request-ID"]=d.guid(),$=be["X-B3-TraceId"]}Z=w.getPageviewId()["EagleEye-SessionID"];break;default:if(y.headers["uber-trace-id"])$=y.headers["uber-trace-id"].split(":")[0];else{var Ee=w.getUberTraceId(L);y.headers["uber-trace-id"]=Ee["uber-trace-id"],$=Ee.traceId}Z=w.getPageviewId()["EagleEye-SessionID"]}}return R.apply(l,A).then(function(he){if(!w||!w.api)return he;try{if(!he||typeof he.clone!="function")return he;var Ne=he.clone(),Re=Ne.headers;if(Re&&typeof Re.get=="function"){var Ge=Re.get("content-type");if(Ge&&!/(text)|(json)/.test(Ge))return he;if(!$){var ot=d.parseFetchHeaders(Re);typeof ot=="object"&&ot["eagleeye-traceid"]&&($=ot["eagleeye-traceid"],fe="response")}}var ce=P();return Ne.text().then(function(ae){if(!$&&d.isFunction(Y)){var ie=Y(Ne,ae);ie&&d.isString(ie)&&($=ie)}var ve=d.getFetchSnapshot(A,ae,Re);Ne.ok?h(w,I.parseResponse,D,U,ae,Ne.status||200,ce,T,$,Z,ve,fe,L):(w.api(D,!1,ce,Ne.status||404,Ne.statusText,T,$,Z,ve,p,fe,L),I.enableResource&&u.fixResourceStatus&&u.fixResourceStatus({src:Ne.url,res_type:"api"}))}),he}catch(ae){return d.warn("[ARMS] fetch response error :",ae),he}}).catch(function(he){if(!w||!w.api)throw he;var Ne=P();throw w.api(D,!1,Ne,he.name||"Error",he.message,T,$,Z,{},p),I.enableResource&&u.fixResourceStatus&&u.fixResourceStatus({src:U,res_type:"api"}),he})},l[f].toString=d.createFakeToString(f)}}(),function(){if(typeof l[b]=="function"){var R,_=l[b];l[S]=_;var y=function(A){var w=new _(A),T=u;if(!T||!T.api||!w.addEventListener)return w;var I,P,D,U,q=w.send,Y=w.open,G=w.setRequestHeader,$=T._conf,Z=($.ignore||{}).ignoreApis,te=$.parseTraceId,fe=T.getConfig("enableLinkTrace"),N="",x="",L="",O=null,ue=T.getConfig("sample"),Me=T.getConfig("linkType"),K=1;return ue&&!T.sampling(ue)&&(K=0),w.open=function(Se,Le){R=Se;var _e=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);Y.apply(w,_e),U=Le||"",D=d.cutUrlSearch(U);var Pe=!d.checkAPI(D,!0)||d.ignoreByRule(D,Z);if(D=D?d.filterByRule(D,U,$.ignoreApiPath?$.ignoreApiPath:$.apiHelper):"",!Pe&&fe){var be="";try{be=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(Re){be=""}var Ee=d.checkSameOrigin(U,be);if((T.getConfig("enableApiCors")||Ee)&&G&&typeof G=="function")switch(Me){case"arms":N=T.getTraceId()["EagleEye-TraceID"],G.apply(w,["EagleEye-TraceID",N]),x=T.getPageviewId()["EagleEye-SessionID"],G.apply(w,["EagleEye-SessionID",x]),L=T.getConfig("pid"),G.apply(w,["EagleEye-pAppName",L]);break;case"b3":var he=T.getB3TraceId(K);G.apply(w,["X-B3-TraceId",he["X-B3-TraceId"]]),G.apply(w,["X-B3-ParentSpanId",he["X-B3-ParentSpanId"]]),G.apply(w,["X-B3-SpanId",he["X-B3-SpanId"]]),G.apply(w,["X-B3-Sampled",he["X-B3-Sampled"]]),G.apply(w,["X-Request-ID",d.guid()]),N=he["X-B3-TraceId"],x=T.getPageviewId()["EagleEye-SessionID"];break;default:var Ne=T.getUberTraceId(K);G.apply(w,["uber-trace-id",Ne["uber-trace-id"]]),N=Ne.traceId,x=T.getPageviewId()["EagleEye-SessionID"]}}},w.send=function(){I=Date.now(),P=d.duration();var Se=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);q.apply(w,Se)},d.on(w,"readystatechange",function(){if(D&&w.readyState===4){var Se=P(),Le=d.getXhrSnapshot(U,R,w);if(!N){var _e=d.parseXhrHeaders(typeof w.getAllResponseHeaders=="function"&&w.getAllResponseHeaders()||"");typeof _e=="object"&&_e["eagleeye-traceid"]&&(N=_e["eagleeye-traceid"],O="response")}if(!N&&d.isFunction(te)){var Pe=te(w);Pe&&d.isString(Pe)&&(N=Pe)}if(w.status>=200&&w.status<=299){var be=w.status||200;if(typeof w.getResponseHeader=="function"){var Ee=w.getResponseHeader("Content-Type");if(Ee&&!/(text)|(json)/.test(Ee))return}w.responseType&&w.responseType!=="text"?T.api(D,!0,Se,be,"",I,N,x,{},p,O,K):h(T,$.parseResponse,D,U,w.responseText,be,Se,I,N,x,Le,O,K)}else T.api(D,!1,Se,w.status||"FAILED",w.statusText,I,N,x,Le,p,O,K),$.enableResource&&u.fixResourceStatus&&u.fixResourceStatus({src:w.responseURL||U,res_type:"api"})}}),w};y.prototype=_.prototype,d.each(Object.keys(_),function(A){y[A]=_[A]}),l[b]=y,l[b].toString=d.createFakeToString(b)}}()),u=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}}),o}),ja)(c,i),(za||(za=1,Wa=function(o,l){var d=et(),u=l.history||{},p=l.document,h=function(g,S){var b;l.CustomEvent?b=new CustomEvent(g,{detail:S}):((b=p.createEvent("HTMLEvents")).initEvent(g,!1,!0),b.detail=S),l.dispatchEvent(b)},f=function(g){var S=u[g];typeof S=="function"&&(u[g]=function(b,v,R){var _=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),y=location.href,A=S.apply(u,_);if(!R||typeof R!="string"||R===y)return A;try{var w=y.split("#"),T=R.split("#"),I=d.cutUrlSearch(w[0]),P=d.cutUrlSearch(T[0]),D=w[1]&&w[1].replace(/^\/?(.*)/,"$1"),U=T[1]&&T[1].replace(/^\/?(.*)/,"$1");D!==U?h("historystatechange",U):I!==P&&h("historystatechange",P)}catch(q){d.warn("[retcode] error in "+g+": "+q)}return A},u[g].toString=d.createFakeToString(g))};d.ext(o.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(f("pushState"),f("replaceState"),this.hasHackedHistoryState=!0),this}})}),Wa)(c,i),function(){if(Ka)return Er;Ka=1;var o=et(),l=Tr().TIMING_KEYS;return Er=function(d,u){function p(g,S,b){if(g instanceof u.PerformanceResourceTiming&&g.initiatorType){var v=o.getResType(g.initiatorType,g.name),R=S.resourceTypes||[],_=(S.ignore||{}).ignoreResources;if(v&&R.includes(v)&&!o.ignoreByRule(g.name,_)&&!o.ignoreByRule(o.decode(g.name),_)){var y=g[l[0]],A=g[l[1]],w=g[l[2]],T=g[l[3]],I=g[l[4]],P=g[l[5]],D=g[l[6]],U=g[l[7]],q=g[l[8]],Y=g[l[18]],G=g[l[19]];if(!b.has(g)&&(!o.areInOrder(y,A,w,T,I,P,D,U,q)||y>U))return;if(Y<y&&(Y=y),G<y&&(G=A),o.areInOrder(y,Y,G,A))return{domain:o.getURL(g.name).domain,res_type:v,src_type:o.getSrcType(g.name,S.cdnHostList),success:1,size:Math.round(g.decodedBodySize),duration:Math.round(g.duration),timeStamp:g.responseEnd,timing:g}}}}var h="_resource-"+Date.now(),f="_resource_error-"+Date.now();o.ext(d.prototype,{initResource:function(){var g=this,S=u.performance,b=u.PerformanceObserver;if(g[f]||(g[f]=new WeakMap),!S||!b||typeof S!="object"||typeof S.getEntriesByType!="function")return null;var v=S.getEntriesByType("resource")||[];return setTimeout(function(){g.setResource(v)},10),new b(function(R){setTimeout(function(){g.setResource(R.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(g.resourceComboReport.bind(g),5e3)}),g},setResource:function(g){var S=this._conf,b=this[f];if(o.isArray(g)&&g.length){this[h]||(this[h]={});for(var v=this[h],R=0,_=g.length;R<_;R+=1){var y=g[R];if(o.checkAPI(y.name,!1)){var A=p(y,S,b);if(A){var w=A.res_type+"-"+A.domain;w in v||(v[w]=[]),v[w].push(A)}}}return this}},fixResourceStatus:function(g){var S=u.performance;if(!S||typeof S.getEntriesByName!="function")return null;var b=this[f];if(!g.src||!o.checkAPI(g.src,!1))return this;var v=g.timeStamp||S.now(),R=S.getEntriesByName(g.src,"resource");return o.each(R,function(_){b.has(_)||v-_.responseEnd<100&&b.set(_,{success:0})}),this},resourceComboReport:function(){var g=this[h]||{},S=this._conf.resourceSlow||2e3,b=this[f];this[h]={};var v=Object.keys(g);if(v.length!==0){var R=[];o.each(v,function(w){var T=g[w],I={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};o.each(T,function(P){var D=P.timing||{},U=b.get(P.timing),q=U?U.success:1,Y=P.duration>S?1:0;I.domain=P.domain,I.res_type=P.res_type,I.src_type=P.src_type,I.count+=1,I.duration+=P.duration,I.size+=P.size,q||(I.err_count+=1,I.err_duration+=P.duration),Y&&(I.slow_count+=1,I.slow_duration+=P.duration);try{var G=JSON.parse(JSON.stringify(D));G.success=q,G.resourceSlow=S,G.isSlow=Y,I.timings.push(G)}catch($){}}),I.count&&(I.size=Math.round(I.size/I.count),I.duration=Math.round(I.duration/I.count)),I.slow_count&&(I.slow_duration=Math.round(I.slow_duration/I.slow_count)),I.err_count&&(I.err_duration=Math.round(I.err_duration/I.err_count)),I.timings.length>20&&(I.timings.sort(function(P,D){return D.duration-P.duration}),I.timings.length=20),I.timings=encodeURIComponent(JSON.stringify(I.timings)),R.push(I)});var _={_combo:1,resource:JSON.stringify(R)},y=u.navigator.connection;_.ct=y?y.effectiveType||y.type:"";var A=y&&(y.downlink||y.downlinkMax||y.bandwidth)||null;(A=A>999?999:A)&&(_.bandwidth=A),this._lg("resource",_,this.getConfig("sample"))}}})},Er}()(c,i),c._super=s,c._root=s._root,s.Browser=c,fr.exports=c,fr.exports}var rc={getArmsLogger:function(){return function(){if(qa)return gr.exports;function a(r,n){var c=s[t]=new e(r);c.sendPipe(n);var o=c._conf;return o.autoSendPv!==!1&&c.sendPV(),o&&o.useFmp||c.sendPerformance(),o&&o.sendResource&&c.sendResources(),s[i]=!0,c}qa=1;var s=window,e=s.BrowserLogger=ic(),t=et().key,i="__hasInitBlSdk";return e.singleton=function(r,n){return s[i]?s[t]:a(r,n)},e.createExtraInstance=function(r){r&&typeof r=="object"&&r.enableInstanceAutoSend!==!0&&(r.enableInstanceAutoSend=!1);var n=new e(r),c=n._conf;return c.enableInstanceAutoSend&&(c.autoSendPv!==!1&&n.sendPV(),c&&c.useFmp||n.sendPerformance(),c&&c.sendResource&&n.sendResources()),n},typeof window=="object"&&window.navigator&&s[t]&&(e.bl=function(){if(s[i])return s[t];var r={},n=[];return t in s&&(r=s[t].config||{},n=s[t].pipe||[]),a(r,n)}()),gr.exports=e,gr.exports}()}};const Xa="https://arms-retcode.aliyuncs.com/r.png?",Ya="https://arms-retcode-sg.aliyuncs.com/r.png?",Qa="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",Za="e1iftji1w7@7ec1cef2cc88733",en="e1iftji1w7@10a06d1ec260adc",tn="e1iftji1w7@10a06d1ec260adc",Ir={cn:{reportUrl:Xa,pid:Za},"cn-hangzhou":{reportUrl:Xa,pid:Za},sg:{reportUrl:Ya,pid:en},"ap-southeast-1":{reportUrl:Ya,pid:en},usw:{reportUrl:Qa,pid:tn},"us-west-1":{reportUrl:Qa,pid:tn}},sc=a=>!!Object.isExtensible(a)&&(s=>Object.prototype.toString.call(s).slice(8,-1))(a)==="Object";function rn(a,s){if(typeof a!="string")return s;if(sn(a,s))return a;const e=a.indexOf(`
131
- `);return e<0?`${a}${s}`:`${a.slice(0,e)}${s}${a.slice(e)}`}function sn(a,s){if(typeof a!="string")return!1;const e=a.indexOf(s);if(e<0)return!1;const t=a.indexOf(`
132
- `);return t<0||e<t}function Lt(a,s,e){return typeof a=="function"?function(t,i,r){if(Reflect.get(t,"__v_skip")===!0)return t;const n={MediaboxWrapperFunctionApply(c,o,l){let d;try{d=Reflect.apply(c,o,l)}catch(u){throw r(u),u}return Lt(d,i,r)},MediaboxWrapperFunctionGet(c,o){const l=Object.getOwnPropertyDescriptor(c,o);return!l||l.writable||l.configurable?Lt(c[o],i,r):c[o]},MediaboxWrapperClassConstructor(c,o){let l;try{l=new c(...o)}catch(d){throw r(d),d}return Lt(l,i,r)}};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{apply:n.MediaboxWrapperFunctionApply,get:n.MediaboxWrapperFunctionGet,construct:n.MediaboxWrapperClassConstructor})}(a,s+1,e):a instanceof Promise?a.then(t=>Lt(t,s+1,e)).catch(t=>(e(t),Promise.reject(t))):Array.isArray(a)?(a.forEach((t,i)=>{a[i]=Lt(t,s+1,e)}),a):(t=>t!==null&&typeof t=="object")(a)&&sc(a)?function(t,i,r){var n;if(Reflect.get(t,"__v_skip")===!0)return t;const c=[],o=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors((n=Object.getPrototypeOf(t))!=null?n:{}):{};for(const d of Object.keys(o))o[d].get&&c.push(d);const l={MediaboxWrapperObjectGetter(d,u){if(typeof u=="string"&&c.indexOf(u)>-1){let h;try{h=d[u]}catch(f){throw r(f),f}return Lt(h,i,r)}if(i>10)return d[u];const p=Reflect.getOwnPropertyDescriptor(d,u);return!p||p.writable||p.configurable?Lt(d[u],i,r):d[u]},MediaboxWrapperObjectSetter:(d,u,p)=>(d[u]=Lt(p,i,r),!0)};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{get:l.MediaboxWrapperObjectGetter,set:l.MediaboxWrapperObjectSetter})}(a,s+1,e):a}function Cr(a){return typeof a=="string"&&(a.indexOf("g.alicdn.com/apsara-media-")>-1||a.indexOf("g.alicdn.com/thor-server")>-1||a.indexOf("MediaboxWrapper")>-1)}function an(a,s){if(Reflect.get(a,"__v_skip")===!0)return a;const e={MediaboxWrapperShallowGet(t,i){const r=t[i];return typeof r=="function"?e.MediaboxWrapperShallowMethod(r,t):r},MediaboxWrapperShallowMethod:(t,i)=>({MediaboxWrapperShallowApply(...r){let n;try{n=t.apply(i,r)}catch(c){throw s(c),c}return n instanceof Promise?n.catch(c=>(s(c),Promise.reject(c))):n}}).MediaboxWrapperShallowApply};return Object.defineProperty(a,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(a,{get:e.MediaboxWrapperShallowGet})}class nn extends Error{constructor(s){super(s),this.name="MQTError"}}let ac=1;class kr{constructor(s){var e,t;Xt(this,"armsLogger"),Xt(this,"isReady",!1),Xt(this,"isDestroyed",!1),Xt(this,"options"),Xt(this,"queue",[]),Xt(this,"marker"),Xt(this,"helper",{MediaboxWrapperQueue:i=>new nn(i),MediaboxWrapperInitiative:i=>new nn(i)}),this.options=((i,r)=>qo(i,Go(r)))(mr({},s),{region:s.deferRegionSet?void 0:(e=s.region)!=null?e:"cn",env:(t=s.env)!=null?t:"prod"}),this.marker=`-${ac++}-`,this.initArmsLogger()}static get version(){return"0.31.0"}initArmsLogger(s){const{region:e,env:t,disabled:i}=this.options;if(i||this.armsLogger)return;if(s&&!e)throw new Error("region is required");if(!e)return;if(!Ir[e])throw new Error(`region ${e} is not supported`);const r=rc.getArmsLogger();this.armsLogger=r.createExtraInstance({enableInstanceAutoSend:!0,pid:Ir[e].pid,tag:this.options.businessName,release:`${this.options.businessName}_${this.options.version}`,imgUrl:Ir[e].reportUrl,behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:n=>{var c;if(this.isDestroyed||sn(n.stack,this.marker)||n.t!=="pv"&&n.t!=="error"&&n.t!=="health")return!1;if(n.c1=(c=this.options.cid)!=null?c:window.location.host,n.c2=kr.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(function(o){return typeof o=="string"&&(o.indexOf("g.alicdn.com/apsara-media-")>-1||o.indexOf("g.alicdn.com/thor-server")>-1)}(n.file)||Cr(n.stack)){let o=n;return this.options.beforeSend&&(o=this.options.beforeSend(n)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return n}})}wrap(s){return this.options.disabled||typeof Proxy=="undefined"?s:Lt(s,0,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Cr(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=rn(e.stack,this.marker))})}shallowWrapClass(s){return this.options.disabled||typeof Proxy=="undefined"?s:function(e,t){if(Reflect.get(e,"__v_skip")===!0)return e;const i=n=>n instanceof e?an(n,t):n,r={MediaboxWrapperStaticGet(n,c){const o=n[c];return typeof o=="function"&&c!=="prototype"?r.MediaboxWrapperStaticMethod(o,n):o},MediaboxWrapperStaticMethod(n,c){const o={MediaboxWrapperStaticApply(l,d,u){let p;try{p=n.apply(c,u)}catch(h){throw t(h),h}return p instanceof Promise?p.then(h=>i(h)).catch(h=>(t(h),Promise.reject(h))):i(p)},MediaboxWrapperStaticConstruct(l,d,u){let p;try{p=Reflect.construct(n,d,u)}catch(h){throw t(h),h}return i(p)}};return new Proxy(n,{apply:o.MediaboxWrapperStaticApply,construct:o.MediaboxWrapperStaticConstruct})},MediaboxWrapperConstruct(n,c,o){let l;try{l=Reflect.construct(n,c,o)}catch(d){throw t(d),d}return an(l,t)}};return Object.defineProperty(e,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(e,{get:r.MediaboxWrapperStaticGet,construct:r.MediaboxWrapperConstruct})}(s,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Cr(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=rn(e.stack,this.marker))})}updateOptions(s){this.options=mr(mr({},this.options),s)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(s=>{var e;(e=this.armsLogger)==null||e.error(this.helper.MediaboxWrapperQueue(s.msg),{filename:s.file,lineno:s.line,colno:s.col})})}report(s,e){var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperInitiative(s),e)}destroy(){this.isDestroyed=!0}}function ni(){}const ti=class ti{static getInstance(){var s;return ti.instance||(ti.instance=new AudioContext),(s=ti.instance.resume())==null||s.then(ni,ni).catch(ni),ti.instance}};m(ti,"instance");let Yt=ti;const Vi=()=>{var s;const a=Yt.getInstance();a.state!=="running"&&a.state!=="closed"&&((s=a.resume())==null||s.then(ni,ni).catch(ni)),window.removeEventListener("mousedown",Vi),window.removeEventListener("touchstart",Vi)};window.addEventListener("mousedown",Vi),window.addEventListener("touchstart",Vi);class nc extends ne{constructor(){super();m(this,"audioContext");m(this,"stream");m(this,"sourceNode");m(this,"analyser");this.audioContext=Yt.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(r,n,c,o,l){let d,u=o,p=0;const h=r.createAnalyser();h.fftSize=256;const f=new Uint8Array(h.frequencyBinCount);n.connect(h),h.connect(c);const g=()=>{d&&window.clearInterval(d)},S=()=>{r.state==="suspended"&&r.resume(),d=window.setInterval(()=>{h.getByteFrequencyData(f);let b=Math.round(f.reduce((v,R)=>v+R)/f.length);b=Math.min(100,b),p=b,l&&l(b)},u)};return S(),{updateInterval:b=>{g(),u=b,S()},getLevel:()=>p,dispose:()=>{g(),n.disconnect(),h.disconnect()}}}(this.audioContext,this.sourceNode,i,t,r=>{this.emit("audioLevel",r)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class on extends ne{constructor(e,t,i,r){super();m(this,"uid");m(this,"name");m(this,"rtsManager");m(this,"callId","");m(this,"audioLevelMonitor");m(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=r,this.audioLevelMonitor=new nc}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=ke.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class cn{static getCurrentStatus(s){let e=0;s.micOpen&&(e+=1),s.micInterrupted&&(e+=2),s.cameraOpen&&(e+=4),s.screenShare&&(e+=128),s.audioDisable&&(e+=8),s.videoDisable&&(e+=16),s.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(s){let e=parseInt(s,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}const k=(a,s)=>(e,t,i)=>{const r=i.value;return i.value=function(...n){var u;const c=`[${this.logName||((u=e.constructor)==null?void 0:u.logName)||""}]`,o=Date.now();let l=[];if(a)try{l=a(n)}catch(p){}C.interface(c,t,...l);const d=r.apply(this,n);return Promise.resolve(d).then(p=>p).catch(p=>p).then(p=>{var S;let h="";const f=p instanceof Error,g=f&&((S=e.constructor)==null?void 0:S.logError);if(s||f){if(g)h=p;else if(f)h=p.message||"";else{if(!s)return;if(p===void 0)h="";else try{h=s(p)}catch(b){}}C.interfaceResult(c,t,!(f&&g),Date.now()-o+"ms",h)}}),d},i},H=a=>a,ln="customVideoProfile",dn="customScreenProfile",Pr={width:1280,height:720,frameRate:30,maxBitrate:2e3},un={width:1920,height:1080,frameRate:30,maxBitrate:2600};var Si=(a=>(a[a.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",a[a.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",a[a.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",a[a.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",a[a.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",a[a.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",a[a.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",a[a.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",a[a.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",a[a.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",a[a.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",a[a.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",a[a.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",a))(Si||{});const oc={1e4:De.AliEngineLocalDeviceExceptionTypeUnknown,2e4:De.AliEngineLocalDeviceExceptionTypeUnknown,10001:De.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:De.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:De.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:De.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:De.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:De.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:De.AliEngineLocalDeviceExceptionTypeDisplayException,10011:De.AliEngineLocalDeviceExceptionTypeDisplayException,10012:De.AliEngineLocalDeviceExceptionTypeDisplayException,10013:De.AliEngineLocalDeviceExceptionTypeDisplayException,10014:De.AliEngineLocalDeviceExceptionTypeDisplayException,10019:De.AliEngineLocalDeviceExceptionTypeDisplayException};var Xe=(a=>(a.CREATE_ENGINE="create_engine",a.JOIN="join",a.WANT_INSERT_PUB_TASK="wantInsertPubTask",a.INSERT_PUB_TASK="InsertPubTask",a.HANDLE_PUB_TASK="HandlePubTask",a.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",a.INSERT_SUB_TASK="InsertSubTask",a.HANDLE_SUB_TASK="HandleSubTask",a.FIRST_REMOTE="first_remote",a))(Xe||{}),tt=(a=>(a.START="start",a.SEND_SIG="send_sig",a.RECV_RST="recv_rst",a.END="end",a.RECEIVED="received",a.DECODED="decoded",a.PLAYED="played",a))(tt||{});const hn=(a,s,e=!1)=>{const t=()=>(a.muted=!0,Promise.race([Nt(500),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&a.srcObject===s?i=Promise.resolve():(a.load(),a.srcObject=s,i=a.play(),a._playPromise=i),i}));return new Promise(i=>{if(J.AliRTS.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,n=window.WeixinJSBridge||window.top.WeixinJSBridge;n?n.invoke("getNetworkType",{},()=>{i(t())}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{n.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},It=a=>{Promise.race([Nt(100),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{a.srcObject=null,a._playPromise=void 0})};var Dr=(a=>(a[a.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",a[a.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",a[a.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",a))(Dr||{});class Ui{constructor(s,e,t,i=0){m(this,"msgType");m(this,"msgId");m(this,"protocolVersion");m(this,"tlvVersion");this.msgType=s,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const s=new Uint8Array(4);return s.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),s.set(Uint16Array.from([this.msgId]),2),s}static parse(s){const e=new DataView(s),t=e.getUint8(0),i=e.getUint8(1)>>4,r=15&e.getUint8(1),n=e.getUint16(2);return new Ui(r,n,t,i)}}class Bi{constructor(s,e,t){m(this,"_byteArray");if(this._byteArray=new Uint8Array(0),s!==void 0&&e!==void 0&&t!==void 0){const i=new Ui(s,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(s,e){const t=this._byteArray,i=new ArrayBuffer(5),r=new DataView(i);r.setUint8(0,s),r.setUint32(1,e.byteLength);const n=new Uint8Array(t.byteLength+5+e.byteLength);n.set(t,0),n.set(new Uint8Array(i),t.byteLength),n.set(new Uint8Array(e),t.byteLength+5),this._byteArray=n}static parse(s){const e={},t=new DataView(s);let i=0;for(;i<s.byteLength;){const r=t.getUint8(i),n=t.getUint32(i+1);if(!(i+5+n<=s.byteLength))break;{const c=s.slice(i+5,i+5+n);e[r]=c,i+=5+n}}return e}get buffer(){return this._byteArray.buffer}}class bi{constructor(s=0,e=!0,t=1,i=!1,r=0,n=!1,c=!1,o=3){m(this,"_fin",!0);m(this,"_hasExtension",!1);m(this,"_version",0);m(this,"_frameType",1);m(this,"_isEncrypted",!1);m(this,"_isCompressed",!1);m(this,"_signalType",3);m(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=r,this._frameType=t,this._isEncrypted=n,this._isCompressed=c,this._signalType=o,this._payloadLength=s}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const s=new ArrayBuffer(4),e=new DataView(s);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),s}static parse(s){const e=new DataView(s),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,r=(48&e.getUint8(0))>>4,n=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,l=15&e.getUint8(1),d=e.getUint16(2);return new bi(d,t,n,i,r,c,o,l)}}class Hi{constructor(s,e){m(this,"_body");m(this,"_header",new bi);this._header=s,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const s=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+s.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(s),t.byteLength),i.set(new Uint8Array(e),t.byteLength+s.byteLength),i.buffer}static parse(s){const e=s.slice(0,4),t=bi.parse(e);let i=new ArrayBuffer(0);return s.byteLength-4>=t.payloadLength&&(i=s.slice(4,4+t.payloadLength)),new Hi(t,i)}}const Mr=a=>{const s=a.byteLength,e=new DataView(a);let t=0;for(let i=0;i<s;i++)t=256*t+e.getUint8(i);return t};let pn=0;class Ut{constructor(s,e=0,t=0,i=0){m(this,"data");m(this,"networkTime");m(this,"futureOrProgress");m(this,"type");this.data=s,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const s=new Bi(0,0,0);s.write(1,Uint8Array.from([0]).buffer),s.write(2,Uint16Array.from([0]).buffer),pn++,s.write(3,Uint32Array.from([pn]).buffer);const e=new Bi;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),s.write(30,e.buffer),s.buffer}static parse(s){if(!s||s.byteLength<4)return;Ui.parse(s.slice(0,4));const e=Bi.parse(s.slice(4))[30];if(!e)return;const t=Bi.parse(e),i=t[2],r=t[3],n=t[4],c=t[5];return c.byteLength!==0?new Ut(c,Mr(i),Mr(n),Mr(r)):void 0}}var cc=Object.defineProperty,lc=Object.getOwnPropertyDescriptor,Te=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?lc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&cc(s,e,r),r};class vi extends ne{constructor(){super();m(this,"_state");m(this,"time");this._state=ee.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const Ae=(ht=class extends on{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:r,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);m(this,"sessionId","");m(this,"traceId","");m(this,"_url","");m(this,"joinTime",0);m(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));m(this,"previewElements",[]);m(this,"screenPreviewElements",[]);m(this,"streamManager");m(this,"dc");m(this,"streamTracks");m(this,"publishId",dt());m(this,"signalingManager");m(this,"shouldPublish",!1);m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"candidateDataCache",[]);m(this,"pcMediaStatsMap",{});m(this,"slsReporter");m(this,"audioPubState");m(this,"videoPubState");m(this,"videoSmallPubState");m(this,"screenPubState");m(this,"dataPubState");m(this,"parameter",{});m(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=n,this.slsReporter=r,this.parameter=o,this.streamManager.on("trackended",l=>{this.onTrackEnd(l)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new vi,this.audioPubState.on("change",(l,d,u)=>{this.emit("audioPublishStateChanged",l,d,u)}),this.videoPubState=new vi,this.videoPubState.on("change",(l,d,u)=>{this.emit("videoPublishStateChanged",l,d,u)}),this.videoSmallPubState=new vi,this.videoSmallPubState.on("change",(l,d,u)=>{this.emit("dualStreamPublishStateChanged",l,d,u)}),this.screenPubState=new vi,this.screenPubState.on("change",(l,d,u)=>{this.emit("screenPublishStateChanged",l,d,u)}),this.dataPubState=new vi,this.dataPubState.on("change",(l,d,u)=>{this.emit("dataPublishStateChanged",l,d,u)}),this.startStreamMonitor(),this.createCallId()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="audio"&&t&&r===M.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.sessionId=e.sessionId||ke.createCallid("web"),this.updatePubId()}setVideoProfile(e){return E(this,null,function*(){yield this.streamManager.setVideoProfile(ln,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return E(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return E(this,null,function*(){yield this.streamManager.setScreenProfile(dn,e)})}setCameraDirection(e){if(e===pi.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==pi.CAMERA_REAR)throw new V(B.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=dt()}clearPublishState(){this.streamTracks=void 0}leave(){return E(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0,this.dataPubState.setState(ee.AliRtcStateNoPublish)})}clear(){return E(this,null,function*(){Zr(ht.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(It(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(It(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return E(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:r}=this,{hasMicrophone:n,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,l=!t&&!e&&!i&&r,d=!n&&!c&&o;try{l&&d?yield this.startCameraAndMic():l?yield this.startCameraCapture():d&&(yield this.startAudioCapture())}catch(u){const p=u.errorCode;let h=B.ERR_CAMERA_OPEN_FAIL;throw l?((p===Si.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||Si.ERROR_DEVICE_NOTALLOWED)&&(h=B.ERR_CAMERA_AUTH_FAIL),h=B.ERR_CAMERA_OPEN_FAIL):((p===Si.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||Si.ERROR_DEVICE_NOTALLOWED)&&(h=B.ERR_MIC_AUTH_FAIL),h=B.ERR_MIC_OPEN_FAIL),new V(h,`auto open fail: ${u.message}`)}})}setViewConfig(e,t){if(e){if(![le.AliRtcVideoTrackCamera,le.AliRtcVideoTrackScreen].includes(t))throw new V(B.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===le.AliRtcVideoTrackScreen})})}else t===le.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return E(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return E(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return E(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return E(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return E(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return E(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let r=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new V(B.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return r?(hn(t,r.mediaStream),this.setPreviewElement(e),r.mediaStream):void C.info(`[${ht.logName}]`,"preview no stream founded")}catch(r){const n=B.ERR_INNER;throw V.fromError(r,n,"preview failed")}})}previewAll(e){return E(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let r=0;r<this.previewElements.length;r++){const n=this.previewElements[r];yield this.preview({videoElement:n})}if(i&&this.screenPreviewElements.length)for(let r=0;r<this.screenPreviewElements.length;r++){const n=this.screenPreviewElements[r];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:r=!0}=e||{};if(t){const n=this.previewElements.findIndex(c=>c===t);if(n>=0)this.previewElements.splice(n,1),It(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),It(t))}}else i&&(this.previewElements.forEach(n=>{It(n)}),this.previewElements=[]),r&&(this.screenPreviewElements.forEach(n=>{It(n)}),this.screenPreviewElements=[])}resumePublish(){return E(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),yield this.startPublish(!0))})}createLocalStream(e){return E(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const r=this.previewElements[i];It(r)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const r=this.screenPreviewElements[i];It(r)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=oc[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",ze.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",ze.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",ze.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",ze.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return E(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return E(this,null,function*(){var n,c;if(!e&&!t)return;if(e&&!t){const o={};return i===M.Audio?o.audio=!0:i===M.VideoLarge||i===M.VideoSmall?(o.video=!0,o.vMsid=i):i===M.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const r={};if(t!=null&&t.hasVideo&&(r.isScreen=i===M.Screen,r.vMsid=i),t!=null&&t.hasAudio&&(r.aMsid=i),!e&&t)return yield this.publishAdd(t,r,!1);if(e&&t&&e.trackId!==(((n=t.videoTrack)==null?void 0:n.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,r)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=J.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(M.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=J.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=J.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return E(this,null,function*(){if(this.dataPubState.state!==ee.AliRtcStatePublishing){this.dataPubState.setState(ee.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(ee.AliRtcStatePublished)):(this.dataPubState.setState(ee.AliRtcStateNoPublish),this.emit("publishDataError",new V(B.ERR_INNER,"publishDataError")))}catch(e){C.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(ee.AliRtcStateNoPublish)}}})}startPublish(){return E(this,arguments,function*(e=!1,t=Tt.MANUAL){var l,d,u;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:r,video:n,videoSmall:c,screen:o}=i;if(r||n||c||o)try{const p=new Date().getTime();r&&this.audioPubState.setState(ee.AliRtcStatePublishing),n&&this.videoPubState.setState(ee.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),o&&this.screenPubState.setState(ee.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,e,t);const{traceId:h,l1ip:f}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const g={type:Mt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?f:void 0,callid:this.callId,tracks:this.streamTracks,traceid:h};(l=this.parameter.data)!=null&&l.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(g,i,p)}),h&&(this.traceId=h),r&&this.reportAudioProfile(),n&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(g,i,p),r&&this.audioPubState.setState(ee.AliRtcStatePublished),n&&this.videoPubState.setState(ee.AliRtcStatePublished),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),o&&this.screenPubState.setState(ee.AliRtcStatePublished)}catch(p){throw r&&this.audioPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoPubState.setState(ee.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),o&&this.screenPubState.setState(ee.AliRtcStateNoPublish),p}else{if((d=this.parameter.data)!=null&&d.enablePubSubDataWithoutMedia&&((u=this.parameter.data)!=null&&u.enablePubDataChannel)){C.event(`[${ht.logName}]`,"startPublish no media stream, publish data channel only");try{const p=new Date().getTime();if(yield this.publishDataChannel(),this.dc){const h={type:Mt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:[],traceid:this.traceId};yield this.syncPublishToRoomServer(h,i,p)}}catch(p){C.error(`[${ht.logName}]`,"publishDataChannel without media failed",p)}return}C.event(`[${ht.logName}]`,"startPublish no stream founded")}})}updateStreams(){return E(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return E(this,null,function*(){var n,c,o,l,d;if(C.info(`[${ht.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const r=new Date().getTime();try{const u=(n=this.streamTracks)==null?void 0:n.find(({ssrc:R,type:_,msid:y})=>_==="audio"&&R&&y===M.Audio),p=yield this.compareAndPublish(u,t.audio,M.Audio);p&&(i=p);const h=(c=this.streamTracks)==null?void 0:c.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===M.VideoLarge),f=yield this.compareAndPublish(h,t.video,M.VideoLarge);f&&(i=f);const g=(o=this.streamTracks)==null?void 0:o.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===M.VideoSmall),S=yield this.compareAndPublish(g,t.videoSmall,M.VideoSmall);S&&(i=S);const b=(l=this.streamTracks)==null?void 0:l.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===M.Screen),v=yield this.compareAndPublish(b,t.screen,M.Screen);v&&(i=v),(d=this.parameter.data)!=null&&d.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),i||e!==Tt.RECONNECT?i&&(yield this.syncPublishToRoomServer(i,t,r)):this.syncPublishToRoomServer({type:Mt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},t,Date.now())}catch(u){const{code:p}=u!=null?u:{},h=this.url;throw p===403&&h&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),u}return i})}syncPublishToRoomServer(e,t,i){return E(this,null,function*(){var o;if(!e)return void C.event(`[${ht.logName}]`,"sync publish to room server failed because no publishInfo");let r=e;if(this.dc){const c=e,{tracks:l}=c,d=Ot(c,["tracks"]);r=vt(X({},d),{tracks:[...l,{type:"data",msid:M.Data,ssrc:`web_${this.callId.substring(0,8)}_${((o=this.dc.datachannel)==null?void 0:o.id)||"0"}`,codec:"text"}]})}const n=yield this.signalingManager.publish(r);e.signaltid=n.tid})}refreshPushStreamUrl(){return E(this,null,function*(){const e=new V(B.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,r=0){return E(this,null,function*(){const n=(t==null?void 0:t.aMsid)===M.Audio,c=(t==null?void 0:t.vMsid)===M.VideoLarge,o=(t==null?void 0:t.vMsid)===M.VideoSmall,l=(t==null?void 0:t.vMsid)===M.Screen;n&&this.audioPubState.setState(ee.AliRtcStatePublishing),c&&this.videoPubState.setState(ee.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),l&&this.screenPubState.setState(ee.AliRtcStatePublishing);try{const d=yield this.rtsManager.publishAdd(this,e,t,!1,!0);d&&(this.traceId=d),n&&(this.audioPubState.setState(ee.AliRtcStatePublished),this.reportAudioProfile()),c&&(this.videoPubState.setState(ee.AliRtcStatePublished),this.reportVideoProfile()),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),l&&(this.screenPubState.setState(ee.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const u={type:Mt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:d};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),u}catch(d){let u=B.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),l&&(this.screenPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),d.errorCode===15006&&r<3)return this.publishAdd(e,t,i,r+1);throw V.fromError(d,u,"publish add failed")}})}publishReplace(e,t){return E(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===M.VideoLarge,r=(t==null?void 0:t.vMsid)===M.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),r&&this.streamManager.setScreenProfile(void 0,void 0);const n={type:Mt.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),n}catch(i){throw V.fromError(i,B.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return E(this,null,function*(){const t={type:Mt.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(ee.AliRtcStateNoPublish),e.video&&(e.vMsid===M.VideoSmall?this.videoSmallPubState.setState(ee.AliRtcStateNoPublish):this.videoPubState.setState(ee.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(ee.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw V.fromError(i,B.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return E(this,null,function*(){C.info(`[${ht.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,r=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(ee.AliRtcStateNoPublish),i&&this.videoPubState.setState(ee.AliRtcStateNoPublish),r&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),n&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Mt.Stop,userid:this.userId,sessionid:this.sessionId,displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw V.fromError(t,B.ERR_INNER,"publish stop failed")}})}unPublish(){return E(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Mt.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,r=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(ee.AliRtcStateNoPublish),r&&this.videoPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),c&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(ee.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw V.fromError(i,B.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(Ze.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,r,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((n=(r=this.streamManager.screenStreamInfo)==null?void 0:r.originVideoTrack)!=null&&n.enabled),cn.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===M.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.traceId||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>E(this,null,function*(){var e,i;try{const r=yield this.rtsManager.getPCStats();let n,c;if(r==null||r.forEach(l=>{l.type==="media-source"||l.type==="media-playout"?l.id&&(this.pcMediaStatsMap[l.id]=l):l.type==="candidate-pair"&&l.state==="succeeded"&&(n=l)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const l=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=l,{_last:d}=t;c=Ot(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),n&&(n._last=c,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(l=>{var d;return((d=this.monitorDataCache[l])==null?void 0:d.length)>0});(this.streamTracks||[]).forEach(l=>{const d=l.msid;if(!d)return;let u;o.includes(d)&&(o=o.filter(p=>p!==d)),u=d===M.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,d),u.then(p=>{if(!p.timestamp)return;this.monitorDataCache[d]||(this.monitorDataCache[d]=[]);const h=this.getMediaStats(p.mediaSourceId);p._source=h;const f=this.monitorDataCache[d];let g;if((f==null?void 0:f.length)>0){const b=f[f.length-1]||{},S=b,{_last:v}=S;g=Ot(S,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(d),p._last=g,p._codec=l.codec||"",this.monitorDataCache[d].push(p)})}),o.forEach(l=>{this.reportPublishMonitor(l)})}catch(r){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(ee.AliRtcStatePublishIdle),this.videoPubState.setState(ee.AliRtcStatePublishIdle),this.videoSmallPubState.setState(ee.AliRtcStatePublishIdle),this.screenPubState.setState(ee.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return E(this,null,function*(){if(!this.url)return;let r=0;return r=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,r,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new V(B.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new V(B.ERR_INNER,"data channel is not ready");const t=function(r,n){let c=0;const o=[];for(;c<r.byteLength;){const l=Math.min(n,r.byteLength-c),d=r.slice(c,c+l);o.push(d),c+=l}return o}(e.toBuffer(),1156);t.forEach((r,n)=>{const c=new Hi(new bi(r.byteLength,n===t.length-1,n===0?1:0),r);this.dc.send(c.toGRTNBuffer())})}getStats(){return E(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:zt.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoLarge);n&&t.push({track:le.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoSmall);n&&t.push({track:le.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.Screen);n&&t.push({track:le.AliRtcVideoTrackScreen,stats:n})}let i;const r=yield this.rtsManager.getPCStats();return r==null||r.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(i=n)}),{audio:e,video:t,candidate:i}})}markReconnect(e){const t=[],i=this.streamManager.publishStreams;!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),!this.dc||e&&!e.includes(M.Data)||t.push(this.dataPubState),t.forEach(r=>{r.setState(ee.AliRtcStateReconnecting)})}markReconnected(e){var r;const t=[],i=this.streamManager.publishStreams;if(!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),this.dc&&(!e||e.includes(M.Data))&&(t.push(this.dataPubState),(r=this.parameter.data)==null?void 0:r.enablePubDataChannel)){const n=this.rtsManager.getDatachannelByMsid({url:this.url,msid:M.Data});this.updateDataChannel(n)}this.publishUpdate(Tt.RECONNECT),t.forEach(n=>{n.setState(ee.AliRtcStatePublished)})}},m(ht,"logName","LocalUser"),ht);Te([k()],Ae.prototype,"clearPublishState",1),Te([k()],Ae.prototype,"clear",1),Te([k(H)],Ae.prototype,"startDefaultCameraAndMic",1),Te([k()],Ae.prototype,"setViewConfig",1),Te([k()],Ae.prototype,"startCameraCapture",1),Te([k()],Ae.prototype,"stopCameraCapture",1),Te([k()],Ae.prototype,"startAudioCapture",1),Te([k()],Ae.prototype,"stopAudioCapture",1),Te([k()],Ae.prototype,"startCameraAndMic",1),Te([k()],Ae.prototype,"stopPreview",1),Te([k()],Ae.prototype,"resumePublish",1),Te([k()],Ae.prototype,"createLocalStream",1),Te([k()],Ae.prototype,"stopLocalStream",1),Te([k()],Ae.prototype,"updateDataChannel",1),Te([k(H)],Ae.prototype,"startPublish",1),Te([k()],Ae.prototype,"updateStreams",1),Te([k(([a])=>[a])],Ae.prototype,"syncPublishToRoomServer",1),Te([k()],Ae.prototype,"refreshPushStreamUrl",1),Te([k(([a,s,e])=>[JSON.stringify(e)])],Ae.prototype,"publishAdd",1),Te([k(([a,s])=>[JSON.stringify(s)])],Ae.prototype,"publishReplace",1),Te([k(H)],Ae.prototype,"publishDeleteTracks",1),Te([k()],Ae.prototype,"publishStop",1),Te([k()],Ae.prototype,"unPublish",1),Te([k(([a,s,e])=>[a.length,s,e])],Ae.prototype,"sendSEI",1),Te([k(H)],Ae.prototype,"markReconnect",1),Te([k(H)],Ae.prototype,"markReconnected",1);let dc=Ae;var gt=(a=>(a.OPUS="opus",a.H264="H264",a.H265="H265",a.AV1="AV1",a.UNKNOWN="",a))(gt||{}),de=(a=>(a[a.NotSubscribe=0]="NotSubscribe",a[a.Subscribing=1]="Subscribing",a[a.Subscribed=2]="Subscribed",a))(de||{}),Qt=(a=>(a.VideoTrackEnded="videoTrackEnded",a.AudioTrackEnded="audioTrackEnded",a.ScreenTrackEnded="screenTrackEnded",a))(Qt||{});const mn=a=>E(this,null,function*(){return yield J.AliRTS.createStream({custom:!0,mediaStream:a})}),yi=a=>E(this,null,function*(){const s=(e=>{const t=new MediaStream;return t.addTrack(e),t})(a);return yield mn(s)});var uc=Object.defineProperty,hc=Object.getOwnPropertyDescriptor;class Nr extends ne{constructor(){super();m(this,"audioInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:gt.UNKNOWN});m(this,"videoLargeInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:gt.UNKNOWN});m(this,"videoSmallInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:gt.UNKNOWN});m(this,"screenInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:gt.UNKNOWN});m(this,"dataInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:gt.UNKNOWN});m(this,"audioVolume",1);m(this,"audioMuted",!1);m(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===de.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===de.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===de.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===de.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===de.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===de.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===de.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===de.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===de.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===de.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===de.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:gt.UNKNOWN}get audioTrackInfo(){return this.hasAudio?zt.AliRtcAudioTrackMic:zt.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?le.AliRtcVideoTrackBoth:this.hasVideo?le.AliRtcVideoTrackCamera:this.hasScreen?le.AliRtcVideoTrackScreen:le.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",r="",n="",c="";return e?(e.forEach(o=>{var p;let l=gt.UNKNOWN;const d=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:h}=JSON.parse(o.userdata);h&&(l=h)}var u;(u=o.msid)===M.Audio||u===Yi.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=l,(d||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=de.NotSubscribe)):(h=>h===M.VideoSmall)(o.msid)?(r=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=l,(d||this.videoSmallInfo.ssrc!==r)&&(this.videoSmallInfo.subscribeState=de.NotSubscribe)):(h=>h===M.VideoLarge||h===Yi.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=l,(d||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=de.NotSubscribe)):(h=>h===M.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=l,(d||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=de.NotSubscribe)):(h=>h===M.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=l,(d||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=de.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,r,n,c)):this.updateRemoteTrackSsrc(t,i,r,n,c),{}}updateRemoteTrackSsrc(e,t,i,r,n){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=r,this.dataInfo.ssrc=n}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=de.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=de.Subscribing)),e.screen&&(this.screenInfo.subscribeState=de.Subscribing),e.audio&&(this.audioInfo.subscribeState=de.Subscribing),e.data&&(this.dataInfo.subscribeState=de.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?de.Subscribed:de.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?de.Subscribed:de.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?de.Subscribed:de.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=cn.parseStatus(e);const{audioDisable:i,videoDisable:r,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(Ze.Remote,i?Ce.MuteAudio:Ce.UnmuteAudio)),this.userStatus.videoDisable!=r&&(this.userStatus.videoDisable=r,this.emit(Ze.Remote,r?Ce.MuteVideo:Ce.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(Ze.Remote,n?Ce.MuteScreen:Ce.UnmuteScreen))):(this.userStatus=t,this.emit(Ze.Remote,i?Ce.MuteAudio:Ce.UnmuteAudio),this.emit(Ze.Remote,r?Ce.MuteVideo:Ce.UnmuteVideo),this.emit(Ze.Remote,n?Ce.MuteScreen:Ce.UnmuteScreen)),!1}}m(Nr,"logName","RemoteStreamInfo"),((a,s,e,t)=>{for(var i,r=t>1?void 0:t?hc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);t&&r&&uc(s,e,r)})([k()],Nr.prototype,"updateRemoteTrackSubState",1);class gn{constructor(s){m(this,"remoteUser");this.remoteUser=s}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var pc=Object.defineProperty,mc=Object.getOwnPropertyDescriptor,je=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?mc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&pc(s,e,r),r};class oi extends ne{constructor(){super();m(this,"state");m(this,"time");m(this,"_enabled");this.state=oe.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const He=(ii=class extends on{constructor(e){var h;const{userId:t,displayName:i,rtsManager:r,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:l,audioVolumeIndicationInterval:d,playoutVolume:u,parameter:p}=e;super(t,i,r,d);m(this,"remoteCallId","");m(this,"remoteUserInfo");m(this,"localUser");m(this,"lastPubId","");m(this,"stream");m(this,"screenStream");m(this,"viewMap");m(this,"audioTrack");m(this,"audioElement");m(this,"subscribed",!1);m(this,"mediaStream");m(this,"secondaryMediaStream");m(this,"prevSubConfig");m(this,"signalingManager");m(this,"slsReporter");m(this,"wantSubAudio",!1);m(this,"wantSubVideo",!1);m(this,"wantSubScreen",!1);m(this,"defaultVideoStreamType",Ke.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"playoutGainNode");m(this,"audioSubState");m(this,"videoSubState");m(this,"videoLargeSubState",new oi);m(this,"videoSmallSubState",new oi);m(this,"screenSubState");m(this,"dataSubState");m(this,"dc");m(this,"dcMsgWaitingPieces",[]);m(this,"streamInfo");m(this,"_streamUrl","");m(this,"parameter",{});m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"traceId","");m(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});m(this,"onDataChannelMessage",e=>{var r;const t=Hi.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const n=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(n);let o=0;for(let l=0;l<this.dcMsgWaitingPieces.length;l++){const d=this.dcMsgWaitingPieces[l];new Uint8Array(c,o,d.byteLength).set(new Uint8Array(d)),o+=d.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=Ut.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=Ut.parse(t.body))}else i=Ut.parse(t.body);i||C.event(`[${this.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(C.event(`[${this.logName}]`,`receive dc message, length(${(r=i.data)==null?void 0:r.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});m(this,"onDataChannelError",e=>{this.emit("occurError",V.fromError(e,B.ERR_SDK_SUBSCRIBE_DATA_ERROR))});m(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});m(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new Nr,this.remoteUserInfo=new gn(this),this.parameter=p,this.streamInfo.on(Ze.Remote,f=>{this.emit(Ze.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(h=n[t])!=null?h:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=c,this.localUser=l,this.audioSubState=new oi,this.audioSubState.on("change",(f,g,S)=>{this.emit("audioSubscribeStateChanged",this.uid,f,g,S)}),this.videoSubState=new oi,this.videoSubState.on("change",(f,g,S)=>{this.emit("videoSubscribeStateChanged",this.uid,f,g,S)}),this.screenSubState=new oi,this.screenSubState.on("change",(f,g,S)=>{this.emit("screenSubscribeStateChanged",this.uid,f,g,S)}),this.dataSubState=new oi,this.dataSubState.on("change",(f,g,S)=>{this.emit("dataSubscribeStateChanged",this.uid,f,g,S)}),this.playoutVolume=u}get logName(){return`${ii.logName}(${this.userId})`}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(me.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=Yt.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const r=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),r.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){return this.streamInfo.hasAudio}get audioSSRC(){var e;return this.streamInfo.isAudioSubscribed&&((e=this.streamInfo.getAudioInfo())==null?void 0:e.ssrc)||""}get hasVideoTrack(){return this.streamInfo.hasVideo}get videoSSRC(){var e,t;return this.streamInfo.isVideoSubscribed?((e=this.streamInfo.getVideoLargeInfo())==null?void 0:e.ssrc)||"":this.streamInfo.isVideoSmallSubscribed&&((t=this.streamInfo.getVideoSmallInfo())==null?void 0:t.ssrc)||""}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.isDataSubscribing}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==le.AliRtcVideoTrackScreen&&t!==le.AliRtcVideoTrackCamera)throw new V(B.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?Qi(e).forEach(i=>{i.setAttribute("playsinline",""),J.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),J.AliRTS.SystenUtil.isAndroid||J.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===le.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===le.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===le.AliRtcVideoTrackScreen),t===le.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return E(this,null,function*(){Zr(ii.prototype,this,"clear").call(this),this.stopPlayAudio(),this.stopStreamMonitor(),e&&this.subscribeDeleteAllTracks(this.streamUrl).catch(t=>{C.event(`[${this.logName}]`,`stopSubscribeAllTracks error: ${t.message||t}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,Yt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(Ze.Remote)})}updateRemoteUserDeviceStatus(e){this.streamInfo.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,r){return E(this,null,function*(){return this.remoteCallId=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.streamInfo.updateTracks(r)})}subscribe(r,n){return E(this,arguments,function*(e,t,i=Date.now()){var h,f;this.createCallId();let c=e;if(!c){const{hasAudio:g,hasVideo:S,hasScreen:b,hasData:v}=(h=this.streamInfo)!=null?h:{};c={audio:this.wantSubAudio&&g,video:this.wantSubVideo&&S,screen:this.wantSubScreen&&b,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:l,video:d,vMsid:u}=c,p=[];(d||l)&&p.push({audio:l,video:d,vMsid:u}),o&&p.push({screen:o}),(p.length!==0||e!=null&&e.data)&&(yield Promise.all(p.map(g=>this.subscribeProxy(g,t||me.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return E(this,null,function*(){var c,o;let r=new Date().getTime(),n="";if(this.streamUrl)try{e.audio&&this.audioSubState.setState(oe.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==oe.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==oe.AliRtcStateNoSubscribe||this.videoSubState.setState(oe.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(oe.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);if(!l)return e.audio&&this.audioSubState.setState(oe.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(oe.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(oe.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid});this.streamInfo.updateRemoteTrackSubState(e),n=l.traceId||"";const{stream:d}=l;if(n&&(this.traceId=n),e.audio){const h=d.audioTrack;h&&(this.audioTrack=h,(o=d.mediaStream)==null||o.removeTrack(h),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(h,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(oe.AliRtcStateSubscribed)}e.video&&(this.updateStream(d,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(oe.AliRtcStateSubscribed),e.vMsid===M.VideoSmall?this.videoSmallSubState.setState(oe.AliRtcStateSubscribed):this.videoLargeSubState.setState(oe.AliRtcStateSubscribed)),e.screen&&(this.updateScreenStream(d),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(oe.AliRtcStateSubscribed));const u=new Date().getTime()-r,p=Date.now();setTimeout(()=>{this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,0,"",u,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:t===me.Join?1:0,url:this.streamUrl,est:r},p)},6e3),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,Nt(1500)]))}catch(l){const d=new Date().getTime()-r;e.audio&&this.audioSubState.setState(oe.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(oe.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(oe.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let u=B.ERR_INNER;e.audio&&(u=B.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(u=e.vMsid===M.VideoSmall?B.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:B.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(u=B.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,u,"",d,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===me.Join?1:0,url:this.streamUrl,est:r});const p=V.fromError(l,u);this.emit("remoteSubscribeError",p)}else{const l=new V(B.ERR_SDK_SUBSCRIBE_INVAILD,`user(${this.uid}) subscribe failed: streamUrl is not ready. Please subscribe after receiving 'remoteTrackAvailableNotify' event instead of 'remoteUserOnLineNotify'.`);this.emit("remoteSubscribeError",l)}})}subscribeDeleteTracks(e){return E(this,null,function*(){const{audio:t,video:i,screen:r,data:n,vMsid:c}=e,o=[];(t||i||n)&&o.push({audio:t,video:i,vMsid:c}),r&&o.push({screen:r}),o.length!==0&&(yield Promise.all(o.map(l=>this.subscribeDeleteProxy(l))),e.data&&this.subscribeDeleteDataChannel())})}subscribeDeleteProxy(e){return E(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},r={};e.audio===!0&&(r.audio=!1,this.audioSubState.setState(oe.AliRtcStateNoSubscribe)),e.video===!0&&(r.video=!1,e.vMsid===M.VideoSmall?(this.videoSmallSubState.setState(oe.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==oe.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==oe.AliRtcStateSubscribeIdle||this.videoSubState.setState(oe.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(oe.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==oe.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==oe.AliRtcStateSubscribeIdle||this.videoSubState.setState(oe.AliRtcStateNoSubscribe))),e.screen===!0&&(r.screen=!1,this.screenSubState.setState(oe.AliRtcStateNoSubscribe));const{callId:n,remoteCallId:c}=this,o={callid:n,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw V.fromError(t,B.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return E(this,null,function*(){const e=Yt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return E(this,null,function*(){return e&&e!==le.AliRtcVideoTrackCamera&&e!==le.AliRtcVideoTrackBoth?e&&e!==le.AliRtcVideoTrackScreen&&e!==le.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return E(this,null,function*(){let t=new Date().getTime();try{e?yield this.subscribeDeleteTracks(e):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,"")}catch(i){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,""),i}})}subscribeDeleteAllTracks(e){return E(this,null,function*(){var r,n,c,o;const{callId:t,remoteCallId:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&e)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const l={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",l}catch(l){if(((o=(c=(n=(r=l==null?void 0:l.extraInfo)==null?void 0:r.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw V.fromError(l,B.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return E(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let r,n;if(e.mediaStream){n=document.createElement("video");const c=()=>{C.event(`[${this.logName}]`,"new mediaStream canplay"),n&&n.removeEventListener("canplaythrough",c,!1),n=void 0,clearTimeout(r),i(!0)};n.addEventListener("canplaythrough",c,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else i(!0);r=window.setTimeout(()=>{C.event(`[${this.logName}]`,"new mediaStream timeout"),n=void 0,i(!0)},3e3)}),this.updateSubscribe(me.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){var e;if(this.dc)try{this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(t){}if(!((e=this.parameter.data)!=null&&e.enablePubSubDataWithoutMedia||this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen))return this.dataSubState.setState(oe.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({data:!1});this.dataSubState.setState(oe.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(t=>{if(t)return this.dataChannelConnected(t),this.dataSubState.setState(oe.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(t=>{const i=V.fromError(t,B.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",i),this.dataSubState.setState(oe.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({data:!1})})}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(oe.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,r;const e={};this.wantSubAudio&&this.streamInfo.hasAudio&&(e.audio=!0,e.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(e.video=!0,e.vMsid=M.VideoSmall):this.streamInfo.hasVideoLarge&&(e.video=!0,e.vMsid=((r=this.streamInfo.getVideoLargeInfo())==null?void 0:r.msid)||M.VideoLarge)),this.wantSubScreen&&this.streamInfo.hasScreen&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var n,c,o,l,d,u;const t=Date.now(),i={},r={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==oe.AliRtcStateReconnecting?(i.audio=!0,i.aMsid=((n=this.streamInfo.getAudioInfo())==null?void 0:n.msid)||M.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(r.audio=!0,r.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==oe.AliRtcStateReconnecting?(i.video=!0,i.vMsid=M.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall||this.videoLargeSubState.currentState===oe.AliRtcStateReconnecting||(i.video=!0,i.vMsid=((o=this.streamInfo.getVideoLargeInfo())==null?void 0:o.msid)||M.VideoLarge),this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(r.video=!0,r.vMsid=M.VideoLarge):this.defaultVideoStreamType!==Ke.AliRtcVideoStreamTypeHigh&&this.streamInfo.hasVideoSmall||!this.isVideoLargeSubscribing||!this.isVideoSmallSubscribing||(r.video=!0,r.vMsid=M.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(r.video=!0,r.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((l=this.streamInfo.getVideoLargeInfo())==null?void 0:l.msid)||M.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==oe.AliRtcStateReconnecting?i.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(r.screen=!0),(d=this.parameter.data)!=null&&d.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==oe.AliRtcStateReconnecting?i.data=!0:(u=this.parameter.data)!=null&&u.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(r.data=!0),this.dc&&i.data&&this.subscribeDeleteDataChannel(),(i.audio||i.video||i.screen||i.data)&&this.subscribe(i,e,t),(r.audio||r.video||r.screen)&&this.subscribeDeleteTracks(r),{addOption:i,deleteOption:r}}handleAutoPlayFailed(){C.event(`[${this.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const i=()=>{var n;const r=(n=t===le.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===r&&this.play(e,t===le.AliRtcVideoTrackScreen),document.removeEventListener("click",i,!1),document.removeEventListener("touchstart",i,!1)};document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}playAudio(){return E(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(C.event(`[${this.logName}]`,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(r=>{i.removeTrack(r)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(J.AliRTS.SystenUtil.isIos&&parseInt(J.AliRTS.SystenUtil.systemVersion)<=13){C.event(`[${this.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const r=()=>{i.removeEventListener("playing",r),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",r)}else(()=>{var i;C.event(`[${this.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{C.event(`[${this.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else C.event(`[${this.logName}]`,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const r=t?this.screenStream:this.stream;e&&r&&r.mediaStream&&hn(e,r.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?le.AliRtcVideoTrackScreen:le.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{It(t)}):this.viewMap.cameraViews.forEach(t=>{It(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return E(this,null,function*(){var i,r,n;const e=[];if(this.isAudioSubscribing){const c=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);c&&e.push({uid:this.uid,track:zt.AliRtcAudioTrackMic,stats:c})}const t=[];if(this.streamInfo.isVideoLargeSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||M.VideoLarge);c&&t.push({uid:this.uid,track:le.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeHigh,stats:c})}if(this.streamInfo.isVideoSmallSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((r=this.streamInfo.getVideoSmallInfo())==null?void 0:r.msid)||M.VideoSmall);c&&t.push({uid:this.uid,track:le.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeLow,stats:c})}if(this.isScreenSubscribing){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((n=this.streamInfo.getScreenInfo())==null?void 0:n.msid)||M.Screen);c&&t.push({uid:this.uid,track:le.AliRtcVideoTrackScreen,stats:c})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){e&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>E(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let r;e.includes(i)&&(e=e.filter(c=>c!==i));const n=i===M.Audio;r=n?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),r.then(c=>{var u;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let l;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},d=p,{_last:h}=d;l=Ot(d,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=l,c._codec=t.codec,n&&(c._source=(u=this.localUser)==null?void 0:u.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}markReconnect(e){const t=[];!this.isAudioSubscribing||e&&!e.includes(this.streamInfo.getAudioInfo().msid)||t.push(this.audioSubState),this.isVideoSubscribing&&(!e||e.includes(this.streamInfo.getVideoLargeInfo().msid)||e.includes(this.streamInfo.getVideoSmallInfo().msid))&&t.push(this.videoSubState),!this.isScreenSubscribing||e&&!e.includes(this.streamInfo.getScreenInfo().msid)||t.push(this.screenSubState),!this.isDataSubscribing||e&&!e.includes(M.Data)||t.push(this.dataSubState),t.forEach(i=>{i.setState(oe.AliRtcStateReconnecting)})}markReconnected(e){const t=[],i=this.streamInfo.getAudioInfo().msid||M.Audio;if(this.isAudioSubscribing&&(!e||e.includes(i))){t.push(this.audioSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:i});o&&o.audioTrack&&(this.audioTrack=o.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const r=this.streamInfo.getVideoLargeInfo().msid||M.VideoLarge,n=this.streamInfo.getVideoSmallInfo().msid||M.VideoSmall;if(this.isVideoSubscribing&&(!e||e.includes(r)||e.includes(n))){t.push(this.videoSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?n:r});o&&o.mediaStream&&(this.stream=o,this.playAll(!1))}const c=this.streamInfo.getScreenInfo().msid||M.Screen;if(this.isScreenSubscribing&&(!e||e.includes(c))){t.push(this.screenSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:c});o&&o.mediaStream&&(this.screenStream=o,this.playAll(!0))}if(this.isDataSubscribing&&(!e||e.includes(this.streamInfo.getDataInfo().msid))){t.push(this.dataSubState);const o=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||M.Data});this.dataChannelConnected(o)}t.forEach(o=>{o.setState(oe.AliRtcStateSubscribed)}),e||this.updateSubscribe(me.Reconnect)}},m(ii,"logName","RemoteUser"),ii);je([k()],He.prototype,"clear",1),je([k()],He.prototype,"updateRemoteUserDeviceStatus",1),je([k()],He.prototype,"updateRemoteTracks",1),je([k(H)],He.prototype,"subscribe",1),je([k()],He.prototype,"subscribeProxy",1),je([k(H)],He.prototype,"subscribeDeleteProxy",1),je([k()],He.prototype,"restore",1),je([k(H)],He.prototype,"resumeAudio",1),je([k(H)],He.prototype,"stopSubscribe",1),je([k(H)],He.prototype,"subscribeDeleteAllTracks",1),je([k()],He.prototype,"clearStream",1),je([k()],He.prototype,"clearScreenStream",1),je([k()],He.prototype,"updateSubscribe",1),je([k()],He.prototype,"playAudio",1),je([k()],He.prototype,"stopPlayAudio",1),je([k((a,s,e)=>[typeof a=="string"?a:a==null?void 0:a.nodeType,s||"-",e||"-"])],He.prototype,"play",1),je([k()],He.prototype,"stopPlayAll",1),je([k(H)],He.prototype,"markReconnect",1),je([k(H)],He.prototype,"markReconnected",1);let gc=He;var Bt=(a=>(a[a.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",a[a.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",a[a.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",a[a.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",a[a.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",a[a.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",a[a.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",a[a.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",a))(Bt||{});class fc extends ne{constructor(){super(...arguments);m(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new V(Bt.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new V(Bt.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){this.plugins.forEach(e=>{this.remove(e.name)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}const Sc=a=>E(this,null,function*(){const s=new J.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:s.checkMediaDevices()&&s.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield s.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=s.checkBrowser({errorCode:0,message:""})}if(e.support=t,s.checkWebRtcSupport()&&a!=="sendonly"){const i=yield s.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(s.checkWebRtcSupport()&&a!=="recvonly"){const i=yield s.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=s.checkWebRtcSupport()&&s.checkScreenCapture()&&!J.AliRTS.SystenUtil.isAndroid&&!J.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=s.checkWebRtcSupport()&&s.checkEncodedTransformSupport(),e}),{BrowserUtil:fn}=J.AliRTS,Ct="RtsManager";class bc{constructor(s){m(this,"ctx");m(this,"rtsClientMap",new Map);m(this,"pubBaseUrl");this.ctx=s}createPerUserRtsInstance(){return J.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0}})}getOrCreateClientEntry(s){let e=this.rtsClientMap.get(s);if(!e){const t=this.createPerUserRtsInstance();e={client:t,connected:!1,traceId:""},this.rtsClientMap.set(s,e),this.addPerUserRTSListener(t,s)}return e}destroyClientEntry(s){const e=this.rtsClientMap.get(s);if(e){try{e.client.removeAllListeners(),e.client.unsubscribe()}catch(t){}this.rtsClientMap.delete(s)}}addPerUserRTSListener(s,e){s.on("connectStatusChange",t=>{C.event(`[${Ct}]`,`[multi-pc:${e}] connectStatusChange to:`,t.status);const i=this.rtsClientMap.get(e);i&&(t.status===J.EConnectStatus.CONNECT_STATUS_DISCONNECTED?(i.connected=!1,e===this.pubBaseUrl&&(this.ctx.slsReporter.reportWarning("rts disconnected (multi-pc pub)"),this.ctx.emit("disconnected"))):t.status===J.EConnectStatus.CONNECT_STATUS_CONNECTED&&(i.connected=!0,e===this.pubBaseUrl&&this.ctx.emit("connected",!1,Ri.PUBLISH)))}),s.on("reconnect",t=>{var i,r,n;C.debug(`[${Ct}]`,`[multi-pc:${e}] reconnect`,t),this.ctx.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(r=t.extraInfo)==null?void 0:r.msids)==null?void 0:n.map(c=>c.name))}),s.on("reconnectFinish",t=>{var r;C.debug(`[${Ct}]`,`[multi-pc:${e}] reconnectFinish`,t),this.ctx.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(r=t==null?void 0:t.msids)==null?void 0:r.map(n=>n.name));const i=this.rtsClientMap.get(e);if(i&&(i.connected=!0),e===this.pubBaseUrl)try{this.ctx.emit("connected",!0,Ri.PUBLISH)}catch(n){C.error(`[${Ct}]`,"emit connected error:",n)}}),s.on("receivedSEI",t=>{this.ctx.emit("seimessage",t.url,t.sei.payloadType,t.sei.data)}),s.on("traceId",({url:t,traceId:i})=>{if(!t||!i||this.ctx.traceIdMap[t]===i)return;this.ctx.traceIdMap[t]=i;const r=this.rtsClientMap.get(e);r&&(r.traceId=i),this.ctx.emit("traceIdUpdated",t,i)}),s.on("onError",t=>{C.event(`[${Ct}]`,`[multi-pc:${e}] onError:`,t)})}get isConnected(){var s,e;if(this.pubBaseUrl)return(e=(s=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:s.connected)!=null?e:!1;for(const t of this.rtsClientMap.values())if(t.connected)return!0;return!1}get isConnecting(){if(this.pubBaseUrl){const s=this.rtsClientMap.get(this.pubBaseUrl);return!!s&&!s.connected}return!1}publish(s,e,t){return E(this,null,function*(){const i=s.url,r=s.callId,n=i.split("?")[0];this.pubBaseUrl=n;const c=this.getOrCreateClientEntry(n),o=Date.now();let l;const{publishStream:d,vMsid:u}=yield this.ctx.localStreamManager.createHTTPPublishStream();if(!d)return C.warn(`[${Ct}]`,"multiPCPublish: publishStream is null"),{traceId:"",l1ip:l};const p=this.ctx.getPubMsid(d,{vMsid:u});p.answerSdpHook=v=>{const R=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(v);return R!=null&&R[0]&&(l=R[0]),v},this.ctx.handleHTTPConfig(p),p.disableHeartbeat=!0,this.ctx.rtsPeerConnectionType=Ri.PUBLISH;const h=Date.now();let f="";try{const v=this.ctx.suffixHttpUrl(i);f=yield c.client.publish(v,d,p)}catch(v){c.connected=!1;const R=2e3-(Date.now()-h);throw R<=0?this.ctx.emit("disconnected"):setTimeout(()=>{this.ctx.emit("disconnected")},R),this.ctx.slsReporter.reportPublish(e,i,r,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,(v==null?void 0:v.errorCode)||-1,this.ctx.pcTraceId,"",h,h),V.fromRtsError(v)}f&&(this.ctx.pcTraceId=f,c.traceId=f),c.connected=!0,this.ctx.publishingTracks=c.client.getPublishTrackInfoList(),C.event(`[${Ct}]`,"multiPCPublish success",f);const g=Date.now();setTimeout(()=>{this.ctx.slsReporter.reportPublish(e,i,r,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,0,this.ctx.pcTraceId,s.traceId,h,g)},6e3),this.ctx.slsReporter.reportConnectionLatencyEvent(Xe.HANDLE_PUB_TASK,tt.START,r,f,o),this.ctx.slsReporter.reportConnectionLatencyEvent(Xe.HANDLE_PUB_TASK,tt.END,r,f,Date.now());const S=!d.hasVideo,b=u;return yield this.waitPublishSender(i,S,b),this.ctx.slsReporter.reportPublishFirstPacket(e,r,h,g,this.ctx.localJoinTime,S?M.Audio:p.vMsid,f||"",f||"",t),this.ctx.emit("connected",!1,Ri.PUBLISH),{traceId:f,l1ip:l}})}publishStop(s){return E(this,null,function*(){if(this.pubBaseUrl){const e=this.rtsClientMap.get(this.pubBaseUrl);e&&(yield e.client.publishStop([{url:s}]),this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0)}return this.ctx.publishingTracks=[],""})}unpublish(){return E(this,null,function*(){this.pubBaseUrl&&(this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0),this.ctx.publishingTracks=[]})}subscribe(s,e,t,i,r){return E(this,null,function*(){const{options:n,remoteUser:c}=s;if(n.screen)return C.warn(`[${Ct}]`,"screen subscribe not supported in multi-PC mode"),null;const o=c.streamUrl,l=o.split("?")[0];this.ctx.subUrlMap[c.userId]=l;const d=this.getOrCreateClientEntry(l),u=this.ctx.getSubConfig(c.streamInfo,n);this.ctx.handleHTTPConfig(u),u.disableHeartbeat=!0;const p=Date.now();let h;try{const w=this.ctx.suffixHttpUrl(o,u);h=yield d.client.subscribe(w,u)}catch(w){throw d.connected=!1,V.fromRtsError(w)}d.connected=!0,d.traceId=h.traceId,this.ctx.reportSubscribeLatency(n,t,p,!0);const f={traceId:h.traceId,stream:h,isHTTP:!0},g=Date.now();let S=M.VideoLarge;const b=n.video,v=n.audio;n.video&&n.vMsid&&(S=n.vMsid);let R=0,_=0,y=0;const A=((w,T)=>{let I=0;const P=()=>{if(!this.rtsClientMap.has(l))return Promise.resolve();let D;return v&&!R&&(D=d.client.getSubscribeAudioStats(o).then(U=>{if(U.packetsReceived>0)R=Date.now();else if(!b)return I<w&&(I++,new Promise(q=>setTimeout(()=>q(P()),T)));return!0})),b&&!y&&(D=d.client.getSubscribeVideoStats(o,S).then(U=>{if(typeof U.packetsReceived=="number"){if(!_&&U.packetsReceived>0&&(_=Date.now()),U.framesDecoded>0)y=Date.now();else if(I<w)return I++,new Promise(q=>setTimeout(()=>q(P()),T));return!0}})),Promise.resolve(D)};return P()})(20,100);return A.then(()=>{_&&this.ctx.slsReporter.reportSubscribeFirstPacket(e===me.Resume,t,i,S,{fprt:_-p,ifsprtc:y?y-p:0,ajsub:e===me.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}),y&&this.ctx.slsReporter.reportSubscribeFirstFrame(e===me.Resume,t,i,S,{fvfrt:y-p,fp2fftc:y-_,ajsub:e===me.Join?1:0,tffrtc:e===me.Join?y-this.ctx.localJoinTime:y-r,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",fvfdtc:y-p}),R&&(this.ctx.slsReporter.reportConnectionLatencyEvent(Xe.FIRST_REMOTE,tt.DECODED,t,M.Audio,R),this.ctx.slsReporter.reportSubscribeFirstPacket(e===me.Resume,t,i,M.Audio,{fprt:R-p,ifsprtc:R-p,ajsub:e===me.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}))}),f.statsCheckPromise=A,f})}subscribeDelete(s){return E(this,null,function*(){const{remoteUser:e,options:t}=s,i=e.streamUrl.split("?")[0];if(!this.rtsClientMap.get(i))return null;const r=!!t.audio,n=!(!t.video&&!t.screen);if(this.destroyClientEntry(i),r&&n)return null;const c={};r||(c.audio=!0),n||(c.video=!0);const o=this.getOrCreateClientEntry(i),l=this.ctx.getSubConfig(e.streamInfo,c);this.ctx.handleHTTPConfig(l),l.disableHeartbeat=!0;try{const d=this.ctx.suffixHttpUrl(e.streamUrl,l),u=yield o.client.subscribe(d,l);o.connected=!0,o.traceId=u.traceId,C.info(`[${Ct}]`,"multiPCSubscribeDelete: re-subscribed remaining tracks",c)}catch(d){C.error(`[${Ct}]`,"multiPCSubscribeDelete: re-subscribe failed",d),this.destroyClientEntry(i)}return null})}getPublishVideoStats(s,e){return E(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishVideoStats(s,e)}return{}})}getPublishAudioStats(s,e){return E(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishAudioStats(s,e)}return{}})}getSubscribeVideoStats(s,e){return E(this,null,function*(){const t=s.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeVideoStats(s,e):{}})}getSubscribeAudioStats(s,e){return E(this,null,function*(){const t=s.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeAudioStats(s,e):{}})}getNetworkQuality(){return E(this,null,function*(){var i,r;let s=0,e=0,t=!1;for(const n of this.rtsClientMap.values())if(n.connected)try{const c=(r=(i=n.client.commonController)==null?void 0:i.peerCore)==null?void 0:r.pc;if(!c||c.connectionState==="disconnected"||c.connectionState==="failed"||c.connectionState==="closed")continue;t=!0;const o=c.getReceivers();let l=0,d=0,u=0;for(const h of o)(yield h.getStats()).forEach(f=>{f.type==="candidate-pair"&&typeof f.currentRoundTripTime=="number"&&(l=Math.round(1e3*f.currentRoundTripTime)),f.type!=="inbound-rtp"||f.mediaType!=="audio"&&f.mediaType!=="video"||(d+=f.packetsLost||0,u+=f.packetsReceived||0)});const p=u>0?Math.round(d/(d+u)*100):0;l>s&&(s=l),p>e&&(e=p)}catch(c){}return t?{rtt:s,loss:e,quality:er(e,s)}:{rtt:0,loss:0,quality:Qe.AliRtcNetworkDisconnected}})}getPCStats(){return E(this,null,function*(){var s,e;if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return(e=(s=t.client.commonController.peerCore)==null?void 0:s.pc)==null?void 0:e.getStats()}})}getStreamByMsid(s){if(s!=null&&s.url){const e=s.url.split("?")[0],t=this.rtsClientMap.get(e);if(t)return t.client.commonController.streamManager.getStreamByMsid(s)}}updateAuth(s){const e=s.split("?")[0],t=this.rtsClientMap.get(e);t&&t.client.updateAuth(s)}sendSEI(s,e,t,i){return E(this,null,function*(){if(this.pubBaseUrl){const r=this.rtsClientMap.get(this.pubBaseUrl);if(r)return r.client.sendSEI({url:s,vMsid:M.VideoLarge,data:e,repeatCount:t,payloadType:i})}})}waitPublishSender(s,e=!1,t){return E(this,null,function*(){var r;const i=this.pubBaseUrl?(r=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:r.client:void 0;if(i)return Promise.race([Nt(1e3),((n,c)=>{let o=0;const l=()=>(e?i.getPublishAudioStats(s,t):i.getPublishVideoStats(s,t)).then(d=>!(d.bytesSent>0)&&o<n?(o++,new Promise(u=>setTimeout(()=>u(l()),c))):Promise.resolve());return l()})(5,100)]).catch(()=>{})})}clear(){for(const[s]of this.rtsClientMap)this.destroyClientEntry(s);this.rtsClientMap.clear(),this.pubBaseUrl=void 0}}var vc=Object.defineProperty,yc=Object.getOwnPropertyDescriptor,$e=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?yc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&vc(s,e,r),r},Ri=(a=>(a.PUBLISH="publish",a.SUBSCRIBE="subscribe",a))(Ri||{});const Fi=([a])=>{const{remoteUser:s,options:e}=a;return[`user(${s.userId})`,e]};class Rc{constructor(s,e=5){m(this,"queue");m(this,"queue2");m(this,"batchFunc");m(this,"maxCount");m(this,"disabled",!1);m(this,"pendingFlush",Promise.resolve());this.queue=[],this.queue2=[],this.batchFunc=s,this.maxCount=e}add(s){return this.disabled?this.batchFunc([s]).then(e=>e.find(t=>t.url===s.url)||e[0]):(this.queue.length>=this.maxCount||this.queue2.length>=this.maxCount?this.flush():(e=>{if(typeof e!="function")throw new TypeError("Callback must be a function");typeof Promise!="undefined"?Promise.resolve().then(e).catch(t=>console.error(t)):setTimeout(e,0)})(this.flush.bind(this)),new Promise((e,t)=>{this.queue.find(i=>i.config.url===s.url)?this.queue2.push({config:s,resolve:e,reject:t}):this.queue.push({config:s,resolve:e,reject:t})}))}waitForPending(){return E(this,null,function*(){(this.queue.length>0||this.queue2.length>0)&&this.flush(),yield this.pendingFlush})}fallbackToSingleRequest(s){s.forEach(e=>{this.batchFunc([e.config]).then(t=>{const i=t.find(r=>r.url===e.config.url)||t[0];e.resolve(i)}).catch(t=>{e.reject(t)})})}handleError(s,e){var t;(t=s==null?void 0:s.message)!=null&&t.includes("Message too large")?(this.disabled=!0,C.warn("[Batcher]","Message too large, batcher disabled, fallback to single request"),this.fallbackToSingleRequest(e)):e.forEach(i=>i.reject(s))}flush(){if(this.queue.length===0&&this.queue2.length===0)return;const s=this.queue.map(i=>i),e=this.queue2.map(i=>i);this.queue=[],this.queue2=[];const t=[];[s,e].forEach(i=>{if(i.length>0)try{const r=this.batchFunc(i.map(n=>n.config)).then(n=>{n.forEach(c=>{const o=i.find(l=>l.config.url===c.url);o&&o.resolve(c)})}).catch(n=>{this.handleError(n,i)});t.push(r)}catch(r){this.handleError(r,i)}}),t.length>0&&(this.pendingFlush=Promise.all(t).then(()=>{}))}}const Fe=(re=class extends ne{constructor(e,t,i){var r,n,c,o;super();m(this,"rts");m(this,"encodedInsertableStreams",!0);m(this,"audioRedEnabled",!1);m(this,"localStreamManager");m(this,"slsReporter");m(this,"_rtsPeerConnectionType","publish");m(this,"connecting",!1);m(this,"connected",!1);m(this,"rtsDisconnected",!1);m(this,"_pcTraceId","");m(this,"_localJoinTime",0);m(this,"connectionResolve");m(this,"connectingPromise");m(this,"dcResolve");m(this,"dcReject");m(this,"dcConnectingPromise");m(this,"_dcReady",!1);m(this,"_prevDownlinkStat");m(this,"_publishingTracks",[]);m(this,"parameter",{});m(this,"preferredPubL1Ip");m(this,"preferredSubL1Ip");m(this,"httpPublishUrlMap",{});m(this,"httpSubscribeUrlMap",{});m(this,"traceIdMap",{});m(this,"subUrlMap",{});m(this,"subscribeAddBatcher");m(this,"multiPC");if(this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher=new Rc(this.subscribeAddWithRetry.bind(this),((n=(r=this.parameter)==null?void 0:r.subscribe)==null?void 0:n.maxBatchCount)||3),((o=(c=this.parameter)==null?void 0:c.subscribe)==null?void 0:o.disableBatcher)===!0&&(this.subscribeAddBatcher.disabled=!0),(()=>{const l=(fn.browserName||"").toLowerCase(),d=parseInt(fn.browserVersion||"0",10);return l==="firefox"&&d>=148})()){C.info(`[${re.logName}]`,"Multi-PC mode enabled (Firefox 148+)"),this.subscribeAddBatcher.disabled=!0;const l=this,d={emit:(u,...p)=>l.emit(u,...p),suffixHttpUrl:l.suffixHttpUrl.bind(l),handleHTTPConfig:l.handleHTTPConfig.bind(l),getSubConfig:l.getSubConfig.bind(l),getPubMsid:l.getPubMsid.bind(l),reportSubscribeLatency:l.reportSubscribeLatency.bind(l),localStreamManager:l.localStreamManager,slsReporter:l.slsReporter,traceIdMap:l.traceIdMap,subUrlMap:l.subUrlMap,get pcTraceId(){return l._pcTraceId},set pcTraceId(u){l._pcTraceId=u},get localJoinTime(){return l._localJoinTime},get publishingTracks(){return l._publishingTracks},set publishingTracks(u){l._publishingTracks=u},get rtsPeerConnectionType(){return l._rtsPeerConnectionType},set rtsPeerConnectionType(u){l._rtsPeerConnectionType=u}};this.multiPC=new bc(d)}}subscribeAddWithRetry(e){return ts(t=>E(this,null,function*(){return this._dcReady||(yield this.dcConnectingPromise),t>0&&C.event(`[${re.logName}]`,`subscribeAdd retry times: ${t}`),this.isConnected?this.rts.subscribeAdd(e):Promise.reject()}),10,100,t=>{var i,r,n,c;return(t==null?void 0:t.errorCode)===15006||(t==null?void 0:t.errorCode)===15004&&((c=(n=(r=(i=t.extraInfo)==null?void 0:i.parsedData)==null?void 0:r.streams)==null?void 0:n[0])==null?void 0:c.res_code)===404})}createRtsInstance(){var e,t;return J.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!1,signalDatachannelInitOptions:(t=(e=this.parameter)==null?void 0:e.net)!=null&&t.datachannelInitOptions?this.parameter.net.datachannelInitOptions:void 0})}addRTSListener(){this.rts.on("connectStatusChange",t=>{var i,r,n,c;if(C.event(`[${re.logName}]`,"rts connectStatusChange to:",t.status),t.status===J.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(t.status===J.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const o=(c=(n=(r=(i=this.rts.commonController)==null?void 0:i.peerCore)==null?void 0:r.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:c.readyState;C.event(`[${re.logName}]`,"dcReadyState:",o),o==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",t=>{var i,r,n;C.debug(`[${re.logName}]`,"reconnect",t),this.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(r=t.extraInfo)==null?void 0:r.msids)==null?void 0:n.map(c=>c.name))}),this.rts.on("reconnectFinish",t=>{var i;C.debug(`[${re.logName}]`,"reconnectFinish",t),this.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(i=t==null?void 0:t.msids)==null?void 0:i.map(r=>r.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(r){C.error(`[${re.logName}]`,"emit connected error:",r)}this.logCandidateProtocol("reconnectFinish")}),this.rts.on("datachannelStatusChange",t=>{C.event(`[${re.logName}]`,"rts datachannelStatusChange to:",t.status),t.status===J.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?(this._dcReady=!0,this.dcResolve&&this.dcResolve(!0)):t.status===J.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this._dcReady=!1,this.dcReject&&this.dcReject(new Error("signal datachannel closed")),this.dcConnectingPromise=new Promise((i,r)=>{this.dcResolve=i,this.dcReject=r}))}),this.rts.on("receivedSEI",t=>{var i;if(this.emit("seimessage",t.url,t.sei.payloadType,t.sei.data),t.sei.payloadType===99)try{const r=JSON.parse(new TextDecoder().decode(t.sei.data));this.slsReporter.reportLoopAudioDelay(((i=this.publishingTracks.find(n=>n.type==="audio"))==null?void 0:i.ssrc)||"",r)}catch(r){}}),this.rts.on("onError",t=>{C.event(`[${re.logName}]`,"rts onError event:",t)}),this.rts.on("reconnect",t=>{C.event(`[${re.logName}]`,"rts reconnect event:",t)}),this.rts.on("traceId",({url:t,traceId:i})=>{t&&i&&this.traceIdMap[t]!==i&&(this.traceIdMap[t]=i,this.emit("traceIdUpdated",t,i))});const e={sophon_audio:"audio",sophon_video_camera_large:"vlarge",sophon_video_camera_small:"vsmall",sophon_video_screen_share:"screen",sophon_data:"data"};this.rts.on("signalSent",t=>{const i=t.streams||[],r=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${r.join(", ")}`;C.event(`[${re.logName}]`,"rts signalSent event:",n,t)}),this.rts.on("signalReceived",t=>{const i=t.streams||[],r=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),l+=` ${c.res_code||""}`,c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${r.join(", ")}`;C.event(`[${re.logName}]`,"rts signalReceived event:",n,t)}),this.rts.on("hebtSent",t=>{var i,r,n;if((n=(r=(i=this.parameter)==null?void 0:i.net)==null?void 0:r.heartbeat)!=null&&n.enableLog){const c=Object.keys(this.subUrlMap).find(o=>{var l,d;return this.subUrlMap[o]===((d=(l=t.streams)==null?void 0:l[0])==null?void 0:d.url.split("?")[0])})||(t.streams?"pub":"empty");C.event(`[${re.logName}]`,"rts hebtSent event:",c,t)}}),this.rts.on("hebtReceived",t=>{var i,r,n,c,o,l,d;if((n=(r=(i=this.parameter)==null?void 0:i.net)==null?void 0:r.heartbeat)!=null&&n.enableLog){let u=`${Object.keys(this.subUrlMap).find(p=>{var h,f;return this.subUrlMap[p]===((f=(h=t.streams)==null?void 0:h[0])==null?void 0:f.url.split("?")[0])})||(t.streams?"pub":"empty")} ${((o=(c=t.streams)==null?void 0:c[0])==null?void 0:o.res_code)||""}`;(d=(l=t.streams)==null?void 0:l[0])!=null&&d.msid&&(u+=` ${t.streams[0].msid.map(p=>e[p.name]||p.name).join("+")}`),C.event(`[${re.logName}]`,"rts hebtReceived event:",u,t)}})}updateAuth(e){if(this.multiPC)return this.multiPC.updateAuth(e);this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setReceiverPreferredVideoCodecH265(){var r;let e=(r=RTCRtpReceiver.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var r;let e=(r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,r;return e===gt.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===gt.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===gt.AV1&&((r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(C.info(`[${re.logName}]`,"changeVideoCodec to:",e),gt.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):C.warn(`[${re.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const r=i.findIndex(c=>c.mimeType==="audio/red"),n=i.findIndex(c=>c.mimeType==="audio/opus");if(r>-1&&n>-1&&r>n){const c=i[n];i[n]=i[r],i[r]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(i){}this.audioRedEnabled=e}}clear(){this.multiPC&&this.multiPC.clear(),this.setConnected(!1),this.rtsDisconnected=!1,this._dcReady=!1,this._publishingTracks=[],this._prevDownlinkStat=void 0;try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe()}catch(e){}this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher.batchFunc=this.subscribeAddWithRetry.bind(this)}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this._dcReady=!1,this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.multiPC?this.multiPC.isConnecting:this.connecting}get isConnected(){return this.multiPC?this.multiPC.isConnected:this.connected}suffixHttpUrl(e,t){const i=!t;let r=Zi(e,i?this.preferredPubL1Ip:this.preferredSubL1Ip);const n={ip_migration:"on",exception_detection:"on"},c=new URL(r),o=c.searchParams;Object.keys(n).forEach(p=>{o.has(p)||o.set(p,n[p])});const l=c.toString(),d=e.split("?")[0];i?this.httpPublishUrlMap[d]=l:this.httpSubscribeUrlMap[d]=l;let u="";return t&&(t.vMsid?t.aMsid||(u="@subaudio=no"):u="@subvideo=no"),l+u}getSuffixedUrl(e,t){const i=e.split("?")[0];return t?this.httpPublishUrlMap[i]||e:this.httpSubscribeUrlMap[i]||e}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:r}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[i!=null?i:M.Audio]),e.hasScreen&&(n.vMsid=[M.Screen]),e.hasVideo&&(n.vMsid=[r!=null?r:t!=null&&t.isScreen?M.Screen:M.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:r,codec:n,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${r}`,codec:n!=null?n:"",trackId:o})))}httpPublish(r){return E(this,arguments,function*(e,t=!1,i=Tt.MANUAL){let n;const c=Date.now(),o=e.url,l=e.callId;this.startConnect();const{publishStream:d,videoSmallStream:u,screenStream:p,vMsid:h}=yield this.localStreamManager.createHTTPPublishStream();if(!d)return C.warn(`[${re.logName}]`,"publishStream is null"),{traceId:"",l1ip:n};const f=this.getPubMsid(d,{vMsid:h});f.answerSdpHook=_=>{const y=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(_);return y!=null&&y[0]&&(n=y[0]),_},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let g=!d.hasVideo,S=h,b="";const v=Date.now();try{b=yield this.publishWithPreferredL1Fallback(o,d,f)}catch(_){this.setConnected(!1);const y=2e3-(Date.now()-v);throw y<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},y),this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!h||h===M.VideoLarge),d.hasVideo&&h===M.VideoSmall,d.hasVideo&&h===M.Screen,d.hasAudio,(_==null?void 0:_.errorCode)||-1,this.pcTraceId,"",v,v),V.fromRtsError(_)}b&&(this._pcTraceId=b),C.event(`[${re.logName}]`,"rts publish success",b);const R=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!h||h===M.VideoLarge),d.hasVideo&&h===M.VideoSmall,d.hasVideo&&h===M.Screen,d.hasAudio,0,this.pcTraceId,e.traceId,v,R)},6e3),this.slsReporter.reportConnectionLatencyEvent(Xe.HANDLE_PUB_TASK,tt.START,l,b,c),this.slsReporter.reportConnectionLatencyEvent(Xe.HANDLE_PUB_TASK,tt.END,l,b,Date.now());try{const _=Date.now();return this._pcTraceId=b,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),u&&(yield this.publishAdd(e,u,{vMsid:M.VideoSmall},t),g=!1,S=M.VideoSmall),p&&(yield this.publishAdd(e,p,{vMsid:M.Screen},t),g=!1,S=M.Screen),yield this.waitPublishSender(o,g,S),this.slsReporter.reportPublishFirstPacket(t,l,v,_,this._localJoinTime,g?M.Audio:f.vMsid,b||"",b||"",i),{traceId:b,l1ip:n}}catch(_){throw this.setConnected(!1),V.fromError(_)}})}waitPublishSender(e,t=!1,i){return E(this,null,function*(){return this.multiPC?this.multiPC.waitPublishSender(e,t,i):Promise.race([Nt(1e3),((r,n)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(l=>!(l.bytesSent>0)&&c<r?(c++,new Promise(d=>setTimeout(()=>d(o()),n))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return E(this,null,function*(){return this.multiPC?this.multiPC.getPublishVideoStats(e,t):yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return E(this,null,function*(){return this.multiPC?this.multiPC.getPublishAudioStats(e,t):yield this.rts.getPublishAudioStats(e,t)})}publishAdd(o,l,d){return E(this,arguments,function*(e,t,i,r=!1,n=!1,c=Tt.MANUAL){var g,S,b,v;if(this.multiPC)return C.warn(`[${re.logName}]`,"publishAdd not supported in multi-PC mode"),"";const u=e.url,p=e.callId;this._dcReady||(yield this.dcConnectingPromise);const h=Date.now(),f=this.getPubMsid(t,i);try{const R=yield ts(_=>E(this,null,function*(){return _>0&&C.event(`[${re.logName}]`,`publishAdd retry times: ${_}`),this.isConnected?(this._dcReady||(yield this.dcConnectingPromise),this.rts.publishAdd([X({url:u,stream:t,updateSourceStream:!1},f)])):Promise.reject(new V(B.ERR_INNER,"rts not connected"))}),10,0,_=>(_==null?void 0:_.errorCode)===15006);if(R){const _=Date.now(),[y]=R,A=Date.now();return setTimeout(()=>{var w,T,I,P;this.slsReporter.reportPublish(!1,u,p,((w=f.vMsid)==null?void 0:w[0])===M.VideoLarge,((T=f.vMsid)==null?void 0:T[0])===M.VideoSmall,((I=f.vMsid)==null?void 0:I[0])===M.Screen,((P=f.aMsid)==null?void 0:P[0])===M.Audio,0,this.pcTraceId,y.traceId||"",h,A)},6e3),y.traceId&&(this._pcTraceId=y.traceId),this.updatePublishingTracks(y.trackInfoList),n&&(yield this.waitPublishSender(u,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(r,p,h,_,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,y.traceId||"",c),y.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,u,p,((g=f.vMsid)==null?void 0:g[0])===M.VideoLarge,((S=f.vMsid)==null?void 0:S[0])===M.VideoSmall,((b=f.vMsid)==null?void 0:b[0])===M.Screen,((v=f.aMsid)==null?void 0:v[0])===M.Audio,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",h),R!=null&&R.errorCode?V.fromRtsError(R):V.fromError(R)}return""})}publishDelete(e,t){return E(this,null,function*(){var l,d,u,p,h,f,g,S;if(this.multiPC)return C.warn(`[${re.logName}]`,"publishDelete not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const i=(d=(l=this.publishingTracks)==null?void 0:l.find(({msid:b})=>b===M.Audio))==null?void 0:d.msid,r=(p=(u=this.publishingTracks)==null?void 0:u.find(({msid:b})=>b===M.VideoLarge))==null?void 0:p.msid,n=(f=(h=this.publishingTracks)==null?void 0:h.find(({msid:b})=>b===M.Screen))==null?void 0:f.msid,c=[];t.screen&&n?c.push(n):t.video&&c.push(t.vMsid||r);const o=[];t.audio&&i&&o.push(i),C.event(re.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[b]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return C.event(re.logName,"publishDelete",{result:b}),b&&this.updatePublishingTracks(b.trackInfoList),((S=(g=b==null?void 0:b.trackInfoList)==null?void 0:g[0])==null?void 0:S.trackId)||""}catch(b){throw V.fromRtsError(b)}})}publishReplace(e,t,i){return E(this,null,function*(){var c,o;if(this.multiPC)return C.warn(`[${re.logName}]`,"publishReplace not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const{vMsid:r,aMsid:n}=i!=null?i:{};try{const l=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:r,aMsid:n}]),[d]=l;return this.updatePublishingTracks(d.trackInfoList),((o=(c=d==null?void 0:d.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(l){throw V.fromRtsError(l)}})}publishStop(e){return E(this,null,function*(){return this.multiPC?(yield this.multiPC.publishStop(e),""):(yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],"")})}publishAddDataChannel(e){return E(this,null,function*(){if(this.multiPC)return C.warn(`[${re.logName}]`,"publishAddDataChannel not supported in multi-PC mode"),null;this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.publishAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!0),label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.datachannel.send(r)}return i})}publishStopDataChannel(e,t){return E(this,null,function*(){return this.multiPC?void C.warn(`[${re.logName}]`,"publishStopDataChannel not supported in multi-PC mode"):yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return E(this,null,function*(){if(this.multiPC)return yield this.multiPC.unpublish(),void(this._publishingTracks=[]);yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getMultiPCNetworkQuality(){return E(this,null,function*(){return this.multiPC?this.multiPC.getNetworkQuality():{rtt:0,loss:0,quality:Qe.AliRtcNetworkDisconnected}})}getSubscribeNetworkQuality(){return E(this,null,function*(){var h;if(this.multiPC)return this.getMultiPCNetworkQuality();const e=(h=this.rts.commonController.peerCore)==null?void 0:h.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:Qe.AliRtcNetworkDisconnected};let t=0,i=0,r=0;const n=e.getReceivers();for(const f of n)(yield f.getStats()).forEach(g=>{g.type==="candidate-pair"&&typeof g.currentRoundTripTime=="number"&&(t=Math.round(1e3*g.currentRoundTripTime)),g.type!=="inbound-rtp"||g.mediaType!=="audio"&&g.mediaType!=="video"||(i+=g.packetsLost||0,r+=g.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:r},{rtt:t,loss:0,quality:Qe.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=r-o;let u=0;l>0&&d>=0&&(u=Math.round(l/(l+d)*100));const p=er(u,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:r},{rtt:t,loss:u,quality:p}})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const r={};return i.audio&&(r.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||M.Audio]),i.video?i.vMsid?r.vMsid=[i.vMsid]:r.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||M.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||M.VideoSmall]:[M.VideoLarge]:i.screen&&(r.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||M.Screen]),r}handleHTTPConfig(e){var i,r,n,c,o,l,d,u,p,h,f,g;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(r=(i=this.parameter)==null?void 0:i.net)!=null&&r.useTCP&&(e.tcpOnly=!0),(c=(n=this.parameter)==null?void 0:n.net)!=null&&c.cumuDelay&&(e.cumuDelay=!0),(l=(o=this.parameter)==null?void 0:o.net)!=null&&l.disableHeartbeat&&(e.disableHeartbeat=!0),(u=(d=this.parameter)==null?void 0:d.net)!=null&&u.heartbeat&&(e.heartbeat=this.parameter.net.heartbeat),(h=(p=this.parameter)==null?void 0:p.net)==null?void 0:h.mediaTimeout){const S=(g=(f=this.parameter)==null?void 0:f.net)==null?void 0:g.mediaTimeout;S>1e3&&S<1e5&&(e.mediaTimeout=S)}e.offerSdpHook=Kn;let t=0;e.beforeRetry=S=>E(this,null,function*(){if(t++,C.info(`[${re.logName}]`,`before retry, retryCount: ${t}`),t>=2&&S.url.includes("ali_prefer_media_server"))try{const b=new URL(S.url);b.searchParams.delete("ali_prefer_media_server"),S.url=b.toString(),C.info(`[${re.logName}]`,`removed ali_prefer_media_server, fallback url: ${S.url}`)}catch(b){C.error(`[${re.logName}]`,"failed to parse url for removing ali_prefer_media_server",S.url,b)}return S}),e.retryTimes=17,e.retryInterval=5e3,C.info(`[${re.logName}]`,"http config",e)}httpSubscribe(e){return E(this,null,function*(){const{remoteUser:t,options:i}=e,r=t.streamUrl,n=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(n),this._rtsPeerConnectionType="subscribe";try{this.startConnect();const c=yield this.subscribeWithPreferredL1Fallback(r,n);return this._pcTraceId=c.traceId,this.setConnected(!0),{traceId:c.traceId,stream:c}}catch(c){throw this.setConnected(!1),this.emit("disconnected"),V.fromRtsError(c)}})}subscribeWithPreferredL1Fallback(e,t){return E(this,null,function*(){if(this.preferredSubL1Ip){const r=this.suffixHttpUrl(e,t),n=new Promise((c,o)=>{setTimeout(()=>o(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const c=yield Promise.race([this.rts.subscribe(r,t),n]);return this.logCandidateProtocol("subscribe (preferred L1)"),c}catch(c){if(c.message==="PREFERRED_L1_TIMEOUT"){C.warn(`[${re.logName}]`,"Preferred L1 subscribe timeout, clearing preferredSubL1Ip and falling back to DNS"),this.preferredSubL1Ip=void 0;const o=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe (fallback)"),o}throw c}}const i=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe"),i})}publishWithPreferredL1Fallback(e,t,i){return E(this,null,function*(){if(this.preferredPubL1Ip){const n=this.suffixHttpUrl(e),c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rts.publish(n,t,i),c]);return this.logCandidateProtocol("publish (preferred L1)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){C.warn(`[${re.logName}]`,"Preferred L1 publish timeout, clearing preferredPubL1Ip and falling back to DNS"),this.preferredPubL1Ip=void 0;const l=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish (fallback)"),l}throw o}}const r=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish"),r})}subscribeAdd(e){return E(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,r=vt(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return this.subscribeAddBatcher.disabled?(yield this.subscribeAddWithRetry([r]))[0]:yield this.subscribeAddBatcher.add(r)}catch(d){if((d==null?void 0:d.errorCode)===15011)return C.info(`[${re.logName}]`,"subscribeAdd ignored",d==null?void 0:d.message),null;if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===508)return this.emit("subscribeexceeds"),null;throw V.fromRtsError(d)}})}subscribeDelete(e){return E(this,null,function*(){var n,c,o,l;if(this.multiPC)return this.multiPC.subscribeDelete(e);yield this.subscribeAddBatcher.waitForPending();const{remoteUser:t,options:i}=e,r=vt(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return C.event(`[${re.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:r.url,subAudio:r.subAudio,subVideo:r.subVideo,aMsid:r.aMsid,vMsid:r.vMsid})),(yield this.rts.subscribeDeleteTracks([r]))[0]}catch(d){if((d==null?void 0:d.errorCode)===15011)return C.info(`[${re.logName}]`,"subscribeDelete ignored",d==null?void 0:d.message),null;if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===404)return null;throw V.fromRtsError(d)}})}updateSubscribeBatcher(e){e.disableBatcher!==void 0&&(this.subscribeAddBatcher.disabled=e.disableBatcher),e.maxBatchCount!==void 0&&(this.subscribeAddBatcher.maxCount=e.maxBatchCount)}subscribeAddDataChannel(e){return E(this,null,function*(){if(this.multiPC)return C.warn(`[${re.logName}]`,"subscribeAddDataChannel not supported in multi-PC mode"),null;yield this.subscribeAddBatcher.waitForPending(),this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!1),label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.send(r)}return i})}subscribeDeleteDatachannel(e,t){return E(this,null,function*(){if(this.multiPC)return void C.warn(`[${re.logName}]`,"subscribeDeleteDatachannel not supported in multi-PC mode");let i;yield this.subscribeAddBatcher.waitForPending();try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:M.Data,datachannel:t})}catch(r){}return i})}publish(r){return E(this,arguments,function*(e,t=!1,i=Tt.MANUAL){if(this.multiPC)return this.multiPC.publish(e,t,i);const n=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){this._dcReady||(yield this.dcConnectingPromise);let l,d=!1;const{audio:u,video:p,videoSmall:h,screen:f}=this.localStreamManager.publishStreams;u&&(o=yield this.publishAdd(e,u,{aMsid:M.Audio},t),d=!0,l=M.Audio,yield Nt(100)),p&&(o=yield this.publishAdd(e,p,{vMsid:M.VideoLarge},t),d=!1,l=M.VideoLarge,yield Nt(100)),h&&(o=yield this.publishAdd(e,h,{vMsid:M.VideoSmall},t),d=!1,l=M.VideoSmall,yield Nt(100)),f&&(o=yield this.publishAdd(e,f,{isScreen:!0,vMsid:M.Screen},t),d=!1,l=M.Screen),l&&(yield this.waitPublishSender(n,d,l))}else{const l=yield this.httpPublish(e,t,i);o=l.traceId,c=l.l1ip}return{traceId:o,l1ip:c}})}reportSubscribeLatency(e,t,i,r){const n=[];e.audio&&n.push(e.aMsid||M.Audio),e.video?n.push(e.vMsid||M.VideoLarge):e.screen&&n.push(M.Screen),n.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(Xe.HANDLE_SUB_TASK,tt.START,t,c,i,0,r),this.slsReporter.reportConnectionLatencyEvent(Xe.HANDLE_SUB_TASK,tt.END,t,c,Date.now(),0,r)})}subscribe(e,t,i,r,n){return E(this,null,function*(){if(this.multiPC)return this.multiPC.subscribe(e,t,i,r,n);let c=!1;const{options:o,remoteUser:l}=e;if(o.video&&o.screen)throw new V(B.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise),this.subUrlMap[l.userId]=l.streamUrl.split("?")[0];let u=Date.now();if(this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),!d)return null;this.reportSubscribeLatency(o,i,u,c);const p=Date.now();let h=M.VideoLarge,f=o.video||o.screen,g=o.audio;o.video&&o.vMsid?h=o.vMsid:o.screen&&(h=M.Screen);let S=0,b=0,v=0;const R=((_,y)=>{let A=0;const w=()=>{let T;return g&&!S&&(T=this.rts.getSubscribeAudioStats(l.streamUrl).then(I=>{if(I.packetsReceived>0)S=Date.now(),C.debug(`[${re.logName}]`,l.userId,"Stats 音频首包");else if(!f)return A<_&&(A++,new Promise(P=>setTimeout(()=>P(w()),y)));return!0})),f&&!v&&(T=this.rts.getSubscribeVideoStats(l.streamUrl,h).then(I=>{if(typeof I.packetsReceived=="number")return!b&&I.packetsReceived>0&&(b=Date.now(),C.debug(`[${re.logName}]`,l.userId,"Stats 视频首包")),I.framesDecoded>0?(v=Date.now(),C.debug(`[${re.logName}]`,l.userId,"Stats 视频首帧数据"),!0):A<_?(A++,new Promise(P=>setTimeout(()=>P(w()),y))):(C.event(`[${re.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)})),Promise.resolve(T)};return w()})(20,100);return R.then(()=>{b&&this.slsReporter.reportSubscribeFirstPacket(t===me.Resume,i,r,h,{fprt:b-u,ifsprtc:v?v-u:0,ajsub:t===me.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-u}),v&&this.slsReporter.reportSubscribeFirstFrame(t===me.Resume,i,r,h,{fvfrt:v-u,fp2fftc:v-b,ajsub:t===me.Join?1:0,tffrtc:t===me.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-u}),S&&(this.slsReporter.reportConnectionLatencyEvent(Xe.FIRST_REMOTE,tt.DECODED,i,M.Audio,S),this.slsReporter.reportSubscribeFirstPacket(t===me.Resume,i,r,M.Audio,{fprt:S-u,ifsprtc:S-u,ajsub:t===me.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-u}))}),d&&(d.isHTTP=c,d.statsCheckPromise=R),d})}getSubscribeVideoStats(e,t){return E(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeVideoStats(e,t):yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return E(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeAudioStats(e,t):yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){if(this.multiPC){const t=this.multiPC.getStreamByMsid(e);if(t)return t}return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){var t;return this.multiPC?(C.warn(`[${re.logName}]`,"getDatachannelByMsid not supported in multi-PC mode"),null):(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(e)}getPCStats(){return E(this,null,function*(){var e,t;return this.multiPC?this.multiPC.getPCStats():(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}logCandidateProtocol(e){return E(this,null,function*(){var t,i;try{const r=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.pc;if(!r)return void C.debug(`[${re.logName}]`,`${e} - PC not available`);const n=yield r.getStats();let c,o,l,d;n.forEach(u=>{u.type==="candidate-pair"&&u.state==="succeeded"&&u.nominated&&(c=u.localCandidateId,o=u.remoteCandidateId)}),c||o||n.forEach(u=>{u.type!=="candidate-pair"||u.state!=="succeeded"&&u.state!=="in-progress"||c||(c=u.localCandidateId,o=u.remoteCandidateId)}),n.forEach(u=>{u.type==="local-candidate"&&u.id===c&&(l=u.protocol),u.type==="remote-candidate"&&u.id===o&&(d=u.protocol)}),C.event(`[${re.logName}]`,`${e} - Candidate Protocol: local=${l||"unknown"}, remote=${d||"unknown"}`)}catch(r){C.warn(`[${re.logName}]`,`${e} - Failed to get candidate protocol:`,r)}})}sendSEI(e,t,i,r){return E(this,null,function*(){return this.multiPC?this.multiPC.sendSEI(e,t,i,r):this.rts.sendSEI({url:e,vMsid:M.VideoLarge,data:t,repeatCount:i,payloadType:r})})}},m(re,"logName","RtsManager"),re);$e([k(H)],Fe.prototype,"startConnect",1),$e([k()],Fe.prototype,"updatePublishingTracks",1),$e([k(H,H)],Fe.prototype,"httpPublish",1),$e([k(H,H)],Fe.prototype,"waitPublishSender",1),$e([k(([a,s,e])=>[a,JSON.stringify(e)],H)],Fe.prototype,"publishAdd",1),$e([k(H,H)],Fe.prototype,"publishDelete",1),$e([k(([a,s,e])=>[a,JSON.stringify(e)])],Fe.prototype,"publishReplace",1),$e([k(H)],Fe.prototype,"publishStop",1),$e([k(H)],Fe.prototype,"publishAddDataChannel",1),$e([k(H)],Fe.prototype,"publishStopDataChannel",1),$e([k()],Fe.prototype,"unpublish",1),$e([k(Fi,({traceId:a})=>a)],Fe.prototype,"httpSubscribe",1),$e([k(Fi,({traceId:a})=>a)],Fe.prototype,"subscribeAdd",1),$e([k(Fi)],Fe.prototype,"subscribeDelete",1),$e([k(H)],Fe.prototype,"subscribeAddDataChannel",1),$e([k(H)],Fe.prototype,"subscribeDeleteDatachannel",1),$e([k(H)],Fe.prototype,"publish",1),$e([k(Fi)],Fe.prototype,"subscribe",1),$e([k()],Fe.prototype,"sendSEI",1);let Ac=Fe;class Lr{constructor(s=Pr){m(this,"defaultProfile");m(this,"profile");m(this,"profileMap",new Map);m(this,"audioProfile");m(this,"contentHint");this.defaultProfile=X({},s)}updateProfile(s,e){this.profileMap.set(s,X(X(X({},this.defaultProfile),this.profileMap.get(s)||{}),e||{})),this.profile=s}get videoProfile(){return this.profile}updateAudioProfile(s){this.audioProfile=s}setContentHint(s,e){e&&(this.contentHint=e),this.contentHint&&s&&(s.contentHint=this.contentHint)}setVideoProfile(s,e,t=!1){return E(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&s&&s.readyState==="live"&&s.applyConstraints)try{yield s.applyConstraints(i)}catch(r){}if(e){const r=X({},i);i.maxSendFrameRate&&(r.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,r),yield e.setVideoProfile(this.profile)}}})}}var Ve=(a=>(a[a.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",a[a.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",a))(Ve||{});class xr extends ne{constructor(e){super();m(this,"type");m(this,"originVideoTrack");m(this,"videoSource");m(this,"_videoMuted",!1);m(this,"originAudioTrack");m(this,"audioSource");m(this,"_audioMuted",!1);m(this,"_targetVideoTrack");m(this,"_targetDualVideoTrack");m(this,"_targetAudioTrack");m(this,"_publishVideoStream");m(this,"_publishDualVideoStream");m(this,"_publishAudioStream");m(this,"_previewStream");m(this,"plugins",[]);m(this,"_profileManager");m(this,"cameraVideoConstraints");m(this,"micAudioConstraints");m(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});m(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return E(this,null,function*(){var c,o,l,d,u,p;const{videoTrack:r,audioTrack:n}=e;r&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Ve.AliRtcSdkStreamTypeScreen?this.stop():(r&&((l=this.originVideoTrack)==null||l.stop()),n&&((d=this.originAudioTrack)==null||d.stop())),r&&(this.originVideoTrack=r,(u=this.originVideoTrack)==null||u.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||mi.Camera,this.updateVideoTrack(r)),n&&(this.originAudioTrack=n,(p=this.originAudioTrack)==null||p.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Pi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return E(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return E(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return E(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return E(this,null,function*(){var t,i,r,n,c,o,l,d,u,p,h,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const g of this.plugins)try{yield g.execute(this,e)}catch(S){console.error(`error in plugin-${g.name}, error: ${S}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield yi(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(r=this.profileManager)==null||r.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield yi(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield yi(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(u=this._publishAudioStream)==null?void 0:u.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield yi(this._targetAudioTrack),this.audioProfile&&(yield this._publishAudioStream.setAudioProfile(this.audioProfile)),this.setAudioMuted(this._audioMuted),this.previewStream?(h=this.previewStream)==null||h.mergeStream(this._publishAudioStream):this._previewStream=yield yi(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return E(this,null,function*(){this._profileManager||(this._profileManager=new Lr(this.type===Ve.AliRtcSdkStreamTypeScreen?un:Pr)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Lr(this.type===Ve.AliRtcSdkStreamTypeScreen?un:Pr)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return E(this,null,function*(){this._profileManager||(this._profileManager=new Lr),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return E(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}cloneAudioProfile(e){return E(this,null,function*(){this.audioProfile&&(yield e.setAudioProfile(this.audioProfile))})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var wc=Object.defineProperty,_c=Object.getOwnPropertyDescriptor,At=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?_c(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&wc(s,e,r),r};const ft=(jt=class extends ne{constructor(e,t){super();m(this,"pluginManager");m(this,"slsReporter");m(this,"publishingCameraVideoStream");m(this,"publishingScreenVideoStream");m(this,"cameraStreamInfo",new xr(Ve.AliRtcSdkStreamTypeCapture));m(this,"screenStreamInfo",new xr(Ve.AliRtcSdkStreamTypeScreen));m(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);m(this,"_audioCaptureDisabled",!1);m(this,"_cameraCaptureDisabled",!1);m(this,"_publishLocalAudioStreamEnabled",!0);m(this,"_publishLocalVideoStreamEnabled",!0);m(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>E(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",Qt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>E(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",Qt.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>E(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",Qt.ScreenTrackEnded)})),this.pluginManager.on("added",i=>E(this,null,function*(){if(C.info(`[${jt.logName}]`,"plugin added",i.name),!i.isSupported("7.2.7"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(r){i.emit("error",V.fromError(r,Bt.AliRtcPluginErrorInitError))}i.streamType===Ve.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Ve.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>E(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>E(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return E(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return E(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield J.AliRTS.getCameraList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return E(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield J.AliRTS.getMicList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return E(this,null,function*(){var u;const{screen:t,mediaStream:i,videoProfile:r,screenProfile:n}=e;let{video:c,audio:o}=e;const l=(p=>{const{audio:h,video:f,screen:g}=p;if(f&&g)throw new V(B.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||h||g)})(e);let d;if(l){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=X({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=X(X({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=X({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=X(X({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const p=Date.now();try{d=yield J.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),C.info(`[${jt.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((u=d==null?void 0:d.audioTrack)==null?void 0:u.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p)}catch(h){throw o&&!i&&this.slsReporter.reportAudio(h,Date.now()-p,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p),h}if(t)yield this.screenStreamInfo.updateSource(d,mi.Screen,Pi.Screen),yield this.setScreenProfile(n||dn),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,mi.Camera,Pi.Microphone),d.hasVideo&&(yield this.setVideoProfile(r||ln),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const h=this.cameraStreamInfo.audioProfile;h&&(yield d.setAudioProfile(h))}}return J.AliRTS.SystenUtil.isIos&&J.AliRTS.SystenUtil.compareVersion("15.1")&&!J.AliRTS.SystenUtil.compareVersion("15.2")&&(yield Nt(1e3)),yield this.updateStreams(),d})}stopLocalStream(e){return E(this,null,function*(){const{screen:t,video:i,audio:r}=e!=null?e:{};let n=!1;i&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),r&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return E(this,null,function*(){var o,l,d,u;let e,t,i,r,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw C.error(`[${jt.logName}]`,"no tracks founded"),new V(B.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,r=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=M.Screen,p.addTrack((u=c.screen)==null?void 0:u.videoTrack),n=!0),e=yield mn(p),n?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e),this.cameraStreamInfo.cloneAudioProfile(e)}catch(p){}return{publishStream:e,videoSmallStream:i,screenStream:r,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return E(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return E(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return E(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=X(X({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=X(X({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},m(jt,"logName","LocalStreamManager"),jt);At([k(([a])=>{const{audio:s,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}=a;return[{audio:s,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}]})],ft.prototype,"createLocalStream",1),At([k(H)],ft.prototype,"stopLocalStream",1),At([k()],ft.prototype,"createHTTPPublishStream",1),At([k()],ft.prototype,"stop",1),At([k(H)],ft.prototype,"setVideoProfile",1),At([k(H)],ft.prototype,"setVideoContentHint",1),At([k(H)],ft.prototype,"setAudioProfile",1),At([k(H)],ft.prototype,"setScreenProfile",1),At([k(H)],ft.prototype,"setScreenContentHint",1),At([k(H)],ft.prototype,"setCameraVideoConstraints",1),At([k(H)],ft.prototype,"setMicAudioConstraints",1);let Ec=ft;var Sn=(a=>(a[a.PRE_PROCESSOR=0]="PRE_PROCESSOR",a[a.POST_PROCESSOR=1]="POST_PROCESSOR",a))(Sn||{}),ci=(a=>(a[a.AUDIO=0]="AUDIO",a[a.VIDEO=1]="VIDEO",a[a.BOTH=2]="BOTH",a))(ci||{});class xt extends ne{constructor(e,t=Ve.AliRtcSdkStreamTypeCapture,i=1){super();m(this,"name");m(this,"options");m(this,"type",0);m(this,"streamType");m(this,"trackType");m(this,"zIndex",1);m(this,"_isEnable",!0);m(this,"shouldCache",!0);m(this,"lastInputAudioTrack");m(this,"lastOutputAudioTrack");m(this,"lastInputVideoTrack");m(this,"lastOutputVideoTrack");m(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return E(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return E(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class Tc extends xt{constructor(){super("AliRtcScreenStandardize",Ve.AliRtcSdkStreamTypeScreen);m(this,"canvas");m(this,"lastWidth");m(this,"lastHeight");m(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,r=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=r,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,i,r)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===mi.Screen){const r=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(r){const{width:n,height:c}=r;t=!n||!c||!(n%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return E(this,null,function*(){var n;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const r=(n=this.canvas)==null?void 0:n.getContext("2d");if(this.canvas&&r){r.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return E(this,null,function*(){var d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const u=e.originVideoTrack.getSettings();if(u){const{width:p,height:h}=u;if(!(!p||!h||!(p%this.options.base===0&&h%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),r=new MediaStream([i]),n=this,c=new TransformStream({transform(u,p){return E(this,null,function*(){const h=yield n.handleFrame(u);yield p.enqueue(h),h==null||h.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=r.getVideoTracks())==null?void 0:d[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class Ic extends xt{constructor(){super("blankAudio",Ve.AliRtcSdkStreamTypeCapture,ci.BOTH);m(this,"hasTrack",!1);m(this,"oscillator",null);m(this,"audioTrack",null);m(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const r=i.stream;return this.audioTrack=r.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return E(this,null,function*(){var r;const i=t.some(n=>n.originVideoTrack||n.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((r=this.oscillator)==null||r.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}class bn{constructor(s){m(this,"name","COMMON");this.name=s||this.name}info(...s){}warn(...s){}print(s,...e){const t=s.toLowerCase();t&&console[t](`[${s}][${this.name}]`,...e)}}m(bn,"LEVEL",0);class Cc{constructor(){m(this,"logger",new bn("AudioMixer"));m(this,"audioContext",new AudioContext);m(this,"audioDestination",this.audioContext.createMediaStreamDestination());m(this,"audioTrack",(s=>s.getAudioTracks()[0])(this.audioDestination.stream));m(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(s=>s.sourceNode).filter(s=>!!s)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(s=>s.gainNode).filter(s=>!!s)}get sourceCount(){return this.sourceNodeList.length}resume(){var s;return(s=this.audioContext)==null?void 0:s.resume()}addTrack(s){this.connectTrack(s)}hasTrack(s){return!!this.sourceNodeMap[s]}removeTrack(s){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[s]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[s],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${s} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(s,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(s)}`),t.gain.value=this.scale(s)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var s;this.reset(),(s=this.audioTrack)==null||s.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(s){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(s);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[s.id]={track:s,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(s=>s.disconnect()),this.gainNodeList.forEach(s=>s.disconnect())}scale(s){return s/100}}class kc extends xt{constructor(){super("audioMixer",Ve.AliRtcSdkStreamTypeCapture,ci.AUDIO);m(this,"audioMixer");m(this,"primaryAudioTrackId");m(this,"screenAudioTrackId");m(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,c;if(e.type!==Ve.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Ve.AliRtcSdkStreamTypeCapture),r=t.find(o=>o.type===Ve.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=i==null?void 0:i.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((c=r==null?void 0:r.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return E(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(l=>l.type===Ve.AliRtcSdkStreamTypeScreen),r=e.currentAudioTrack,n=i==null?void 0:i.currentAudioTrack;if(!n&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=r==null?void 0:r.id,void e.updateAudioTrack(r);this.audioMixer||(this.audioMixer=new Cc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(r==null?void 0:r.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),r&&!this.audioMixer.hasTrack(r==null?void 0:r.id)&&this.audioMixer.addTrack(r),this.primaryAudioTrackId=r==null?void 0:r.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class Pc extends xt{constructor(){super(...arguments);m(this,"isProcessing",!1);m(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return hr.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return E(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=hr.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function li(a,s,e,t){return new(e||(e=Promise))(function(i,r){function n(l){try{o(t.next(l))}catch(d){r(d)}}function c(l){try{o(t.throw(l))}catch(d){r(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(u){u(d)})).then(n,c)}o((t=t.apply(a,s||[])).next())})}var Ht,kt;function vn(){return li(this,void 0,void 0,function*(){let a=!1;try{a=yield(()=>E(this,null,function*(){return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}))()}catch(s){a=!1}return console.log("isSupportedSIMD",a),a})}typeof SuppressedError=="function"&&SuppressedError,(kt=Ht||(Ht={}))[kt.ERROR=0]="ERROR",kt[kt.WARN=1]="WARN",kt[kt.INFO=2]="INFO",kt[kt.LOG=3]="LOG",kt[kt.DEBUG=4]="DEBUG";class ye{static error(...s){var e;ye.logLevel>=Ht.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${ye.logTag}] `,...s))}static warn(...s){var e;ye.logLevel>=Ht.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${ye.logTag}] `,...s))}static info(...s){var e;ye.logLevel>=Ht.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${ye.logTag}] `,...s))}static log(...s){var e;ye.logLevel>=Ht.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${ye.logTag}] `,...s))}static debug(...s){var e;ye.logLevel>=Ht.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${ye.logTag}] `,...s))}}ye.logLevel=Ht.WARN,ye.logTag="aliyun-audio-3a";class Dc{}class yn extends Dc{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const s="AudioWorklet"in window,e="WebAssembly"in window;return s&&e}return!1}()}static isSupportedSIMD(){return li(this,void 0,void 0,function*(){return yield vn()})}static setLogger(s){ye.logLevel=s}constructor(s){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},s||{})}initWASM(s,e,t){return li(this,void 0,void 0,function*(){ye.log("initWASM",s,e,t);const i=n=>li(this,void 0,void 0,function*(){try{const c=yield fetch(n,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${n}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),ye.error("Error fetching WASM:",c),new Uint8Array(0)}}),r=n=>li(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield vn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(n?o:c),u=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",h=n?p:u,f=yield r(h);s.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:n,audioModuleScript:f,logLevel:ye.logLevel},this.options),[d])}catch(n){ye.error("Error initializing WASM:",n),this.onLoadError(new Error("WASM init error"))}s.port.onmessage=n=>{n.data.type==="init_done"&&this.onLoadSuccess(void 0),n.data.type==="dump_output_data"&&this.onDumpOutputData(n.data.data),n.data.type==="dump_near_data"&&this.onDumpNearInputData(n.data.data),n.data.type==="dump_far_data"&&this.onDumpFarInputData(n.data.data),n.data.type==="dump_meta_data"&&this.onDumpMeatData(n.data.data),n.data.type==="output_log"&&this.onOutputLog(n.data.data),n.data.type==="apm_stat_data"&&this.onStatData(n.data.data)}})}createProcessor(s,e,t,i,r){return li(this,void 0,void 0,function*(){this.audioContext=s,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var hl=Object.defineProperty,pl=Object.defineProperties;var ml=Object.getOwnPropertyDescriptors;var Gi=Object.getOwnPropertySymbols,gl=Object.getPrototypeOf,Wn=Object.prototype.hasOwnProperty,zn=Object.prototype.propertyIsEnumerable,fl=Reflect.get;var Qr=(W,J,ne)=>J in W?hl(W,J,{enumerable:!0,configurable:!0,writable:!0,value:ne}):W[J]=ne,X=(W,J)=>{for(var ne in J||(J={}))Wn.call(J,ne)&&Qr(W,ne,J[ne]);if(Gi)for(var ne of Gi(J))zn.call(J,ne)&&Qr(W,ne,J[ne]);return W},vt=(W,J)=>pl(W,ml(J));var Ot=(W,J)=>{var ne={};for(var rt in W)Wn.call(W,rt)&&J.indexOf(rt)<0&&(ne[rt]=W[rt]);if(W!=null&&Gi)for(var rt of Gi(W))J.indexOf(rt)<0&&zn.call(W,rt)&&(ne[rt]=W[rt]);return ne};var m=(W,J,ne)=>(Qr(W,typeof J!="symbol"?J+"":J,ne),ne);var Zr=(W,J,ne)=>fl(gl(W),ne,J);var E=(W,J,ne)=>new Promise((rt,yt)=>{var lt=ze=>{try{mt(ne.next(ze))}catch(De){yt(De)}},Rt=ze=>{try{mt(ne.throw(ze))}catch(De){yt(De)}},mt=ze=>ze.done?rt(ze.value):Promise.resolve(ze.value).then(lt,Rt);mt((ne=ne.apply(W,J)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}catch(o){ye.error("Failed to add module to audio worklet:",o)}let n=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=n,e.connect(n),r&&(this.farNode=r,r.connect(n,0,1));const c=this.audioContext.createMediaStreamDestination();n.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(n,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(s){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),s&&(this.farNode=s,s.connect(this.workletNode,0,1)))}getStatData(){var s;try{(s=this.workletNode)===null||s===void 0||s.port.postMessage({type:"get_stat_data"})}catch(e){ye.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),ye.log("postMessage destroy")}catch(s){ye.error("Failed to post message to worklet node:",s)}}startDump(){var s;try{(s=this.workletNode)===null||s===void 0||s.port.postMessage({type:"start_dump"})}catch(e){ye.error("Failed to post message to worklet node:",e)}}stopDump(){var s;try{(s=this.workletNode)===null||s===void 0||s.port.postMessage({type:"stop_dump"})}catch(e){ye.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(s,e=!1){if(s&&s.length>0&&this.collectDumpOutputData.push(s),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(s,e=!1){if(s&&s.length>0&&this.collectDumpNearInputData.push(s),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(s,e=!1){if(s&&s.length>0&&this.collectDumpFarInputData.push(s),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(s,e=!1){if(s&&s.length>0&&this.collectDumpMetaData.push(s),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var s;if(!((s=this.workletNode)===null||s===void 0)&&s.port)try{this.workletNode.port.postMessage({type:"enable"}),ye.log("postMessage enable")}catch(e){ye.error("Failed to post message to worklet node:",e)}}disable(){var s;if(!((s=this.workletNode)===null||s===void 0)&&s.port)try{ye.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){ye.error("Failed to post message to worklet node:",e)}}on(s,e){s==="loaderror"&&(this.onLoadError=e),s==="loadsuccess"&&(this.onLoadSuccess=e),s==="dumpdata"&&(this.onDumpData=e),s==="outputlog"&&(this.onOutputLog=e),s==="statdata"&&(this.onStatData=e)}onLoadError(s){console.log("onLoadError",s)}onLoadSuccess(s){console.log("onLoadSuccess",s)}onDumpData(s,e){console.log("onDumpData",s,e)}onOutputLog(s){console.log("[WASM]",s)}onStatData(s){console.log("onStatData:",s)}}class Mc extends xt{constructor(e){super("AliRtcAudioProcessPlugin",Ve.AliRtcSdkStreamTypeCapture,ci.AUDIO);m(this,"audioProcessor");m(this,"slsReporter");m(this,"enableSoft3ACheck",!1);m(this,"useHardOnly",!1);m(this,"lastDiffOutputLog","");m(this,"audioContext",new AudioContext({sampleRate:48e3}));m(this,"farNode");m(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}activeAudioContext(){var e;(e=this.audioContext)==null||e.resume(),document.removeEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=X(X({},this.options),e))}isSupported(){return yn.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return E(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){this.audioProcessor=new yn({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(r,n)=>{let c=3e3;n.includes("far")?c=5e3:n.includes("output")?c=1e4:n.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(r),l=document.createElement("a");l.href=o,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var r,n;this.enableSoft3ACheck||e.updateAudioTrack((r=this.audioProcessor)==null?void 0:r.targetMediaTrack),this.options.dumpAudioData&&((n=this.audioProcessor)==null||n.startDump())}),this.audioProcessor.on("loaderror",r=>{this.emit("error",r)}),this.audioProcessor.on("outputlog",r=>{r!=null&&r.includes("diff")&&(this.lastDiffOutputLog=r||"")}),this.audioProcessor.on("statdata",r=>{var n;if(r)try{let c=r;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),l=JSON.parse(r);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(c){}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,r;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(r=this.farNode)==null||r.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var Ai=(a=>(a[a.Default=0]="Default",a[a.Human=1]="Human",a[a.Robot=2]="Robot",a))(Ai||{}),Nc=Object.defineProperty,Lc=Object.getOwnPropertyDescriptor,Rn=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?Lc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&Nc(s,e,r),r};const Or=($t=class extends ne{constructor(e,t){super();m(this,"self");m(this,"remoteUser");m(this,"sendReadyMsg",!1);m(this,"hasPubDataChannel",!1);m(this,"hasSubDataChannel",!1);m(this,"readyMsgSuccess",!1);m(this,"sendReadyMsgTimer");m(this,"startReadyMsgTime");m(this,"robotUserId");m(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg()))});m(this,"onCheckReadyMsg",(e,t)=>{var i,r;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const n=new TextDecoder().decode(t.data),c=JSON.parse(n);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(C.event(`[${$t.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(r=this.remoteUser)==null||r.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(n){}});m(this,"onDataPublishStateChange",(e,t)=>{t===ee.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){C.event(`[${$t.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return E(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new Ut(new TextEncoder().encode(t).buffer))}catch(n){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const r=Date.now()-this.startReadyMsgTime;i=r<1e3?50:r<2e3?100:r<3e3?500:2e3,e>30?C.event(`[${$t.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},m($t,"logName","DataChannelReadyHelper"),$t);Rn([k()],Or.prototype,"destroy",1),Rn([k()],Or.prototype,"sendReadyMsgLoop",1);let xc=Or;class Oc{constructor(s){m(this,"_useSysEchoCancellation",!0);m(this,"_useSysNoiseSuppression",!0);m(this,"_useSysAutoGainControl",!0);m(this,"_useAIAEC",!1);m(this,"_enableSoft3A",!1);m(this,"_enableSoft3ACheck",!1);m(this,"_useHardOnly",!1);m(this,"_dumpAudioData",!1);m(this,"_useAudio3AConfigFromServer",!0);s&&Object.assign(this,s)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(s){this._useSysEchoCancellation=s}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(s){this._useSysNoiseSuppression=s}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(s){this._useSysAutoGainControl=s}get useAIAEC(){return this._useAIAEC}set useAIAEC(s){this._useAIAEC=s}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(s){this._enableSoft3A=s}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(s){this._enableSoft3ACheck=s}get useHardOnly(){return this._useHardOnly}set useHardOnly(s){this._useHardOnly=s}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(s){this._dumpAudioData=s}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(s){this._useAudio3AConfigFromServer=s}loadFromLocalConfig(s){var e,t,i,r,n,c,o,l,d;this.useAudio3AConfigFromServer=(e=s.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=s.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=s.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(r=s.useSysAutoGainControl)!=null?r:this.useSysAutoGainControl,this.useAIAEC=(n=s.useAIAEC)!=null?n:this.useAIAEC,this.enableSoft3A=(c=s.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=s.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(l=s.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=s.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(s){if(s&&typeof s=="object"){const e=Kt(s,"enableSoft3A"),t=ai(s,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(s.archCfgs){const i=Kt(s,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=Kt(s,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=Kt(s,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=Kt(s,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=Kt(s,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(s.config){const i=ai(s,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=ai(s,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=ai(s,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=ai(s,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=ai(s,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}C.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var Vc=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,at=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?Uc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&Vc(s,e,r),r};class Ye extends ne{constructor(e){super();m(this,"self");m(this,"userMap",{});m(this,"usersViewMap",{});m(this,"rtsManager");m(this,"localStreamManager");m(this,"authInfo");m(this,"signalingManager");m(this,"pluginManager");m(this,"audioMixerPlugin");m(this,"dualVideoPlugin");m(this,"blankAudioPlugin");m(this,"audioProcessorPlugin");m(this,"slsReporter");m(this,"statsMonitorId");m(this,"autoSubAudio",!0);m(this,"autoSubVideo",!0);m(this,"autoSubScreen",!0);m(this,"wantSubAudio",!0);m(this,"wantSubVideo",!0);m(this,"wantSubScreen",!0);m(this,"defaultStreamType",Ke.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"refreshUrlTimer");m(this,"audioVolumeIndicationInterval",0);m(this,"indicationTimer",0);m(this,"parameter",{});m(this,"audio3AConfig",new Oc);m(this,"dcReadyHelper");m(this,"networkQualityTimer");const{signalingManager:t,slsReporter:i,parameter:r}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,r&&(this.parameter=r),this.pluginManager=new fc,this.localStreamManager=new Ec(this.pluginManager,this.slsReporter),this.rtsManager=new Ac(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new dc({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new kc,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new Pc("dualVideoPlugin"),new J.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new Tc)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(r=>{var n;if(r.msid===M.Audio&&r.userdata)try{const c=JSON.parse(r.userdata);c.agent_instance&&((n=this.slsReporter)==null||n.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(Xe.RECV_NOTIFY_PUBLISH,"","",""),C.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(ke.removeQueryString(this.self.url)===ke.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(r=>ke.removeQueryString(r.streamUrl)===ke.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(n=>{n.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const r=this.remoteUsers.find(n=>ke.removeQueryString(n.streamUrl)===ke.removeQueryString(t||""));r==null||r.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(C.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(n=>{n.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const r=this.remoteUsers.find(n=>ke.removeQueryString(n.streamUrl)===ke.removeQueryString(t||""));r==null||r.markReconnected(i)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(me.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(me.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(me.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){if(!e)return this.publisher.setViewConfig(null,t);const i=Qi(e);i.length!==0&&i.forEach(r=>{this.publisher.resetElement(r),Object.values(this.usersViewMap).forEach(({cameraViews:n=[],screenViews:c=[]})=>{n.includes(r)&&n.splice(n.indexOf(r),1),c.includes(r)&&c.splice(c.indexOf(r),1)}),this.publisher.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var n,c;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,i);const r=Qi(t);r.length!==0&&(r.forEach(o=>{this.publisher.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:l=[],screenViews:d=[]})=>{l.includes(o)&&l.splice(l.indexOf(o),1),d.includes(o)&&d.splice(d.indexOf(o),1)})}),(c=this.userMap[e])==null||c.setViewConfig(r,i))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:r,isScreenSubscribing:n}=t;return i||r||n})}onRemotePublishStateChange(e,t=!0){var h;const{userid:i,callid:r,subscribe:n,pubid:c="",tracks:o}=e,l=(h=n==null?void 0:n.pullstreamurl)!=null?h:"";let d=this.getRemoteUser(i);if(!d)return;const u=d.streamInfo.audioTrackInfo,p=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(r,l,c,o),u===d.streamInfo.audioTrackInfo&&p===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(me.Publish)}setTimeoutToUpdateAllStreamUrls(e){var r;if(!e)return;let t=354e4;const i=(r=function(n){var c,o;try{const l=new URL(n),[d,u]=l.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(u),h=p==null?void 0:p[1],f=p==null?void 0:p[2],g=new URLSearchParams(l.search);return{appId:d,channelId:h,sessionId:f,timeoutTs:1e3*parseInt((o=(c=g.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){return null}}(e))==null?void 0:r.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>E(this,null,function*(){var c;const n=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});n.pushstreamurl&&(this.self.url=n.pushstreamurl),(c=n.users)==null||c.forEach(o=>{var d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(n.pushstreamurl)}),t)}init(e,t,i){var r;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((r=t==null?void 0:t.config)==null?void 0:r.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===Ai.Human&&(this.dcReadyHelper=new xc(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destroy(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(n=>{this.addUser(n,me.InRoom)}),this.startStatsMonitor(),this.networkQualityTimer=window.setInterval(()=>E(this,null,function*(){if(this.remoteUsers.length===0)return void this.emit("networkQuality",{subscribe:{rtt:0,loss:0,quality:Qe.AliRtcNetworkUnknown}});const n=yield this.rtsManager.getSubscribeNetworkQuality();this.emit("networkQuality",{subscribe:n})}),2e3)}leave(){return E(this,null,function*(){var e;this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:t=[],screenViews:i=[]})=>{t.forEach(r=>{r.srcObject=null,r._playPromise=void 0}),i.forEach(r=>{r.srcObject=null,r._playPromise=void 0})}),this.usersViewMap={};for(let t in this.userMap)this.userMap[t]&&(this.userMap[t].clear(),delete this.userMap[t]);this.self.leave(),(e=this.dcReadyHelper)==null||e.destroy(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0,window.clearInterval(this.networkQualityTimer)})}clear(){return E(this,null,function*(){yield this.leave(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>E(this,null,function*(){if(this.publisher){const{audio:i,video:r,candidate:n}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),r&&r.length>0&&this.emit("rtcLocalVideoStats",r),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:r,video:n}=yield i.getStats();r&&r.forEach(c=>{e.push(c)}),n&&n.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t){const i=e.userid;let r=this.userMap[i];return r||(r=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=r,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==me.InRoom),r}executeAddUser(e,t,i){const r=new gc({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return r.on(Ze.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(Ce.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(Ce.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(n,c,o,l)=>{this.emit("audioSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("videoSubscribeStateChanged",(n,c,o,l)=>{this.emit("videoSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("screenSubscribeStateChanged",(n,c,o,l)=>{this.emit("screenSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("dataSubscribeStateChanged",(n,c,o,l)=>{var d;o===oe.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),r.on("remoteVideoAutoPlayFail",(n,c)=>{this.emit("remoteVideoAutoPlayFail",n,c)}),r.on("remoteAudioPlayError",(n,c)=>{this.emit("remoteAudioPlayError",n,c)}),r.on("remoteVideoPlayError",(n,c)=>{this.emit("remoteVideoPlayError",n,c)}),r.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n,r.userId)}),r.on("occurError",n=>{this.emit("occurError",n,r.userId)}),r.on("remoteDataChannelMessage",(n,c)=>{this.emit("remoteDataChannelMessage",n,c)}),r.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),r.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),r.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),r.setRemoteDefaultVideoStreamType(this.defaultStreamType),r.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&r.updateSubscribe(i),r}onRemoteDeviceStatusChange(e,t){e===Ce.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ce.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ce.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ce.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ce.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ce.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Ce.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Ce.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return E(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(n=>{n.userid&&(this.userMap[n.userid]?i.push(n):t.push(n))});const r=Object.keys(this.userMap).filter(n=>!e.find(c=>c.userid===n)).map(n=>({userid:n,reason:"",leavecode:Xi.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:r,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(me.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(me.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(me.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=X(X({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,r,n,c,o;const t=JSON.parse(e);Object.keys(t).forEach(l=>{const d=this.parameter[l],u=t[l];this.parameter[l]=typeof d=="object"&&typeof u=="object"?X(X({},d),u):u}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new Ic),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((r=this.blankAudioPlugin)==null?void 0:r.name),(n=this.blankAudioPlugin)==null||n.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio)),t.subscribe&&((o=this.rtsManager)==null||o.updateSubscribeBatcher(t.subscribe))}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new Mc({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;C.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}m(Ye,"logName","BizControl"),at([k()],Ye.prototype,"init",1),at([k()],Ye.prototype,"leave",1),at([k()],Ye.prototype,"clear",1),at([k(H)],Ye.prototype,"addUser",1),at([k()],Ye.prototype,"removeLeftUser",1),at([k()],Ye.prototype,"diffUsers",1),at([k(H)],Ye.prototype,"updateAudioWant",1),at([k(H)],Ye.prototype,"updateVideoWant",1),at([k(H)],Ye.prototype,"updateScreenWant",1),at([k()],Ye.prototype,"stopIndication",1),at([k()],Ye.prototype,"startIndication",1),at([k(H)],Ye.prototype,"setEnableDualVideoStream",1),at([k(H)],Ye.prototype,"setAudioVolume",1),at([k()],Ye.prototype,"enableAudioVolumeIndication",1);var wi=(a=>(a[a.LiveTranscodingSingle=0]="LiveTranscodingSingle",a[a.LiveTranscodingMix=1]="LiveTranscodingMix",a))(wi||{}),Vr=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingAudio=1]="LiveTranscodingAudio",a[a.LiveTranscodingVideo=2]="LiveTranscodingVideo",a))(Vr||{}),di=(a=>(a[a.LiveTranscodingCamera=0]="LiveTranscodingCamera",a[a.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",a))(di||{});const _i={0:"camera",1:"shareScreen"};var Ur=(a=>(a[a.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",a[a.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",a[a.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",a[a.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",a[a.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",a[a.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",a[a.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",a[a.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",a[a.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",a[a.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",a[a.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",a[a.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",a[a.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",a[a.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",a[a.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",a[a.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",a[a.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",a[a.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",a[a.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",a))(Ur||{});const Bc={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var ji=(a=>(a[a.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",a[a.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",a[a.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",a[a.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",a[a.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",a))(ji||{}),Ei=(a=>(a[a.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",a[a.LiveTranscodingBody=1]="LiveTranscodingBody",a))(Ei||{}),Ti=(a=>(a[a.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",a[a.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",a[a.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",a[a.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",a[a.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",a[a.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",a))(Ti||{}),Br=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingCrop=1]="LiveTranscodingCrop",a[a.LiveTranscodingFill=2]="LiveTranscodingFill",a))(Br||{}),$i=(a=>(a[a.LiveTranscodingNormal=0]="LiveTranscodingNormal",a[a.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",a))($i||{}),Hr=(a=>(a[a.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",a[a.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",a[a.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",a[a.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",a[a.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",a[a.LiveTranscodingState_END=5]="LiveTranscodingState_END",a))(Hr||{}),Pt=(a=>(a[a.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",a[a.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",a[a.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",a[a.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",a[a.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",a[a.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",a[a.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",a[a.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",a[a.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",a))(Pt||{}),Fr=(a=>(a[a.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",a[a.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",a[a.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",a))(Fr||{}),nt=(a=>(a[a.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",a[a.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",a[a.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",a[a.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",a[a.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",a[a.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",a[a.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",a))(nt||{});const Hc={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class jr{constructor(s,e,t,i,r,n,c,o){m(this,"videoWidth");m(this,"videoHeight");m(this,"videoFramerate",20);m(this,"videoBitrate",2e3);m(this,"videoGop",30);m(this,"audioSamplerate",ji.LiveTranscoding_HZ_44100);m(this,"audioBitrate",500);m(this,"audioChannels",1);this.videoWidth=s,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),r&&(this.videoGop=r),n&&(this.audioSamplerate=n),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const $r=a=>((16711680&a)>>16)+(65280&a)+((255&a)<<16),St=(a=0,s)=>{if(s==0)return 0;let e=a/s;return e<0&&(e=0),e>1&&(e=1),e};class Wi{constructor(s,e,t){m(this,"mixMode",wi.LiveTranscodingSingle);m(this,"singleParam");m(this,"mixParam");s&&(this.mixMode=s),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(s,e,t,i,r){const n={appid:e.appId,channelid:e.channelId};if(s===nt.MPU_TASK_TRANSACTION_POLLING||s===nt.MPU_TASK_TRANSACTION_LIST||s===nt.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return s===nt.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=r),n;if(n.taskid=t,s!==nt.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===wi.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===di.LiveTranscodingShareScreen?n.sourcetype=_i[c.sourceType]:n.sourcetype=_i[di.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(s===nt.MPU_TASK_TRANSACTION_START||s===nt.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=Bc[c.taskProfile]);const o=c.encodeParam||new jr(1280,720);let l=o.videoWidth,d=o.videoHeight;const u={};Object.keys(o).forEach(h=>{const f=o[h];f>0&&(u[h.toLowerCase()]=f)}),u.lowbitratehighquality=0,n.encodeparam=u,n.backgrounds=c.backgrounds.map(h=>h.toJson(l,d)),n.watermarks=c.watermarks.map(h=>h.toJson(l,d)),n.clockwidgets=c.clockWidgets.map(h=>h.toJson(l,d));const p=c.users.map(h=>h.userId);n.subspecusers=[...new Set(p)],n.layouts=[{audiomixcount:c.users.length,panes:c.users.map((h,f)=>h.toJson(f,l,d,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=$r(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const Wr=a=>E(this,null,function*(){const s=new Uint8Array(160).fill(170),e=new TextEncoder().encode(a),t=yield window.crypto.subtle.importKey("raw",s,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")});class Fc{constructor(s){m(this,"authInfo");m(this,"slsReporter");this.slsReporter=s}doRequest(s,e){var c;const t=this.authInfo;if(!t)return Promise.reject(Pt.LiveTranscodingErrorInvalidParam);const i=Hc[s],r={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:ke.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:ke.createCallid()},n=Object.keys(r).map(o=>`${o}=${encodeURIComponent(r[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${n}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new V(B.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new V(B.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(s){this.authInfo=s}clear(){this.authInfo=void 0}startPublishLiveStream(s,e){return E(this,null,function*(){if(!this.authInfo)return Promise.reject(Pt.LiveTranscodingErrorInvalidParam);const t=yield Wr(s.split("?")[0]),i=nt.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,s);return this.doRequest(i,r)})}startPublishLiveStreamWithTaskId(s,e){return E(this,null,function*(){if(!this.authInfo)return Promise.reject(Pt.LiveTranscodingErrorInvalidParam);const t=nt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,s);return this.doRequest(t,i)})}updatePublishLiveStream(s,e){return E(this,null,function*(){if(!this.authInfo)return Promise.reject(Pt.LiveTranscodingErrorInvalidParam);const t=yield Wr(s.split("?")[0]),i=nt.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,s);return this.doRequest(i,r)})}updatePublishLiveStreamWithTaskId(s,e){return E(this,null,function*(){if(!this.authInfo)return Promise.reject(Pt.LiveTranscodingErrorInvalidParam);const t=nt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,s);return this.doRequest(t,i)})}stopPublishLiveStream(s){return E(this,null,function*(){if(!this.authInfo)return Promise.reject(Pt.LiveTranscodingErrorInvalidParam);const e=yield Wr(s.split("?")[0]),t=nt.MPU_TASK_TRANSACTION_STOP,i=new Wi().toJson(t,this.authInfo,e,s);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(s){if(!this.authInfo)return Promise.reject(Pt.LiveTranscodingErrorInvalidParam);const e=nt.MPU_TASK_TRANSACTION_STOP,t=new Wi().toJson(e,this.authInfo,s);return this.doRequest(e,t)}refreshAuthInfo(s){this.authInfo&&this.setAuthInfo(X(X({},this.authInfo),s))}}function An(a,s){const e=new window.XMLHttpRequest;e.open("POST",`${a}?APIVersion=0.6.0`,!0),e.send(s)}function jc(a,s){try{if(s.length>=32768)return void An(a,s);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(a,s)||An(a,s)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
133
- `+e),console.error("Failed log data:",a))}}function $c(a,s,e){return t=this,i=null,r=function*(){try{a=a.slice(0,-6);const{data:n,header:c}=yield e.process(a,s),o=new window.XMLHttpRequest;o.open("POST",a,!0);for(let l in c)o.setRequestHeader(l,c[l]);o.send(n)}catch(n){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
134
- `+n),console.error("Failed log data:",a))}},new Promise((n,c)=>{var o=u=>{try{d(r.next(u))}catch(p){c(p)}},l=u=>{try{d(r.throw(u))}catch(p){c(p)}},d=u=>u.done?n(u.value):Promise.resolve(u.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}class wn extends ga{constructor(s){super(Object.assign({},s,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>{jc(e,t)}}))}useStsPlugin(s){this.getOpt().sendPayload=(e,t)=>{$c(e,t,s)},this.overwriteTransString(s)}}ns(window,"SLS_Tracker",wn);const ri=class ri{constructor(){m(this,"ntpClock");this.ntpClock=new J.AliRTS.Clock}static getInstance(){return ri.instance||(ri.instance=new ri),ri.instance}now(){return this.ntpClock.now()}};m(ri,"instance");let zr=ri;const _n=()=>zr.getInstance(),{BrowserUtil:Kr,SystenUtil:En}=J.AliRTS,zi=6e5,Wc={host:"cn-shanghai.log.aliyuncs.com",project:"apsara-video-client",logstore:"client"},zc={host:"ap-southeast-1.log.aliyuncs.com",project:"apsara-video-client-sgp",logstore:"client"};class Kc{constructor(s){m(this,"tracker");m(this,"param");m(this,"msgCacheArr",[]);m(this,"index",0);m(this,"ntpClock");m(this,"clientId",dt());m(this,"stsData");m(this,"stsExpiration",Date.now());m(this,"updateTaskTimer");m(this,"globalEnv","DEFAULT");this.ntpClock=_n(),s&&(this.globalEnv=s)}createTracker(){if(!this.tracker&&this.stsData&&this.param){const s=this.globalEnv==="SEA"?zc:Wc,e=new wn({host:s.host,project:s.project,logstore:s.logstore}),t={accessKeyId:this.stsData.AccessKeyId,accessKeySecret:this.stsData.AccessKeySecret,securityToken:this.stsData.SecurityToken,refreshSTSTokenInterval:zi,refreshSTSToken:()=>{this.refreshSTSToken().then(r=>{t.accessKeyId=r.AccessKeyId,t.accessKeySecret=r.AccessKeySecret,t.securityToken=r.SecurityToken}).catch(()=>{})}},i=ar(t);e.useStsPlugin(i),this.tracker=e,this.msgCacheArr.forEach((r,n)=>{var c,o;(o=this.tracker)==null||o.send(X(vt(X({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${n}`}),r))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}}startSTSUpdateTask(){return E(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{this.stsData=yield this.refreshSTSToken(),this.createTracker()}catch(s){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},zi)})}refreshSTSToken(){return E(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+zi){const s=yield this.requestSTSToken(),e=new Date(s==null?void 0:s.Expiration).getTime()||0,t=Date.now()+zi;this.stsExpiration=Math.max(e,t),this.stsData=s}return this.stsData})}requestSTSToken(){const s=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${s}`,t={Action:"AssumeSlsRoleV2",AuthInfo:Gt.MD5(e).toString(Gt.enc.Hex),ClientId:this.clientId,BusinessType:"rtc",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${s}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Ni(s,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),r=`https://${this.globalEnv==="SEA"?"vod.ap-southeast-1.aliyuncs.com":"vod.cn-shanghai.aliyuncs.com"}/?${i}`;return fetch(r).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}start(s){this.initParam(s),this.createTracker(),this.startSTSUpdateTask()}stop(){this.tracker=void 0,this.param=void 0,this.msgCacheArr=[],this.index=0,this.stsData=void 0,this.updateTaskTimer&&(clearTimeout(this.updateTaskTimer),this.updateTaskTimer=void 0)}sendReport(s){var t,i;let e;s.tm=Date.now();try{e=JSON.parse(JSON.stringify(X(vt(X({bt:Kr.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((t=this.param)==null?void 0:t.sesid)||"nosession"}-${this.index}`}),s)))}catch(r){}e&&(this.tracker?((i=this.tracker)==null||i.send(e),this.index++):this.msgCacheArr.push(e))}initParam(s){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=dt(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:s.appId,usrid:s.userId,statsvrs:"0.6.1",evetid:0,sesid:s.sessionId,sessionId:s.sessionId,channelid:s.channelId,usrn:s.userId,osn:En.systemName,osv:En.systemVersion,deb:Ho(),den:Vo(),udid:e,sdkvrs:gi,acs:"Unknown",cput:ma(),dm:`${window.location.protocol}//${window.location.host}`,bt:Kr.browserName,bv:Kr.browserVersion,envir:"PRODUCT",args:"",instid:dt()})}}const we=(a,s=1,e=6e4,t=0)=>{let i=a;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*s)))},bt=(a,s,e=2e7,t=0)=>{let i=s;(!s||s<0||s>1e4)&&(i=1e3);let r=a;return r||(r=0),Math.min(e,Math.max(t,Math.round(r/(i/1e3))))},Zt=(a,s)=>{if(s===0||!s)return"0.00";let e=a;return(!e||e<0)&&(e=0),(e/s*100).toFixed(2)},Tn=a=>a>=0&&a<=1?we(Math.floor(32767*a),1,32767):0,Ie=(a,s)=>{var t,i,r;let e=((t=a._last)==null?void 0:t[s])||0;return a.ssrc&&((i=a._last)!=null&&i.ssrc)&&a.ssrc!==((r=a._last)==null?void 0:r.ssrc)&&(e=0),((a==null?void 0:a[s])||0)-e},In=(a,s)=>we(Ie(a,s),1e3,1e4),ei=(a,s=2e7)=>we(a,1,s);class Jc{constructor(s,e){m(this,"engine");m(this,"logClient");m(this,"authInfo");m(this,"ntpClock");m(this,"customFields",{});this.logClient=new Kc(e),this.engine=s,this.ntpClock=_n()}setCustomFields(s){this.customFields=X(X({},this.customFields),s)}getCustomField(s){return this.customFields[s]}start(s){this.authInfo=s,this.logClient.start(s)}stop(){this.logClient.stop()}reportPublishAudio3A(s,e,t,i){const r={};let n=JSON.parse(i);r.publevel=n.capture_audio_cur_level_db||0,r.eleakrate=n.echo_leak_rate||0,r.playbw=n.render_bandwidth||-1,r.capbw=n.capture_bandwidth||-1,r.diff=n.diff||0,r.leak=n.leak||0,this.log({evetid:10070,traceid:t,calid:s,rmtid:"",args:this.data2String(X({calid:s,tckid:e||"audio3a",rmtid:"",traceid:t},r))})}reportPublishMonitor(s,e,t,i,r){if(!t||r.length<=0)return;const n=t===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[],S=[],b=[],v=[],R=[],_=[],y=[],A=[],w=[],T=[],I=[],P=[];try{if(r.forEach(D=>{var O,ue,Me,K,Se,Le;if(!D||!D.timestamp)return;const U=(O=D._last)!=null&&O.timestamp?D.timestamp-D._last.timestamp:1e3,q=Ie(D,"bytesSent"),Y=Ie(D,"headerBytesSent"),G=bt(we(q+Y,8,2e7),U);o.push(G);const $=bt(we(q,8,2e7),U);l.push($);const Z=bt(we(Y,8,2e7),U);d.push(Z);const te=Ie(D,"packetsSent"),fe=bt(te,U);u.push(fe);const N=Ie(D,"packetsLost"),x=bt(N,U);p.push(x);const L=Zt(N,te);if(h.push(L),n)(ue=D._source)!=null&&ue.audioLevel&&f.push(Tn(D._source.audioLevel)),g.push(0);else{S.push(In(D,"totalEncodeTime")),b.push(ei((Me=D._source)==null?void 0:Me.framesPerSecond,100)),v.push(ei((K=D._source)==null?void 0:K.framesPerSecond,100)),R.push(ei(D.framesPerSecond,100)),_.push(ei((Se=D._source)==null?void 0:Se.height,4400)),y.push(ei((Le=D._source)==null?void 0:Le.width,7700)),A.push(ei(D.frameHeight,4400)),w.push(ei(D.frameWidth,7700));const _e=Ie(D,"totalPacketSendDelay");T.push(we(_e,1/(N||1),2e3));const Pe=Ie(D,"qpSum");I.push(we(Pe,1/(D.framesPerSecond||1),51)),P.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=u.join(","),c.pl=p.join(","),c.plr=h.join(","),n){const D=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=g.join(","),c.arsr=D,c.aesr=D,c.publevel=-90,c.rawlevel=-90}else c.em=S.join(","),c.cfps=b.join(","),c.ifps=v.join(","),c.sfps=R.join(","),c.ih=_.join(","),c.iw=y.join(","),c.sh=A.join(","),c.sw=w.join(","),c.sd=T.join(","),c.aqp=I.join(","),c.caf=P.join(","),c.can=P.join(","),c.cav=l.join(","),c.ifimax=P.join(","),c.ifimin=P.join(","),c.efimax=P.join(","),c.efimin=P.join(","),c.sfimax=P.join(","),c.sfimin=P.join(","),c.apsnr=P.join(",")}catch(D){}this.log({evetid:10070,traceid:e,calid:s,rmtid:"",args:this.data2String(X({calid:s,tckid:t,rmtid:"",traceid:e},c))})}reportSubscribeMonitor(s,e,t,i,r){if(!i||!r||r.length<=0)return;const n=i===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[],S=[],b=[],v=[],R=[],_=[],y=[],A=[],w=[],T=[],I=[],P=[],D=[],U=[],q=[],Y=[],G=[],$=[],Z=[],te=[],fe=[],N=[],x=[],L=[],O=[],ue=[],Me=[];try{r.forEach(K=>{var pe,We;if(!K||!K.timestamp)return;const Se=(pe=K._last)!=null&&pe.timestamp?K.timestamp-K._last.timestamp:1e3,Le=Ie(K,"bytesReceived"),_e=Ie(K,"headerBytesReceived"),Pe=bt(we(Le+_e,8,2e7),Se);o.push(Pe);const be=bt(we(Le,8,2e7),Se);l.push(be);const Ee=bt(we(_e,8,2e7),Se);d.push(Ee);const he=Ie(K,"packetsReceived"),Ne=bt(he,Se);u.push(Ne);const Re=Ie(K,"packetsLost"),Ge=bt(Re,Se);p.push(Ge);const ot=Zt(Re,he);h.push(ot);const ce=Ie(K,"jitterBufferDelay"),ae=Ie(K,"jitterBufferEmittedCount");if(K.jitterBufferDelay&&K.jitterBufferEmittedCount){const Q=we(ce,1e3/ae,1e4);f.push(Q)}else f.push(0);const ie=Ie(K,"fecPacketsReceived");R.push(Zt(ie,he));const ve=Ie(K,"retransmittedPacketsReceived"),Ue=he+Re-ve;if(S.push(Zt(he-ve,Ue)),b.push(Zt(Re,Ue)),g.push(Zt(ve,Ue)),v.push(Ue),ue.push(0),Me.push(""),n){y.push(Tn(K.audioLevel));const Q=((Oe,wt)=>{var Dt,_t,Wt;return(((Dt=Oe==null?void 0:Oe._source)==null?void 0:Dt[wt])||0)-(((Wt=(_t=Oe==null?void 0:Oe._last)==null?void 0:_t._source)==null?void 0:Wt[wt])||0)})(K,"synthesizedSamplesEvents");A.push(Q);const xe=In(K,"synthesizedSamplesDuration");w.push(xe);const ct=Zt(xe,Se);_.push(ct),T.push(0)}else{const Q=(We=K._last)!=null&&We.totalInterFrameDelay?K.totalInterFrameDelay-K._last.totalInterFrameDelay:0;I.push(we(Q,1e3/(K.framesDecoded||30),500)),P.push(we(K.framesPerSecond,1,100)),D.push(Ie(K,"framesReceived")),O.push(Ie(K,"framesRendered")),U.push(we(K.frameHeight,1,4400)),q.push(we(K.frameWidth,1,7700));const xe=Ie(K,"totalProcessingDelay");Y.push(we(xe,1e3/(K.framesDecoded||30),12e4));const ct=Ie(K,"nackCount");$.push(ct);const Oe=Ie(K,"pliCount");G.push(Oe);const wt=Ie(K,"qpSum");Z.push(we(wt,1/(K.framesPerSecond||1),51)),te.push(we(K.framesDropped));const Dt=Ie(K,"totalFreezesDuration");fe.push(we(Dt,1e3,3e4));const _t=Ie(K,"jitterBufferEmittedCount"),Wt=Ie(K,"jitterBufferDelay");Wt&&_t?N.push(we(Wt,1e3/_t,3e4)):N.push(0);const Ci=Ie(K,"jitterBufferTargetDelay");Ci&&_t?x.push(we(Ci,1e3/_t,3e4)):x.push(0);const qi=Ie(K,"jitterBufferMinimumDelay");qi&&_t?L.push(we(qi,1e3/_t,3e4)):L.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=u.join(","),c.pl=p.join(","),c.plr=h.join(","),c.jd=f.join(","),c.fecr=R.join(","),c.retransr=g.join(","),c.baser=S.join(","),c.basel=b.join(","),c.recoverr=ue.join(","),c.alll=b.join(","),c.totalc=v.join(","),n?(c.er=_.join(","),c.aolevel=y.join(","),c.asrc=T.join(","),c.scnt=A.join(","),c.sdura=w.join(",")):(c.dm=I.join(","),c.dfps=P.join(","),c.rfps=D.join(","),c.rh=U.join(","),c.rw=q.join(","),c.fpt=Me.join(","),c.ns=$.join(","),c.pliss=G.join(","),c.aqp=Z.join(","),c.ofimax=ue.join(","),c.ofimin=ue.join(","),c.dfimax=ue.join(","),c.dfimin=ue.join(","),c.rfimax=ue.join(","),c.rfimin=ue.join(","),c.vrstutter=fe.join(","),c.cdm=N.join(","),c.tdm=x.join(","),c.pdm=L.join(","),c.ofps=O.join(","),c.dfbd=te.join(","))}catch(K){}this.log({evetid:10080,traceid:t,rmtid:e,calid:s,args:this.data2String(X({calid:s,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(s){if(s.length<=0)return;const e=[],t=[],i=[],r=[],n=[],c=[],o=[],l=[],d=[],u=[];s.forEach((h,f)=>{var S;if(!h.timestamp)return;const g=(S=h._last)!=null&&S.timestamp?h.timestamp-h._last.timestamp:1e3;e.push(we(h.currentRoundTripTime,1e3)),t.push(we(h.availableOutgoingBitrate,8,2e8)),i.push(bt(we(h.bytesSent,8,2e7),g,25e6)),r.push(bt(we(h.bytesReceived,8,2e7),g,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),u.push(""))});const p={ctm:Math.floor(s[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:r.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:u.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(X({asb:t.join(","),abms:n.join(","),vbms:c.join(",")},p))}),this.log({evetid:10081,args:this.data2String(X({},p))})}reportLoopAudioDelay(s,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:r={},AISub:n={},pub:c={},sub:o={},grtn:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const u={};let p=0;for(let g=0;g<10;g++){const S=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${g}`,b=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${g}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${g}`;if(!l.hasOwnProperty(S))break;p+=l[S]||0,p+=l[b]||0,p+=l[v]||0,u[`_gnd${g}`]=`gnd[${g}]: {${this.data2String({gnirh:l[S]||0,gnbp:l[b]||0,gnpc:l[v]||0})}}`}const h={};for(let g=0;g<10;g++){const S=`aigrtninternalrtthalf_${g}`,b=`aigrtnbeforepacer_${g}`,v=`aigrtnpacercost_${g}`;if(!i.hasOwnProperty(S))break;h[`_lgnd${g}`]=`lgnd[${g}]: {${this.data2String({gnirh:i[S]||0,gnbp:i[b]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(vt(X({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(vt(X({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:r.aAIClientScentenceId||0,quct:65535*(r.aAIClientQuestionTimestampHEAD||0)+(r.aAIClientQuestionTimestampTAIL||0),anct:65535*(r.aAIClientAnswerTimestampHEAD||0)+(r.aAIClientAnswerTimestampTAIL||0),casc:r.aAIClientSourceCost||0,camc:r.aAIClientMixerCost||0,caec:r.aAIClientEncoderCost||0,cantc:r.aIClientNetsdkThrCost||0,caqtc:r.aIClientQosThrCost||0,capc:r.aIClientPacerCost||0,cuphr:r.aIClientUpRTTHalf||0},h),{qgac:0,ldhr:l.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:n.aAILinuxReceiveCost||0,lanqc:n.aAILinuxNeteqCost||0,larsc:n.aAILinuxRemoteSourceCost||0,lapmc:n.aAILinuxPlayMixerCost||0,lapc:n.aAILinuxPlayCost||0,lsdnc:n.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:s,tpd:0,scc:r.aAIClientSourceCost||0,mxc:r.aAIClientMixerCost||0,encc:r.aAIClientEncoderCost||0,netc:r.aIClientNetsdkThrCost||0,qostc:r.aIClientQosThrCost||0,pacerc:r.aIClientPacerCost||0,uphr:r.aIClientUpRTTHalf||0},u),{agac:p,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:n.aAILinuxReceiveCost||0,nqc:n.aAILinuxNeteqCost||0,rscc:n.aAILinuxRemoteSourceCost||0,plmxc:n.aAILinuxPlayMixerCost||0,plc:n.aAILinuxPlayCost||0,dvd:0}))})}reportCumuAudioDelay(s,e){const{pub:t={},sub:i={},grtn:r={}}=e||{};let n=0;n=Object.keys(r).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(r.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,u=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!r.hasOwnProperty(d))break;o+=r[d]||0,o+=r[u]||0,o+=r[p]||0,c[`_gnd${l}`]=`gnd[${l}]: {${this.data2String({gnirh:r[d]||0,gnbp:r[u]||0,gnpc:r[p]||0})}}`}this.log({evetid:10074,args:this.data2String(vt(X({ssrc:s,tpd:n,scc:(t==null?void 0:t.aSourceCCost)||0,mxc:(t==null?void 0:t.aMixerCost)||0,encc:(t==null?void 0:t.aEncodeCCost)||0,netc:(t==null?void 0:t.netsdkThrCost)||0,qostc:(t==null?void 0:t.qosThrCost)||0,pacerc:(t==null?void 0:t.pacerCost)||0,uphr:(t==null?void 0:t.upRTTHalf)||0},c),{agac:o,dnhr:(i==null?void 0:i.downRTTHalf)||0,tsd:(i==null?void 0:i.vTotalCost)||0,rcc:0,nqc:0,rscc:0,plmxc:0,plc:0,device_delay:0,psdkt:0,pub_sdk_version:gi}))})}reportCumuVideoDelay(s,e){const{pub:t={},sub:i={},grtn:r={}}=e||{};let n=0;n=Object.keys(r).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(r.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,u=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!r.hasOwnProperty(d))break;o+=r[d]||0,o+=r[u]||0,o+=r[p]||0,c[`_gnd${l}`]=`vgnd[${l}]: {${this.data2String({vgnirh:r[d]||0,vgnbp:r[u]||0,vgnpc:r[p]||0})}}`}this.log({evetid:10075,args:this.data2String(vt(X({vssrc:s,valld:n,vcdc:(t==null?void 0:t.capDeviceCost)||0,vpec:(t==null?void 0:t.pushExtCost)||0,vcpc:(t==null?void 0:t.capPlugCost)||0,vptc:(t==null?void 0:t.prepThrCost)||0,vppc:(t==null?void 0:t.prepPlugCost)||0,vdptc:(t==null?void 0:t.dispThrCost)||0,vdppc:(t==null?void 0:t.dispPlugCost)||0,vetc:(t==null?void 0:t.vEncThrCost)||0,vepc:(t==null?void 0:t.vEncPlugCost)||0,vntc:(t==null?void 0:t.netsdkThrCost)||0,vqtc:(t==null?void 0:t.qosThrCost)||0,vvpac:(t==null?void 0:t.pacerCost)||0,vuphr:(t==null?void 0:t.upRTTHalf)||0},c),{vagac:o,vdnhr:(i==null?void 0:i.downRTTHalf)||0,vrc:(i==null?void 0:i.vAssemblyCost)||0,vstc:0,vfbc:i.vJitterBufferDelay||0,vdtc:(i==null?void 0:i.vDecPlugCost)||0,vdvpc:(i==null?void 0:i.vDecPlugCost)||0,vrtc:0,vrpc:0}))})}reportJoin(s,e,t=""){var u,p;const{start:i,rs:r=0,re:n=0}=e,c=Date.now()-i,o=n-r;let l=0;r&&(l=r-i);let d=0;n&&(d=n-r),this.log({evetid:10010,args:this.data2String({sesid:((u=this.authInfo)==null?void 0:u.sessionId)||"",joitm:c,rslt:s,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(p=this.authInfo)==null?void 0:p.userId,mgt:"cdn",cttc:l,iptc:d,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(s){this.log({evetid:20002,args:this.data2String(X({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},s))})}reportLeave(s,e,t){this.log({evetid:10020,args:this.data2String({lvetm:s,rslt:e,tid:t})})}reportPublish(s,e,t,i,r,n,c,o,l,d,u,p){this.log({evetid:s?10032:10030,calid:t,tm:p,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:r?1:0,isvss:n?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-u,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(s,e,t,i,r,n,c,o,l){const d=Date.now();this.log({evetid:s?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:d-r,jorm:l===Tt.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(s,e,t,i){var r;this.log({evetid:10040,args:this.data2String({calid:s,unpubtm:e,rslt:t,tid:i,sesid:((r=this.authInfo)==null?void 0:r.sessionId)||""})})}reportSubscribe(s,e,t,i,r,n,c,o,l,d,u){this.log({evetid:10050,calid:s,rmtid:e,tm:u,args:this.data2String(X({calid:s,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:r?1:0,isaudio:n?1:0,rslt:c,tid:o,subtm:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}reportSubscribeFirstPacket(s,e,t,i,r){this.log({evetid:s?10054:10051,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},r))})}reportSubscribeFirstFrame(s,e,t,i,r){this.log({evetid:s?10055:10052,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i},r))}),this.log({evetid:s?10058:10057,args:this.data2String(X({calid:e,rmtid:t,tckid:i},r))})}reportUnsubscribe(s,e,t,i,r){this.log({evetid:10060,calid:s,args:this.data2String({calid:s,rmtid:e,unsubtm:t,rslt:i,tid:r})})}reportMute(s,e,t){this.log({evetid:11030,args:this.data2String({calid:s,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(s,e){this.log({evetid:11040,args:this.data2String({or:s||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(s,e,t,i){this.log({evetid:11041,args:this.data2String({or:s||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(s){this.log({evetid:20074,args:this.data2String({pf:s,tckid:"sophon_camera_large"})})}reportScreenProfile(s){this.log({evetid:20074,args:this.data2String({pf:s,tckid:"sophon_screenshare"})})}reportError(s){this.log({evetid:10091,args:this.data2String({rslt:(s==null?void 0:s.code)||-1})})}reportWarning(s){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:s})})}reportRoomServerEvent(s,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:s?0:1,dr:s?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(s,e){this.log({evetid:10101,args:this.data2String({rslt:s,taskid:e})})}reportBye(s){var e;this.log({evetid:10093,args:this.data2String({rslt:s,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(s,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:s?-1:0,adm:1,adt:0,adr:s?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:s?-1:0,adm:1,adt:0,adr:s?2:0,acms:e,adrpn:t})})}reportScreen(s,e){var t,i,r,n;this.log({evetid:90013,args:this.data2String({rslt:s?-1:0,vcms:e,vde:(t=s==null?void 0:s.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:s?-1:0,vcms:e,vde:(r=s==null?void 0:s.code)!=null?r:-1,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportScreenStop(s){this.log({evetid:90019,args:this.data2String({rslt:s?s.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:s?s.code||-1:0})})}reportSwitchCamera(s){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:s,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(s,e){this.log({evetid:10201,args:this.data2String(X({tckid:s},e))})}reportSDKCreated(s){this.log({evetid:70011,createtm:Date.now()-s,tm:s})}reportJoinInvoked(s){this.log({evetid:70012,jnnonce:s.nonce||"",jntoken:s.token||"",jntm:s.timestamp||""})}reportJoinResult(s){this.log({evetid:70013,rslt:s?s.code||-1:0,dnsrslt:0})}reportSTSResult(s,e){this.log({evetid:70014,rslt:s,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(s,e,t,i,r){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:s,sei_len:e,sei_rep:t,sei_delay:i,sei_key:r})})}reportConnectionLatencyEvent(s,e,t,i,r,n,c=!1){const o={ageniid:this.getCustomField("ageniid")},l=X({tm:r||Date.now(),ntptm:n||this.ntpClock.now(),stage:s,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(l)})}log(s){s&&(s.tm=s.tm||new Date().getTime(),C.debug("[ConsoleLogger]","log",s),this.logClient.sendReport(s))}data2String(s){let e="";for(let t in s)e.length&&(e+="&"),e+=t.startsWith("_")?s[t]:`${t}=${s[t]}`;return e}}const hi=class hi extends ne{constructor(e){super();m(this,"ws");m(this,"socketStatus",0);m(this,"wsUrl","");m(this,"lastConnectStartTime",0);m(this,"connectRetryMinTimeGap",5e3);m(this,"shouldReconnect",!0);m(this,"connectRetryCount",0);m(this,"gotErr",!1);m(this,"closedByInvoke",!0);m(this,"isReconnecting",!1);m(this,"networkAvailableChecked",!0);m(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.uninitWebsocket()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){C.info(`[${hi.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&ke.isNetworkAvailable().then(t=>{t&&console.error(hi.logName,"onError, Network is available, token may be invalid")})}onClose(e){return E(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(C.info(`[${hi.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield ke.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};m(hi,"logName","Socket");let Jr=hi;const pt=class pt extends ne{constructor(e,t,i,r,n,c){super();m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"wsClient");m(this,"packageCreator");m(this,"keepAliveTimer",0);m(this,"lastKeepAliveResponseTime",0);m(this,"maxConnectRetryDuration",90);m(this,"packageCache",new Map);m(this,"isFirstConnect",!0);m(this,"aliveChecker",0);m(this,"reconnectData");m(this,"joinChannelExtraData");this.authInfo=e,this.userName=t,this.packageCreator=new Oi(e,t),this.channelProfile=i,this.clientRole=r,this.slsReporter=n,c&&(this.maxConnectRetryDuration=c),this.wsClient=new Jr,this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onWillReconnect",this.onWillReconnect.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=Ot(l,["l1ip"]);let r=this.packageCreator.createPublishPackage();r.data.users=[],r.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.2.7";o&&(o=o.split("-")[0]),n.forEach(d=>{const{codec:u,ssrc:p}=d;d.userdata=JSON.stringify({sdk_version:o,codec:u}),d.ssrc=`${p}`,c&&(d.attr={reason:"reconnect"})}),r.data.users.push(i),this.sendPackage(r)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=X(vt(X({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){C.info(`[${pt.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[Be.KEEPALIVE,Be.RECONNECT,Be.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Be.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(C.info(`[${pt.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Rt.AliRtcSdkInteractiveLive&&this.channelProfile!==Rt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==Be.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){C.warn(`[${pt.logName}] onMessage err`,t,e)}}onError(e){C.warn(`[${pt.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){C.warn(`[${pt.logName}] onConnectFail`);const e=new V(B.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){C.warn(`[${pt.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){C.warn(`[${pt.logName}] onNetworkError`);const e=new V(B.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){C.info(`[${pt.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}onWillReconnect(){this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new V(B.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{C.info(`[${pt.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==Be.KEEPALIVE&&C.info(`[${pt.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Be.JOINCHANNEL:this.onJoinResult(e);break;case Be.KEEPALIVE:this.onKeepAliveRsp();break;case Be.PUBLISH:this.onPublishResult(e);break;case Be.NOTIFYJOIN:this.onNotifyJoin(e);break;case Be.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Be.LEAVECHANNEL:this.onLeaveResult(e);break;case Be.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Be.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Be.STATUSREPORT:this.onStatusReport(e);break;case Be.BYE:this.onBye(e);break;case Be.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Be.REFRESHURL:this.onRefreshUrlResult(e);break;case Be.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new V(B.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};m(pt,"logName","RSMessageCenter");let qr=pt;var qc=Object.defineProperty,Gc=Object.getOwnPropertyDescriptor,Gr=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?Gc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&qc(s,e,r),r};const Ki=(it=class extends ne{constructor(e,t,i,r=lt.prod){super();m(this,"messageCenter");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"reconnectData");m(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=r===lt.pre?yt.pre:yt.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){C.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,i,r){return E(this,null,function*(){return new Promise((n,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new qr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var u,p,h;if(C.info(`[${it.logName}]`,"join result: ",d),o.taskretrynum=((u=this.messageCenter)==null?void 0:u.retryCount)||0,d.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(h=this.messageCenter)==null||h.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,B.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new V(B.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),C.info(`[${it.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:dt()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+ke.queryingParam(l),r)})})}leave(){return C.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,r)=>{C.info(`[${it.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:r})):t(this.handleSignalError(i,"leave error"))}),C.info(`[${it.logName}]`,"send leave request"),this.messageCenter.leave()):(C.info(`[${it.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var r;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,c,o)=>{C.info(`[${it.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(vt(X({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(r=this.authInfo.sessionId)!=null?r:""),e.callid||(e.callid=dt()),C.info(`[${it.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(r,n,c)=>{var o,l;C.info(`[${it.logName}]`,"recv role update response "+r),r===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):i(this.handleSignalError(r,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return C.info(`[${it.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",r=>{const{code:n,description:c,data:o={}}=r||{};C.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),C.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return C.info(`[${it.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(r,n)=>{r===200?t():i(new V(r,n))}),this.messageCenter.reportStatus(e)):i(new V(-1,"No messageCenter"))})}handleSignalError(e,t,i=B.ERR_INNER){return new V(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return E(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,r,n,c,o,l,d,u,p,h,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",g=>{this.emit("onNotifyJoin",g)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",g=>{this.emit("onNotifyStatus",g)}),(r=this.messageCenter)==null||r.on("onNotifyLeave",g=>{this.emit("onNotifyLeave",g)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",g=>{this.emit("onNotifyPublish",g)}),(c=this.messageCenter)==null||c.on("onBye",(g,S)=>{this.emit("onBye",g,S)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",g=>{this.emit("onReconnectSuccess",g)}),(d=this.messageCenter)==null||d.on("onReconnectFail",g=>{this.emit("onReconnectFail",g)}),(u=this.messageCenter)==null||u.on("onConnectFail",g=>{this.emit("onConnectFail",g),this.reset()}),(p=this.messageCenter)==null||p.on("onNetworkError",g=>{this.emit("onNetworkError",g)}),(h=this.messageCenter)==null||h.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",g=>{this.emit("onUnknownMessage",g)})}},m(it,"logName","RoomServerSignaling"),it);Gr([k()],Ki.prototype,"join",1),Gr([k()],Ki.prototype,"publish",1),Gr([k()],Ki.prototype,"roleUpdate",1);let Xc=Ki;var Yc=Object.defineProperty,Qc=Object.getOwnPropertyDescriptor;class Xr extends ne{constructor(e,t,i,r=lt.prod){super();m(this,"signaling");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"env",lt.prod);m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=r,this.slsReporter=i}reset(){var e;C.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,i,r,n){return this.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new V(B.ERR_JOIN_ALREADY_JOINED,"already joined")):(C.info("[signalingmanager] create signaling"),this.signaling=new Xc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),r&&(r.rs=Date.now()),this.signaling.join(e,t,i,n).then(l=>{this.authInfo=e,r&&(r.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var r;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(r=this.userName)!=null?r:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{i(n)})):i(new V(B.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(r=>{i(r)}):i(new V(-1,"no signaling"))})}setClientRole(e){return E(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const r=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),r}catch(r){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,r.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new V(B.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return E(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=X(X({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,r,n,c,o,l,d,u,p,h,f,g;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(r=this.signaling)==null||r.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(u=this.signaling)==null||u.on("onConnectFail",this.onConnectFail.bind(this)),(p=this.signaling)==null||p.on("onNetworkError",this.onNetworkError.bind(this)),(h=this.signaling)==null||h.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(g=this.signaling)==null||g.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}m(Xr,"logName","SignalingManager"),((a,s,e,t)=>{for(var i,r=t>1?void 0:t?Qc(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);t&&r&&Yc(s,e,r)})([k(H)],Xr.prototype,"publish",1);class Cn{constructor(s){m(this,"taskProfile");m(this,"encodeParam");m(this,"users",[]);m(this,"backgroundColor",0);m(this,"backgrounds",[]);m(this,"watermarks",[]);m(this,"clockWidgets",[]);m(this,"cropMode");m(this,"mediaProcessMode");this.taskProfile=s}}class kn{constructor(s,e,t){m(this,"userId");m(this,"streamType");m(this,"sourceType");this.userId=s,this.streamType=e,this.sourceType=t}}class Pn{constructor(s,e,t,i=0,r=16777215,n=Ti.NOTO_SERIF_CJKSC_REGULAR){m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.x=s,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=r,this.fontType=n}toJson(s,e){return{x:St(this.x,s),y:St(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:$r(this.fontColor),zorder:this.zOrder}}}var Dn=(a=>(a[a.NOT_DISPLAY=0]="NOT_DISPLAY",a[a.ALWAYS=1]="ALWAYS",a[a.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",a))(Dn||{});class Yr{constructor(s,e,t,i,r,n=0,c=1,o=1){m(this,"url");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"alpha");m(this,"display",1);m(this,"zOrder");this.url=s,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,this.alpha=c,this.display=o}toJson(s,e){return{url:this.url,alpha:this.alpha,display:this.display,x:St(this.x,s),y:St(this.y,e),width:St(this.width,s),height:St(this.height,e),zorder:this.zOrder}}}m(Yr,"DisplayType",Dn);class Mn{constructor(s,e,t,i,r=0,n=16777215,c=Ti.NOTO_SERIF_CJKSC_REGULAR){m(this,"text");m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.text=s,this.x=e,this.y=t,this.fontSize=i,this.zOrder=r,this.fontColor=n,this.fontType=c}toJson(s,e){return{text:this.text,x:St(this.x,s),y:St(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:$r(this.fontColor),zorder:this.zOrder}}}class Nn{constructor(s,e,t,i,r,n=0,c){m(this,"userId");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"zOrder");m(this,"sourceType");m(this,"segmentType",Ei.LiveTranscodingNoBody);m(this,"images",[]);m(this,"texts",[]);this.userId=typeof s=="number"?s.toString():s,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,c&&(this.sourceType=c)}toJson(s,e,t,i){const r={paneid:s,majorpane:0,x:St(this.x,e),y:St(this.y,t),width:St(this.width,e),height:St(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&_i[this.sourceType]?r.sourcetype=_i[this.sourceType]:r.sourcetype=_i[di.LiveTranscodingCamera],this.segmentType&&i===$i.LiveTranscodingVirtualBackground?r.segmenttype=this.segmentType:r.segmenttype=Ei.LiveTranscodingNoBody,r}}class Zc{constructor(s){m(this,"_updateables");m(this,"_useWebworker");m(this,"_inited");m(this,"_active");m(this,"_previousRAFTime");m(this,"_previousWorkerTime");m(this,"_webWorkerString");m(this,"_webWorker");m(this,"_intervalThreshold");m(this,"_rafId");this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=s&&s>0&&s<=60?1/s:.1,this._webWorkerString=`
127
+ `],{type:"text/javascript"}),t=(window.URL||window.webkitURL).createObjectURL(e);this.worker=new Worker(t);const{readable:i}=this.processor,{writable:s}=this.trackGenerator;this.worker.postMessage({type:"startRender",readable:i,writable:s,width:this.targetWidth,height:this.targetHeight,frameRate:this.targetFrameRate},[i,s])}updateOptions(e){super.updateOptions(e),this.worker&&this.worker.postMessage(X({type:"updateOptions"},e))}dispose(){try{this.processor.readable.cancel(),this.trackGenerator.writable.close()}catch(e){}}getVideoTrack(){return this.trackGenerator}}class ys{static isSupport(){return typeof HTMLCanvasElement.prototype.captureStream=="function"}static getInstance(r,e){return Va.isSupport()?new Va(r,e):xa.isSupport()?new xa(r,e):new ic(r,e)}}var Oa,Ua,sc=Object.defineProperty,rc=Object.defineProperties,ac=Object.getOwnPropertyDescriptors,Ba=Object.getOwnPropertySymbols,nc=Object.prototype.hasOwnProperty,oc=Object.prototype.propertyIsEnumerable,Rs=(a,r,e)=>r in a?sc(a,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[r]=e,As=(a,r)=>{for(var e in r||(r={}))nc.call(r,e)&&Rs(a,e,r[e]);if(Ba)for(var e of Ba(r))oc.call(r,e)&&Rs(a,e,r[e]);return a},ri=(a,r,e)=>(Rs(a,typeof r!="symbol"?r+"":r,e),e),ws={exports:{}},_s={exports:{}};function et(){if(Ua)return Oa;Ua=1,Date.now=Date.now||function(){return new Date().getTime()};var a=Date.now(),r=function(){},e={noop:r,warn:function(){var t=typeof console=="object"?console.warn:r;try{var i={warn:t};i.warn.call(i)}catch(s){return r}return t}(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:typeof window=="object"&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",daily_3:"http://arms-retcode-daily.aliyun.test/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(t){if(Object.create)return Object.create(t);var i=function(){};return i.prototype=t,new i},each:function(t,i){var s=0,n=t.length;if(this.T(t,"Array"))for(;s<n&&i.call(t[s],t[s],s)!==!1;s++);else for(s in t)if(i.call(t[s],t[s],s)===!1)break;return t},safetyCall:function(t,i,s){if(typeof t!="function")return s;try{return t.apply(this,i)}catch(n){return s}},T:function(t,i){var s=Object.prototype.toString.call(t).substring(8).replace("]","");return i?s===i:s},duration:function(){var t=Date;try{performance&&this.T(performance.now,"Function")&&(t=performance)}catch(s){t=Date}var i=t.now();return function(){return Math.round(t.now()-i)}},filterByRule:function(){var t=[].slice.call(arguments),i=t.length;if(i<2)return t[0];var s=t[i-1],n=t[0];if(!n)return"";if(!s)return n;var c=this,o=c.T(s),l=t.slice(0,i-1);return o==="Function"?c.safetyCall(s,l,n):o==="Array"?(this.each(s,function(d){l[0]=n=c.filterByRule.apply(c,[].concat(l,d))}),n):o==="Object"?n.replace(s.rule,s.target||""):n.replace(s,"")},ignoreByRule:function(t,i){if(!t||!i)return!1;if((this.isString(i)||i.source||this.T(i)==="Function")&&(i=[i]),!this.isArray(i))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var s,n=[],c=0,o=i.length;c<o;c++)if(s=i[c],this.isString(s))n.push(s.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(s&&s.source)n.push(s.source);else if(s&&this.T(s)==="Function"&&this.safetyCall(s,[t],!1)===!0)return!0;var l=new RegExp(n.join("|"),"i");return!!(n.length&&l.test&&l.test(t))},J:function(t){if(!t||typeof t!="string")return t;var i=null;try{i=JSON.parse(t)}catch(s){}return i},pick:function(t){return t===1||Math.ceil(Math.random()*t)===1},verifyConfig:function(t){if("sample"in t){var i=t.sample,s=i;i&&/^\d+(\.\d+)?%$/.test(i)&&(s=parseInt(100/parseFloat(i))),0<s&&1>s&&(s=parseInt(1/s)),s>=1&&s<=100?t.sample=s:delete t.sample}return t},on:function(t,i,s,n,c){return t.addEventListener?(c=c||!1,t.addEventListener(i,function o(l){n&&t.removeEventListener(i,o,c),s.call(this,l)},c)):t.attachEvent&&t.attachEvent("on"+i,function o(l){n&&t.detachEvent("on"+i,o),s.call(this,l)}),this},off:function(t,i,s){return s?(t.removeEventListener?t.removeEventListener(i,s):t.detachEvent&&t.detachEvent(i,s),this):this},delay:function(t,i){return i===-1?(t(),null):setTimeout(t,i||0)},ext:function(t){for(var i=1,s=arguments.length;i<s;i++){var n=arguments[i];for(var c in n)Object.prototype.hasOwnProperty.call(n,c)&&(t[c]=n[c])}return t},sub:function(t,i){var s={};return this.each(t,function(n,c){i.indexOf(c)!==-1&&(s[c]=n)}),s},uu:function(){for(var t,i,s=20,n=new Array(s),c=Date.now().toString(36).split("");s-- >0;)i=(t=36*Math.random()|0).toString(36),n[s]=t%3?i:i.toUpperCase();for(var o=0;o<8;o++)n.splice(3*o+2,0,c[o]);return n.join("")},guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var i=16*Math.random()|0;return(t==="x"?i:3&i|8).toString(16)})},seq:function(){return(a++).toString(36)},decode:function(t){try{t=decodeURIComponent(t)}catch(i){}return t},encode:function(t,i){try{t=i?encodeURIComponent(t).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(t)}catch(s){}return t},serialize:function(t){t=t||{};var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&t[s]!==void 0&&i.push(s+"="+this.encode(t[s],s==="msg"));return i.join("&")},checkAPI:function(t,i){if(!t||typeof t!="string")return!1;var s=/arms-retcode[\w-]*\.aliyuncs/.test(t);return!s&&i&&(s=/(alicdn\.com)|(mmstat\.com)/.test(t)),!s},checkAutoError:function(t){return!(!t||!t.message||/failed[\w\s]+fetch/i.test(t.message))},cutUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/\?.*$/,""):""},createFakeToString:function(t){return function(){return t+"() { [native code] }"}},checkSameOrigin:function(t,i){if(!i||!t)return!1;var s="//"+i.split("/")[2];return t===i||t.slice(0,i.length+1)===i+"/"||t===s||t.slice(0,s.length+1)===s+"/"||!/^(\/\/|http:|https:).*/.test(t)},getRandIP:function(){for(var t=[],i=0;i<4;i++){var s=Math.floor(256*Math.random());t[i]=(s>15?"":"0")+s.toString(16)}return t.join("").replace(/^0/,"1")},getSortNum:function(t){return t?(t+=1)>=1e3&&t<=9999?t:t<1e3?t+1e3:t%1e4+1e3:1e3},getRandNum:function(t){return t&&typeof t=="string"?t.length<5?this.getNum(5):t.substring(t.length-5):this.getNum(5)},getNum:function(t){for(var i=[],s=0;s<t;s++){var n=Math.floor(16*Math.random());i[s]=n.toString(16)}return i.join("")},getCurDomain:function(){return location&&location.hostname||""},getSrcType:function(t,i){var s=location&&location.host||"";if(!s)return"";var n=new URL(t).host;if(n===s)return"self";for(var c=0;c<i.length;c+=1)if(n.includes(i[c]))return"cdn";return"others"},parseFetchHeaders:function(t){if(!t)return{};var i={};try{if(typeof t.keys=="function")for(var s=t.keys(),n=s.next();!n.done;){var c=n.value;i[c]=t.get(c),n=s.next()}else i=t}catch(o){i={}}return i},parseXhrHeaders:function(t){if(!t&&typeof t!="string")return{};var i={};try{i=t.split(`\r
128
+ `).reduce(function(s,n){var c=n.split(": ");return s[c[0]]=c[1],s},{})}catch(s){i={}}return i},getQuerys:function(t){if(!t)return"";var i={},s=[],n="",c="";try{var o=[];if(t.indexOf("?")>=0&&(o=t.substring(t.indexOf("?")+1,t.length).split("&")),o.length>0)for(var l in o)n=(s=o[l].split("="))[0],c=s[1],i[n]=c}catch(d){i={}}return i},getURL:function(t){if(!t)return null;var i={},s=t.length,n=t.indexOf("://");if(n<0)return null;i.protocol=t.substring(0,n+1);var c=t.indexOf("#"),o=t.indexOf("?");c<0&&(c=s),o<0&&(o=c),i.search=t.substring(o,c).substring(0,1e3);var l=t.substring(n+3,o),d=l.indexOf("/");return d<0&&(d=l.length),i.domain=l.substring(0,d).split(":")[0],i.path=l.substring(d,l.length).substring(0,1e3),i},getResType:function(t,i){if(["script","img","other"].indexOf(t)>-1)return t;if(["video"].indexOf(t)>-1)return"media";if(["document","iframe"].indexOf(t)>-1)return"doc";var s=i?this.getURL(i):null,n=s&&s.path?s.path.lastIndexOf("."):-1,c=(n>0?s.path.substr(n+1):"").toLowerCase();if(c){if(["eot","woff","woff2","ttf"].indexOf(c)>-1)return"font";if(c==="css")return"css";if(c==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(t)>-1?"api":"others"},areInOrder:function(){for(var t=1;t<arguments.length;t+=1)if(arguments[t-1]>arguments[t])return!1;return!0},getFetchSnapshot:function(t,i,s){var n,c;try{var o=(t&&typeof t[0]!="string"?t[0].url:t[0])||"",l=(t&&typeof t[0]!="string"?t[0]:t[1])||{},d=l.method.toUpperCase()==="POST"?l.body:this.getQuerys(o);n={originApi:o,method:l.method||"unknown",params:d,response:i||"",reqHeaders:this.parseFetchHeaders(l.headers||null),resHeaders:this.parseFetchHeaders(s)},c=JSON&&JSON.stringify(n)||"{}"}catch(h){c="{}"}return c},getXhrSnapshot:function(t,i,s){if(!t||!i||!s)return{};var n,c;try{var o="";s.responseType===""||s.responseType==="text"?o=s.responseText:s.responseType==="document"&&(o=s.responseXML),n={originApi:t,method:i,params:this.getQuerys(t),response:o,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof s.getAllResponseHeaders=="function"&&s.getAllResponseHeaders()||"")},c=JSON&&JSON.stringify(n)||"{}"}catch(l){c="{}"}return c},isRobot:function(){var t=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var i=navigator.userAgent.toLowerCase(),s=0;s<t.length;s++){var n=t[s];if(i.lastIndexOf(n)>=0)return!0}}catch(c){this.warn("[arms] useragent parse error")}return!1},isFunction:function(t){return typeof t=="function"},isPlainObject:function(t){return Object.prototype.toString.call(t)==="[object Object]"},isString:function(t){return Object.prototype.toString.call(t)==="[object String]"},isArray:function(t){return Object.prototype.toString.call(t)==="[object Array]"},joinRegExp:function(t){for(var i,s=[],n=0,c=t.length;n<c;n++)i=t[n],this.isString(i)?s.push(i.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):i&&i.source&&s.push(i.source);return new RegExp(s.join("|"),"i")},reWriteMethod:function(t,i,s){if(t!==null){var n=t[i];t[i]=s(n)}},checkSDKError:function(t,i){return!(!t&&!i)&&(!!new RegExp(this.selfErrKey,"i").test(t)||!!this.ignoreByRule(i,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/]))},sdkError:function(t){return{msg:t,message:this.selfErrKey}},dealParam:function(t,i,s){var n={};try{n=this.isPlainObject(t)?this.ext({key:t.key||"default",val:t.val||t.value||s},t,{begin:Date.now()}):{key:t||"default",val:i||s,begin:Date.now()}}catch(c){this.warn("[retcode] baseLog error: "+c)}return n}};return Oa=e}var Ha,Fa,ja,$a,Is={exports:{}},Es={exports:{}};function cc(){if(ja)return Es.exports;ja=1;var a=et(),r=function(){if(Fa)return Ha;Fa=1;var s=et();return Ha=function(n,c,o){typeof n=="object"&&(n=s.serialize(n));var l=c+n+(o?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(l,o||"&post_res="):s.warn("[arms] navigator.sendBeacon not surported")}}(),e="aokcdqn3ly@e629dabd48a9933",t=function(s,n){var c;if(n.t==="error"&&(c=s.requestQueue[0])&&c.t==="error"&&n.msg===c.msg)return n.times=c.times+1,void(s.requestQueue[0]=n);if(n.t==="behavior"){var o=s.requestQueue&&s.requestQueue.length;if(o>0&&s.requestQueue[o-1].t==="behavior"){var l=n.behavior||[];s.requestQueue[o-1].behavior.concat(l)}else s.requestQueue.push(n)}else s.requestQueue.unshift(n);return s.onReady(function(){s.requestTimmer=a.delay(function(){s.clear()},s.requestQueue[0]&&s.requestQueue[0].t==="error"?3e3:-1)}),!0},i=function(s){return this.ver="1.8.36-beta.12",this._conf=a.ext({},i.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=a.seq(),this.resetPageview(),this.setConfig(s),this.rip=a.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};return i.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},i.prototype={constructor:i,onReady:function(s){return s()},getPage:function(){var s=this._conf.page;return a.safetyCall(s,[],s+"")},setPage:function(){},setConfig:function(s){s&&typeof s=="object"&&(a.verifyConfig(s),s=this.setImgUrl(s),this._conf=a.ext({},this._conf,s))},setImgUrl:function(s){var n=s.region,c=s.imgUrl;if(n){var o=a.regionMap[n];return s.imgUrl=o||a.defaultImgUrl,s}return c&&(s.imgUrl=c),s},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(s,n,c){r(s,n||this.getConfig("imgUrl"),c)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(s){s&&typeof s=="object"&&(this._common=a.ext({},this._common,s))},resetPageview:function(){this.pageview=a.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var s=this._conf,n=s&&s.setUsername;if(typeof n=="function")try{var c=n();typeof c=="string"&&(c=c.substr(0,40),this.username=c)}catch(o){a.warn("[arms] setUsername fail",o)}return this.username},getTraceId:function(){var s=this.rip,n=Date.now(),c=a.getSortNum(this.record),o=s+n+c+a.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=o,this.record=c,{"EagleEye-TraceID":o}},getUberTraceId:function(s){var n=this.rip,c=Date.now(),o=a.getSortNum(this.record),l=a.getRandNum(this._conf.pid),d=n+c+o+a.getNum(2)+l,h=d.substring(0,16);return s=s?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{"uber-trace-id":d+":"+h+":0:"+s,traceId:d}},getB3TraceId:function(s){var n=this.rip,c=Date.now(),o=a.getSortNum(this.record),l=a.getRandNum(this._conf.pid),d=n+c+o+a.getNum(2)+l,h=d.substring(0,16);return s=s?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{b3:d+"-"+h+"-"+s+"-0","X-B3-TraceId":d,"X-B3-ParentSpanId":"0","X-B3-SpanId":h,"X-B3-Sampled":s}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(s){return s?this._conf[s]:a.ext({},this._conf)},sampling:function(s){return s===1||(typeof this.sampleCache[s]=="boolean"||(this.sampleCache[s]=a.pick(s)),this.sampleCache[s])},clear:function(s){var n;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var c=this._conf&&typeof this._conf.sendRequest=="function";n=this.requestQueue.pop();)if(n.t==="res")this.postData(n,"res");else if(n.t==="error")this.postData(n,"err");else if(n.t==="api")this.postData(n,"apiSnapshot");else if(n.t==="behavior")this.postData(n,"behavior");else if(n.t==="health"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(n);else if(n.t==="resource"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var o=JSON.stringify({resource:n.resource});delete n.resource,this.sendBeacon(n,null,o)}else n.t==="resource"?this.postData(n,"resource"):this.sendRequest(n);return s&&this.clearSelf(),this},clearSelf:function(){var s;for(clearTimeout(this.Timmer),this.Timmer=null;s=this.selfQueue.pop();)this.postData(s,"err");return this},_lg:function(s,n,c,o){var l=this,d=l._conf,h=l.getPage(),p=d.ignore||{},u=p.ignoreErrors,f=p.ignoreResErrors,g=p.ignoreUrls,S=p.ignoreApis;if(l._isRobot||a.ignoreByRule(h,g)||a.ignoreByRule(a.decode(h),g)||s==="error"&&(a.ignoreByRule(n.msg,u)||a.ignoreByRule(a.decode(n.msg),u))||s==="resourceError"&&(a.ignoreByRule(n.src,f)||a.ignoreByRule(a.decode(n.src),f))||s==="api"&&(a.ignoreByRule(n.api,S)||a.ignoreByRule(a.decode(n.api),S))||!l.checkImgUrl(d.imgUrl)||!n||d.disabled||!d.pid||o===0)return l;var b=n.dl;if(delete n.dl,n=a.ext({t:s,times:1,page:h,tag:d.tag||"",release:d.release||"",environment:d.environment,begin:Date.now(),c1:d.c1,c2:d.c2,c3:d.c3},n,l.commonInfo(),l._common,{pid:d.pid,_v:l.ver,pv_id:l.pageview,username:l.getUsername(),sampling:c||1,dl:b,z:a.seq()}),a.T(d.beforeReport)==="Function")try{if(!(n=d.beforeReport(n)))return l}catch(v){return l}return o===1?t(l,n):c&&!l.sampling(c)?l:t(l,n)},_self:function(s,n,c){var o=this,l=o._conf;if(s!=="error"||!o.checkImgUrl(l.imgUrl)||!n||l.disabled||!l.pid||c&&!o.sampling(c))return o;n=a.ext({t:s,times:1,page:a.selfErrPage,tag:l.pid,begin:Date.now()},n,{pid:e,_v:o.ver,sampling:c||1,z:a.seq()});var d=o.selfQueue[0];if(d){d.times++;try{d.err&&n.err&&d.err.msg_raw&&n.err.msg_raw&&d.err.msg_raw.split("&").indexOf(n.err.msg_raw)<0&&d.err.msg_raw.length<1e3&&(d.err.msg_raw+="&"+n.err.msg_raw)}catch(h){}}else o.selfQueue.unshift(n),o.onReady(function(){o.sdkFlag&&(o.sdkFlag=!1,o.Timmer=a.delay(function(){o.clearSelf()},1e4))})},custom:function(s,n){if(!s||typeof s!="object")return this;var c=!1,o={begin:Date.now()};return a.each(s,function(l,d){return!(c=d&&d.length<=20)&&a.warn("[retcode] invalid key: "+d),o["x-"+d]=l,c}),c?this._lg("custom",o,n||1):this}},Es.exports=i,Es.exports}var Wa,Ts={exports:{}},za,Cs,Ka,ks={exports:{}};function lc(){if(Ka)return Cs;Ka=1;var a=et();return Cs=function(r,e){var t=[],i=null,s=e&&e.location&&e.location.href,n=void 0,c=null,o=function(h,p,u){if(h!==null){var f=h[p];h[p]=u(f)}},l=function(h){var p,u,f,g,S,b=[];if(!h||typeof h.tagName!="string")return"";if(b.push(h.tagName.toLowerCase()),typeof h.id=="string"&&b.push("#".concat(h.id)),typeof(p=h.className)=="string")for(u=p.split(/\s+/),S=0;S<u.length;S++)b.push(".".concat(u[S]));var v=["type","name","title","alt","data-arms-attr"];for(S=0;S<v.length;S++)f=v[S],typeof(g=h.getAttribute(f))=="string"&&b.push("[".concat(f,'="').concat(g,'"]'));return b.join("")},d=function(h,p){return function(u){if(u&&u!==c){var f;c=u;try{f=u.target}catch(S){f="<unknown>"}if(f.length!==0){var g={type:"ui.".concat(h),data:{message:function(S){if(!S||S.nodeType!==1)return"";for(var b=S||null,v=[],R=0,_=0,y="";b&&R++<5&&!((y=l(b))==="html"||R>1&&_+3*v.length+y.length>=80);)v.push(y),_+=y.length,b=b.parentNode;return v.reverse().join(" > ")}(f)},timestamp:Date.now()};h==="click"?i&&i.addBehavior(g):h==="keypress"&&(n||i&&i.addBehavior(g),clearTimeout(n),n=setTimeout(function(){n=void 0},100))}}}};a.ext(r.prototype,{addBehavior:function(h){if(this.getConfig("behavior")&&h&&typeof h=="object"){var p={},u=h.data||{};if(h.type)p=u;else{if(typeof u.name!="string"||typeof u.message!="string")return;p.name=u.name.substr(0,20),p.message=u.message.substr(0,200)}p.message&&(p.message=a.encode(p.message));var f={type:h.type||"custom",data:p||{},timestamp:h.timestamp||Date.now(),page:h.page||e&&e.location&&e.location.pathname};return t.push(f),t=t.slice(-100)}},getBehavior:function(){return t||[]},setBehavior:function(h){return h&&(t=h),t},reportBehavior:function(h){var p=this;p.getConfig("behavior")&&(p.sendBhTimer&&(clearTimeout(p.sendBhTimer),p.sendBhTimer=void 0),p.sendBhTimer=setTimeout(function(){t&&t.length>0&&(p.behavior(t),t=[],p.sendBhTimer=void 0,h&&typeof h=="function"&&h())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!i){try{(function(){if(document&&document.referrer&&document.location){var p=document.referrer,u=document.location.href;if(p!==""){var f={type:"navigation",data:{from:p,to:u}};s=u,i&&i.addBehavior(f)}}})(),e&&e.document&&e.document.addEventListener&&(e.document.addEventListener("click",d("click"),!1),e.document.addEventListener("keypress",d("keypress"),!1)),function(){if(function(){var g=e&&e.chrome,S=g&&g.app&&g.app.runtime,b="history"in e&&!!e.history.pushState&&!!e.history.replaceState;return!S&&b}()){var p=function(g,S){var b={type:"navigation",data:{from:g,to:S}};i&&i.addBehavior(b),s=S},u=e.onpopstate;e.onpopstate=function(){for(var g=arguments.length,S=new Array(g),b=0;b<g;b++)S[b]=arguments[b];var v=e.location.href;if(p(s,v),u)return u.apply(this,S)};var f=function(g){return function(){for(var S=arguments.length,b=new Array(S),v=0;v<S;v++)b[v]=arguments[v];var R=b.length>2?b[2]:void 0;return R&&p(s,String(R)),g.apply(this,b)}};o(e.history,"pushState",f),o(e.history,"replaceState",f)}}();var h=this.getConfig("enableConsole");h&&function(p){if(e&&e.console){var u=["debug","info","warn","log","error","assert"];a.isArray(p)&&(u=p);for(var f=0;f<u.length;f++){var g=u[f];g&&a.isString(g)&&e.console[g]&&typeof e.console[g]=="function"&&o(e.console,g,function(S){var b=g;return function(){for(var v=arguments.length,R=new Array(v),_=0;_<v;_++)R[_]=arguments[_];var y={type:"console",data:{level:b,message:R}};if(i&&i.addBehavior(y),b==="error")for(var A=0;A<R.length;A++){var w=R[A];w&&w.message&&w.stack&&i&&i.errorHandler(new ErrorEvent("error",{error:w,message:w.message}))}S&&Function.prototype.apply.call(S,e.console,R)}})}}}(h)}catch(p){a.warn("[arms] error in initBehavior",p)}i=this,this.hasInitBehavior=!0}return this}})},Cs}var Ja,Ps,Ga,Ds,qa,Xa,Ya,Ms,Qa,Za,en,tn,sn,Ls,rn,an,nn,on={};function Ns(){return Ja||(Ja=1,on.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),on}function dc(){return Ya||(Ya=1,Xa=function(a,r,e){var t=et(),i=function(){if(Ga)return Ps;Ga=1;var g=et(),S=Ns().TIMING_KEYS;return Ps=function(){var b=g.win||{},v=b.performance;if(!v||typeof v!="object"||typeof v.getEntriesByType!="function")return null;var R={},_=v.timing||{},y=v.getEntriesByType("resource")||[];if(R.begin=_[S[1]]||Date.now(),typeof b.PerformanceNavigationTiming=="function"){var A=v.getEntriesByType("navigation")[0];A&&(_=A)}return g.each({dom:[10,8],load:[14,1]},function(w,E){var C=_[S[w[1]]],P=_[S[w[0]]];if(C>0&&P>0){var D=Math.round(P-C);D>=0&&D<6e5&&(R[E]=D)}}),R.res=JSON.stringify(y),R},Ps}(),s=function(){if(qa)return Ds;qa=1;var g=et(),S=Ns().TIMING_KEYS;return Ds=function(){var b=g.win||{},v=b.performance;if(!v||typeof v!="object")return null;var R={},_=v.timing||{},y=Date.now(),A=1;if(typeof b.PerformanceNavigationTiming=="function"){var w=v.getEntriesByType("navigation")[0];w&&(_=w,A=2)}g.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(U,G){var Y=_[S[U[1]]],q=_[S[U[0]]];if(A===2||Y>0&&q>0){var W=Math.round(q-Y);W>=0&&W<6e5&&(R[G]=W)}});var E=b.navigator.connection,C=v.navigation||{};R.ct=E?E.effectiveType||E.type:"";var P=E&&(E.downlink||E.downlinkMax||E.bandwidth)||null;if((P=P>999?999:P)&&(R.bandwidth=P),R.navtype=C.type===1?"Reload":"Other",A===1&&_[S[16]]>0&&_[S[1]]>0){var D=_[S[16]]-_[S[1]];D>=0&&D<36e5&&(R.fpt=D)}return A===1&&_[S[1]]>0?R.begin=_[S[1]]:A===2&&R.load>0?R.begin=y-R.load:R.begin=y,R},Ds}(),n=null,c=e.documentElement,o=r.innerWidth||c.clientWidth||e.body.clientWidth,l=r.innerHeight||c.clientHeight||e.body.clientHeight,d=r.navigator.connection,h={sr:screen.width+"x"+screen.height,vp:o+"x"+l,ct:d?d.effectiveType||d.type:""},p={},u=function(g,S,b,v,R){if(S===void 0){var _,y;if(!p[g]){_=new RegExp(g+"=([^;]+)");try{y=_.exec(e.cookie)}catch(w){return t.warn("[retcode] can not get cookie:",w),null}y&&(p[g]=y[1])}return p[g]}var A=g+"="+S;A+="; path=/",b&&(A+="; max-age="+b);try{return e.cookie=A,!!e.cookie}catch(w){return t.warn("[retcode] can not set cookie: ",w),!1}},f=function(g){var S=g._conf.uid||u("_nk_")||u("_bl_uid");return S||(S=t.uu(),u("_bl_uid",S,15552e3))?S:null};return t.ext(a.prototype,{activeErrHandler:function(g){return n&&!g||(n=this),this},errorHandler:function(g){if(!g)return this;var S=g.type;if(S==="error"){var b=g.target||g.srcElement;!b||!b.tagName||g.message||g.filename||g.lineno||g.colno?this.error(g.error||{message:g.message},g):this.resourceErrorHandler(g)}else S==="unhandledrejection"&&t.T(g.reason,"Error")&&t.checkAutoError(g.reason)&&this.error(g.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(v){}return this},resourceErrorHandler:function(g){var S=this,b=g.target||g.srcElement;try{var v=S.getSrc(b),R=typeof b.tagName=="string"?b.tagName.toLowerCase():"",_=S.getXPath(b,5),y=t.getURL(v),A={src:v&&v.substring(0,1e3),node_name:R,xpath:_,res_type:t.getResType(R,v),res_name:y.path,domain:y.domain};return S._conf.enableResource&&S.fixResourceStatus&&g.timeStamp&&S.fixResourceStatus({src:v,node_name:R,res_type:t.getResType(R,v),timeStamp:g.timeStamp,domain:y.domain}),S._lg("resourceError",A),S}catch(w){return t.warn("[ARMS] resourceErrorHandler error :",w),S}},getSrc:function(g){var S=g.src||g.href;try{if(!S){var b=(typeof g.tagName=="string"?g.tagName.toLowerCase():"")==="object",v=g.getAttribute("classid")&&g.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||g.getAttribute("type")==="application/x-shockwave-flash";b&&v&&(S=g.getAttribute("data")||g.getAttribute("codebase")),S||(S=g.outerHTML||g.innerHTML)}}catch(R){S=""}return S},getXPath:function(g,S){var b=g.id?"#"+g.id:"",v=typeof g.className=="string"?"."+g.className.split(" ").join("."):"",R=(typeof g.tagName=="string"?g.tagName.toLowerCase():"")+b+v;return g.parentNode&&g.parentNode.tagName&&S-1!=0?this.getXPath(g.parentNode,S-1)+" > "+R:R},sendPerformance:function(g){var S=this;S.onReady(function(){var b=s();b&&b.load&&b.load>0&&(b.page=S.getPage(!0),g&&(b=t.ext(b,g)),b.autoSend=!0,S.performance(b))})},sendResources:function(g){var S=this;S.onReady(function(){var b=i();b&&b.load&&b.load>0&&(b.load&&b.load<=2e3||b.load&&b.load<=8e3&&Math.random()>.05||(b.page=S.getPage(!0),b.dl=location.href,g&&(b=t.ext(b,g)),S._lg("res",b,S.getConfig("sample"))))})},sendPV:function(){var g=this;g.onReady(function(){var S,b,v=(S=f(g),b=r.devicePixelRatio||1,{uid:S,dt:e.title,dl:location.href,dr:e.referrer,dpr:b.toFixed(2),de:(e.characterSet||e.defaultCharset||"").toLowerCase(),ul:c.lang,begin:Date.now()});v&&v.uid&&g._lg("pv",v,g.getConfig("pvSample"))})},commonInfo:function(){return h.uid=f(this),h.sid=function(g){if(g.session)return g.session;var S;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(S=sessionStorage.getItem("_bl_sid"))=="string"?(g.session=S,S):(S=t.uu(),g.session=S,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",S),S)}catch(b){t.warn("[ARMS] getSid error :",b)}return g.session=S=t.uu(),S}(this),h},handleUnload:function(g){var S=Date.now();if(S-this._lastUnload<200)return this;this._lastUnload=S,this.sendHealth(g),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(g){var S=this;if(!g^S.hashChangeHandler)return S;g?(S.hackHistoryState(),S.hashChangeHandler=function(b){var v=S._conf.parseHash(location.hash);v&&S.setPage(v,b!==!1)},S.stateChangeHandler=function(b){var v=S._conf.parseHash(b.detail);v&&S.setPage(v)},t.on(r,"hashchange",S.hashChangeHandler),t.on(r,"historystatechange",S.stateChangeHandler),S.hashChangeHandler(!1)):(t.off(r,"hashchange",S.hashChangeHandler),t.off(r,"historystatechange",S.stateChangeHandler),S.hashChangeHandler=null,S.stateChangeHandler=null)},initHandler:function(){var g=this;if(g.hasInitHandler)return g;var S=g._conf;return t.on(r,"beforeunload",function(){g.handleUnload(0)}),g.bindHashChange(S.enableSPA),g.activeErrHandler(!1),g.hasInitHandler=!0,g}}),t.on(r,"error",function(g){n&&n.errorHandler(g)},!1,!0).on(r,"unhandledrejection",function(g){n&&n.errorHandler(g)}),a}),Xa}function hc(){if(Qa)return Ms;Qa=1;var a=et();return Ms=function(r,e,t){function i(d,h,p){var u=0,f=d.tagName;if(f!=="SCRIPT"&&f!=="STYLE"&&f!=="META"&&f!=="HEAD"){var g=d.children?d.children.length:0;if(g>0)for(var S=d.children,b=g-1;b>=0;b--)u+=i(S[b],h+1,u>0);if(u<=0&&!p&&!(d.getBoundingClientRect&&d.getBoundingClientRect().top<n))return 0;u+=1+.5*h}return u}function s(d){for(var h=1;h<d.length;h++)if(d[h].score<d[h-1].score)return d.splice(h,1),s(d);return d}var n=e.innerHeight||0,c=[],o=null,l=0;a.ext(r.prototype,{initFmpObserver:function(d){var h=this;if(!h._conf||!h._conf.useFmp)return null;if(!e.MutationObserver)return a.warn("[retcode] first meaningful paint can not be retrieved"),h.sendPerformance(),null;a.on(e,"beforeunload",function(){h.endObserving(0,!0)});var p=e.MutationObserver;return(o=new p(function(){(function(u){var f=Date.now()-u,g=t.querySelector("body");if(g){var S=0;S+=i(g,1,!1),c.push({score:S,t:f})}else c.push({score:0,t:f})})(h._startTime)})).observe(document,{childList:!0,subtree:!0}),l=1,h.onReady(function(){h.endObserving(d)}),o},endObserving:function(d,h){var p,u,f,g=this;if(o&&l)if(g.fmpTimmer&&(clearTimeout(g.fmpTimmer),g.fmpTimmer=null),h||(p=g._startTime,u=d,(f=Date.now()-p)>u||f-(c&&c.length&&c[c.length-1].t||0)>1e3)){o.disconnect(),l=0,c=s(c);for(var S=null,b=1;b<c.length;b++)if(c[b].t>=c[b-1].t){var v=c[b].score-c[b-1].score;(!S||S.rate<=v)&&(S={t:c[b].t,rate:v})}S&&S.t>0&&S.t<36e5?g.sendPerformance({fmp:S.t}):g.sendPerformance()}else g.fmpTimmer=a.delay(function(){g.endObserving(d)},500)}})},Ms}function uc(){if(an)return _s.exports;an=1;var a=et(),r=function(){if($a)return Is.exports;$a=1;var o=et(),l=cc(),d=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],h=function(u){var f=(u.key||"default").split("::");return f.length>1?o.ext(u,{group:f[0],key:f[1]}):o.ext(u,{group:"default_group",key:f[0]})},p=function(u){var f;l.call(this,u);try{f=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch(g){f=Date.now()}return this._startTime=f,this};return p.prototype=o.createObject(l.prototype),o.ext(l.dftCon,{startTime:null}),o.ext(p.prototype,{constructor:p,_super:l,sum:function(u,f,g){try{var S=o.dealParam(u,f,1);return this._lg("sum",h(S),g)}catch(b){o.warn("[retcode] can not get parseStatData: "+b)}},avg:function(u,f,g){try{var S=o.dealParam(u,f,0);return this._lg("avg",h(S),g)}catch(b){o.warn("[retcode] can not get parseStatData: "+b)}},percent:function(u,f,g,S){try{return this._lg("percent",h({key:u,subkey:f,val:g||0,begin:Date.now()}),S)}catch(b){o.warn("[retcode] can not get parseStatData: "+b)}},msg:function(u,f){if(u&&!(u.length>180))return this.custom({msg:u},f)},error:function(u,f){if(!u)return o.warn("[retcode] invalid param e: "+u),this;arguments.length===1?(typeof u=="string"&&(u={message:u},f={}),typeof u=="object"&&(f=u=u.error||u)):(typeof u=="string"&&(u={message:u}),typeof f!="object"&&(f={}));var g=u.name||"CustomError",S=u.message||"",b=u.stack||"";f=f||{};var v=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if(o.checkSDKError(S,f.filename)){var R=/^Script error\.?$/,_=u.msg||u.message;if(o.ignoreByRule(_,R)||o.ignoreByRule(o.decode(_),R))return this;var y={msg:o.selfErrKey,err:{msg_raw:o.encode(u.msg||u.message)}};return this._self("error",y,1)}for(var A={begin:Date.now(),cate:g,msg:S&&S.substring(0,1e3),stack:b&&b.substring(0,1e3),file:o.removeUrlSearch(f.filename||""),line:f.lineno||"",col:f.colno||"",err:{msg_raw:o.encode(S),stack_raw:o.encode(b)},dl:v},w=["tag","c1","c2","c3"],E=0;E<w.length;E++){var C=w[E];f[C]&&(A[C]=f[C])}var P=(this.getConfig("ignore")||{}).ignoreErrors;return o.ignoreByRule(A.msg,P)||o.ignoreByRule(o.decode(A.msg),P)?this:(this.beforeSend&&this.beforeSend("error",A),this._lg("error",A,1))},behavior:function(u){if(u){var f=typeof u=="object"&&u.behavior?u:{behavior:u};return this.beforeSend&&this.beforeSend("behavior",f),this._lg("behavior",f,1)}},api:function(u,f,g,S,b,v,R,_,y,A,w,E,C,P,D,U){if(!u)return o.warn("[retcode] api is null"),this;if(u=typeof u=="string"?{api:u,success:f,time:g,code:S,msg:b,begin:v,traceId:R,pv_id:_,apiSnapshot:y,domain:A,flag:E,tag:C,c1:P,c2:D,c3:U}:o.sub(u,d),!o.checkAPI(u.api,!0))return this;u.code=u.code||"";var G=u.msg||"";if(G=typeof G=="string"?G.substring(0,1e3):G,u.msg=G,u.success=u.success?1:0,u.time=+u.time,u.begin=u.begin,u.traceId=u.traceId||"",u.pv_id=u.pv_id||"",u.domain=u.domain||"",u.flag=u.flag,u.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",u.apiSnapshot&&(typeof u.apiSnapshot=="object"&&(u.apiSnapshot=JSON.stringify(u.apiSnapshot)),typeof u.apiSnapshot!="string"&&delete u.apiSnapshot,u.apiSnapshot.length>2e3&&(u.apiSnapshot=u.apiSnapshot.substring(0,2e3))),w&&(u.traceOrigin=w),!u.api||isNaN(u.time))return o.warn("[retcode] invalid time or api"),this;var Y=(this.getConfig("ignore")||{}).ignoreApis;return o.ignoreByRule(u.api,Y)||o.ignoreByRule(o.decode(u.api),Y)||u.time<0?this:(this.beforeSend&&this.beforeSend("api",u),this._lg("api",u,u.success&&this.getConfig("sample"),u.flag))},speed:function(u,f,g){var S=this,b=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(u)?(f=typeof f!="number"?Date.now()-b:f>=b?f-b:f,S.speedCache=S.speedCache||{},S.speedCache[u]=f,S.speedCache.begin=b,clearTimeout(S.speedTimmer),S.speedTimmer=setTimeout(function(){g||(S.speedCache.page=S.getPage(!0)),S._lg("speed",S.speedCache),S.speedCache=null},5e3),S):(o.warn("[retcode] invalid point: "+u),S)},performance:function(u){if(u&&typeof u=="object"&&!this.hasSendPerf){var f={},g={},S=this.getConfig("autoSendPerf");if(u.autoSend&&S)return g=o.ext(this.perfData||{},u),this.hasSendPerf=!0,this._lg("perf",g,this.getConfig("sample"));if(u.autoSend&&!S)return delete u.autoSend,this.perfData?(g=o.ext(this.perfData||{},u),this.hasSendPerf=!0,this._lg("perf",g,this.getConfig("sample"))):void(this.perfData=u);for(var b in u)(/^t([1-9]|1[0])$/.test(b)||b==="ctti"||b==="cfpt")&&(f[b]=u[b]);if(u.autoSend===!0||!S&&(S||this.perfData))return u.autoSend!==!0&&S===!1&&this.perfData?(f=o.ext(this.perfData||{},f),this.hasSendPerf=!0,this._lg("perf",f,this.getConfig("sample"))):void 0;this.perfData=o.ext(this.perfData||{},f)}},resource:function(u,f){if(!u||!o.isPlainObject(u))return o.warn("[arms] invalid param data: "+u),this;var g=Object.keys(u),S=["begin","dom","load","res","dl"],b=!1;for(var v in S)if(g.indexOf(S[v])<0){b=!0;break}if(b)return o.warn("[arms] lack param data: "+u),this;var R={begin:u.begin||Date.now(),dom:u.dom||"",load:u.load||"",res:o.isArray(u.res)?JSON.stringify(u.res):JSON.stringify([]),dl:u.dl||""};return this._lg("res",R,f)},event:function(u,f){if(typeof u=="object"&&u&&u.key){var g={},S=["key","success","time","c1","c2","c3"];for(var b in u)S.indexOf(b)>-1&&(g[b]=u[b]);g.success=u.success===!1?0:1,this._lg("event",g,f)}}}),p._super=l,p._root=l,l.Reporter=p,Is.exports=p,Is.exports}(),e=function(){if(Wa)return Ts.exports;Wa=1;var o=et(),l=typeof window=="object"?window:{},d=l.__oFetch_||l.fetch;return d=typeof d=="function"?d:void 0,Ts.exports=function(h,p){var u=-1;typeof h=="object"&&(u=h.z,h=o.serialize(h));var f=p+h;if(d)return d(f,{method:"HEAD",mode:"no-cors"}).catch(o.noop);if(l.document&&l.document.createElement){var g="__request_hold_"+u,S=l[g]=new Image;S.onload=S.onerror=function(){l[g]=void 0},S.src=f,S=null}},Ts.exports}(),t=function(){if(za)return ks.exports;za=1;var o=et(),l=typeof window=="object"?window:{},d=l.__oXMLHttpRequest_||l.XMLHttpRequest;return d=typeof d=="function"?d:void 0,ks.exports=function(h,p){try{var u=new d;u.open("POST",p,!0),u.setRequestHeader("Content-Type","text/plain"),u.send(JSON.stringify(h))}catch(f){o.warn(`[retcode] Failed to log, exception is :
129
+ `+f)}},ks.exports}(),i=a.win,s=i.document,n=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,c=function(o){var l=this;return r.call(l,o),l._initialPage=o.page&&a.safetyCall(o.page,[],o.page+"")||null,l._isRobot=a.isRobot(),l._health={errcount:0,apisucc:0,apifail:0},l.beforeSend=function(d,h){d==="error"?l._health.errcount++:d==="api"&&l._health[h.success?"apisucc":"apifail"]++},o.enableInstanceAutoSend!==!1&&(l.initHandler(),l.initHook(),l.initFmpObserver(1e4),l._conf&&l._conf.behavior&&typeof l.initBehavior=="function"&&l.initBehavior(),l._conf&&l._conf.enableResource&&typeof l.initResource=="function"&&l.initResource()),Object.defineProperty&&i.addEventListener&&Object.defineProperty(l,"pipe",{set:l.sendPipe}),l};return c.prototype=a.createObject(r.prototype),a.ext(r._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(o){return(o?a.cutUrlSearch(o.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(o){if(!o||typeof o!="object")return{};var l=o.code,d=o.msg||o.message||o.subMsg||o.errorMsg||o.ret||o.errorResponse||"";return typeof d=="object"&&(l=l||d.code,d=d.msg||d.message||d.info||d.ret||JSON.stringify(d)),{msg:d,code:l,success:!0}}}),a.ext(c.prototype,{constructor:c,_super:r,onReady:function(o){var l=this;if(l.hasReady)return o();s.readyState==="complete"?(l.hasReady=!0,o()):a.on(i,"load",function(){l.hasReady=!0,o()},!0)},getPage:function(o){var l=this._conf,d=l.page,h=location,p=h.host+h.pathname;return d&&!o?a.safetyCall(d,[],d+""):this._initialPage||a.filterByRule(l.ignoreUrlCase?p.toLowerCase():p,h.href,l.ignoreUrlPath?l.ignoreUrlPath:l.urlHelper)},setPage:function(o,l){var d=this,h=d.prevPage;if(l!==!1){if(!o||o===h)return d;d.prevPage=o,clearTimeout(d.sendPVTimmer),d.handleUnload(1),d.resetPageview(),d.sendPVTimmer=setTimeout(function(){d.sendPV()},10)}else d.prevPage=o;return d._conf.page=o,d},setConfig:function(o,l){if(o&&typeof o=="object"){a.verifyConfig(o),o=this.setImgUrl(o);var d=this._conf;if(this._conf=a.ext({},d,o),!l){var h="disableHook";h in o&&d[h]!==o[h]&&(o[h]?this.removeHook():this.addHook()),(h="enableSPA")in o&&d[h]!==o[h]&&this.bindHashChange(o[h])}}},sendRequest:function(o){e(o,this.getConfig("imgUrl"))},postData:function(o,l){var d={};d[l]=o[l],delete o[l];var h="";typeof o=="object"&&(h=a.serialize(o)),t(d,this.getConfig("imgUrl")+h+"&post_res=")},sendPipe:function(o){var l=this;if(!o||!o.length)return l;try{if(a.T(o[0])==="Array")return a.each(o,function(h){return l.sendPipe(h)});if(a.T(o)!=="Array")return l;var d=o.shift();if(!n.test(d))return l;l[d].apply(l,o)}catch(h){return a.warn("[retcode] error in sendPipe",h),l}},sendHealth:function(){var o=a.ext({},this._health);o.healthy=o.errcount>0?0:1,o.begin=Date.now();var l=o.begin-this.sBegin;o.stay=l,this._lg("health",o,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(o){o=a.ext({pid:this._conf.pid},o);var l=this.__proto__.constructor(o);return o.page&&l.sendPV(),l}}),lc()(c,i),dc()(c,i,s),hc()(c,i,s),(en||(en=1,Za=function(o,l){var d=et(),h=null,p=d.getCurDomain(),u=function(v,R,_,y,A,w,E,C,P,D,U,G,Y){var q=d.J(A)||null,W=d.safetyCall(R,[q,y],null);if(!W)return!1;var Z=W.code||w,te=!("success"in W)||W.success;v.api(_,te,E,Z,W.msg,C,P,D,te?{}:U,p,G,Y)},f="fetch",g="__oFetch_",S="__oXMLHttpRequest_",b="XMLHttpRequest";return d.ext(o.prototype,{removeHook:function(v,R){return h&&(R||this===h)?(l[g]&&(l[f]=l[g],delete l[g]),l[S]&&(l[b]=l[S],delete l[S]),h=null,this):this},addHook:function(v){return!v&&h||(h||(function(){if(typeof l[f]=="function"){var R=l[f];l[g]=R,l[f]=function(_,y){var A=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),w=h;if(!w||!w.api||y&&(y.method==="HEAD"||y.mode==="no-cors"))return R.apply(l,A);y||(y={});var E=Date.now(),C=w._conf,P=d.duration(),D=(_&&typeof _!="string"?_.url:_)||"",U=D;D=d.cutUrlSearch(D);var G=(C.ignore||{}).ignoreApis,Y=C.parseTraceId;if(!d.checkAPI(D,!0)||d.ignoreByRule(D,G))return R.apply(l,A);D=d.filterByRule(D,U,C.ignoreApiPath?C.ignoreApiPath:C.apiHelper);var q=C.enableLinkTrace,W="",Z="",te=w.getConfig("pid"),be=null,L=w.getConfig("sample"),x=w.getConfig("linkType"),N=1;if(L&&!w.sampling(L)&&(N=0),q){var V="";try{V=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(pe){V=""}var ue=d.checkSameOrigin(U,V);if(w.getConfig("enableApiCors")||ue)if(_&&typeof _!="string")try{if(A[0].headers&&typeof A[0].headers.get=="function"&&typeof A[0].headers.append=="function")switch(x){case"arms":var Le=A[0].headers.get("EagleEye-TraceID"),J=A[0].headers.get("EagleEye-SessionID"),ve=A[0].headers.get("EagleEye-pAppName");Le?W=Le:(W=w.getTraceId()["EagleEye-TraceID"],A[0].headers.append("EagleEye-TraceID",W)),J?Z=J:(Z=w.getPageviewId()["EagleEye-SessionID"],A[0].headers.append("EagleEye-SessionID",Z)),ve||A[0].headers.append("EagleEye-pAppName",te);break;case"b3":var xe=A[0].headers.get("X-B3-TraceId");if(xe)W=xe;else{var Ee=w.getB3TraceId(N);A[0].headers.append("X-B3-TraceId",Ee["X-B3-TraceId"]),A[0].headers.append("X-B3-ParentSpanId",Ee["X-B3-ParentSpanId"]),A[0].headers.append("X-B3-SpanId",Ee["X-B3-SpanId"]),A[0].headers.append("X-B3-Sampled",Ee["X-B3-Sampled"]),A[0].headers.append("X-Request-ID",d.guid()),W=Ee["X-B3-TraceId"]}Z=w.pageview;break;default:var Me=A[0].headers.get("uber-trace-id");Me?W=Me.split(":")[0]:(Me=w.getUberTraceId(N),A[0].headers.append("uber-trace-id",Me["uber-trace-id"]),W=Me.traceId),Z=w.pageview}}catch(pe){d.warn(`[retcode] fetch failed to set header, exception is :
130
+ `+pe)}else switch(y.headers=y.headers?y.headers:{},x){case"arms":y.headers["EagleEye-TraceID"]?W=y.headers["EagleEye-TraceID"]:(W=w.getTraceId()["EagleEye-TraceID"],y.headers["EagleEye-TraceID"]=W),y.headers["EagleEye-SessionID"]?Z=y.headers["EagleEye-SessionID"]:(Z=w.getPageviewId()["EagleEye-SessionID"],y.headers["EagleEye-SessionID"]=Z),y.headers["EagleEye-pAppName"]||(y.headers["EagleEye-pAppName"]=te);break;case"b3":if(y.headers["X-B3-TraceId"])W=y.headers["X-B3-TraceId"];else{var ye=w.getB3TraceId(N);y.headers["X-B3-TraceId"]=ye["X-B3-TraceId"],y.headers["X-B3-ParentSpanId"]=ye["X-B3-ParentSpanId"],y.headers["X-B3-SpanId"]=ye["X-B3-SpanId"],y.headers["X-B3-Sampled"]=ye["X-B3-Sampled"],y.headers["X-Request-ID"]=d.guid(),W=ye["X-B3-TraceId"]}Z=w.getPageviewId()["EagleEye-SessionID"];break;default:if(y.headers["uber-trace-id"])W=y.headers["uber-trace-id"].split(":")[0];else{var Te=w.getUberTraceId(N);y.headers["uber-trace-id"]=Te["uber-trace-id"],W=Te.traceId}Z=w.getPageviewId()["EagleEye-SessionID"]}}return R.apply(l,A).then(function(pe){if(!w||!w.api)return pe;try{if(!pe||typeof pe.clone!="function")return pe;var Ne=pe.clone(),we=Ne.headers;if(we&&typeof we.get=="function"){var Xe=we.get("content-type");if(Xe&&!/(text)|(json)/.test(Xe))return pe;if(!W){var dt=d.parseFetchHeaders(we);typeof dt=="object"&&dt["eagleeye-traceid"]&&(W=dt["eagleeye-traceid"],be="response")}}var le=P();return Ne.text().then(function(ne){if(!W&&d.isFunction(Y)){var ie=Y(Ne,ne);ie&&d.isString(ie)&&(W=ie)}var Re=d.getFetchSnapshot(A,ne,we);Ne.ok?u(w,C.parseResponse,D,U,ne,Ne.status||200,le,E,W,Z,Re,be,N):(w.api(D,!1,le,Ne.status||404,Ne.statusText,E,W,Z,Re,p,be,N),C.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:Ne.url,res_type:"api"}))}),pe}catch(ne){return d.warn("[ARMS] fetch response error :",ne),pe}}).catch(function(pe){if(!w||!w.api)throw pe;var Ne=P();throw w.api(D,!1,Ne,pe.name||"Error",pe.message,E,W,Z,{},p),C.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:U,res_type:"api"}),pe})},l[f].toString=d.createFakeToString(f)}}(),function(){if(typeof l[b]=="function"){var R,_=l[b];l[S]=_;var y=function(A){var w=new _(A),E=h;if(!E||!E.api||!w.addEventListener)return w;var C,P,D,U,G=w.send,Y=w.open,q=w.setRequestHeader,W=E._conf,Z=(W.ignore||{}).ignoreApis,te=W.parseTraceId,be=E.getConfig("enableLinkTrace"),L="",x="",N="",V=null,ue=E.getConfig("sample"),Le=E.getConfig("linkType"),J=1;return ue&&!E.sampling(ue)&&(J=0),w.open=function(ve,xe){R=ve;var Ee=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);Y.apply(w,Ee),U=xe||"",D=d.cutUrlSearch(U);var Me=!d.checkAPI(D,!0)||d.ignoreByRule(D,Z);if(D=D?d.filterByRule(D,U,W.ignoreApiPath?W.ignoreApiPath:W.apiHelper):"",!Me&&be){var ye="";try{ye=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(we){ye=""}var Te=d.checkSameOrigin(U,ye);if((E.getConfig("enableApiCors")||Te)&&q&&typeof q=="function")switch(Le){case"arms":L=E.getTraceId()["EagleEye-TraceID"],q.apply(w,["EagleEye-TraceID",L]),x=E.getPageviewId()["EagleEye-SessionID"],q.apply(w,["EagleEye-SessionID",x]),N=E.getConfig("pid"),q.apply(w,["EagleEye-pAppName",N]);break;case"b3":var pe=E.getB3TraceId(J);q.apply(w,["X-B3-TraceId",pe["X-B3-TraceId"]]),q.apply(w,["X-B3-ParentSpanId",pe["X-B3-ParentSpanId"]]),q.apply(w,["X-B3-SpanId",pe["X-B3-SpanId"]]),q.apply(w,["X-B3-Sampled",pe["X-B3-Sampled"]]),q.apply(w,["X-Request-ID",d.guid()]),L=pe["X-B3-TraceId"],x=E.getPageviewId()["EagleEye-SessionID"];break;default:var Ne=E.getUberTraceId(J);q.apply(w,["uber-trace-id",Ne["uber-trace-id"]]),L=Ne.traceId,x=E.getPageviewId()["EagleEye-SessionID"]}}},w.send=function(){C=Date.now(),P=d.duration();var ve=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);G.apply(w,ve)},d.on(w,"readystatechange",function(){if(D&&w.readyState===4){var ve=P(),xe=d.getXhrSnapshot(U,R,w);if(!L){var Ee=d.parseXhrHeaders(typeof w.getAllResponseHeaders=="function"&&w.getAllResponseHeaders()||"");typeof Ee=="object"&&Ee["eagleeye-traceid"]&&(L=Ee["eagleeye-traceid"],V="response")}if(!L&&d.isFunction(te)){var Me=te(w);Me&&d.isString(Me)&&(L=Me)}if(w.status>=200&&w.status<=299){var ye=w.status||200;if(typeof w.getResponseHeader=="function"){var Te=w.getResponseHeader("Content-Type");if(Te&&!/(text)|(json)/.test(Te))return}w.responseType&&w.responseType!=="text"?E.api(D,!0,ve,ye,"",C,L,x,{},p,V,J):u(E,W.parseResponse,D,U,w.responseText,ye,ve,C,L,x,xe,V,J)}else E.api(D,!1,ve,w.status||"FAILED",w.statusText,C,L,x,xe,p,V,J),W.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:w.responseURL||U,res_type:"api"})}}),w};y.prototype=_.prototype,d.each(Object.keys(_),function(A){y[A]=_[A]}),l[b]=y,l[b].toString=d.createFakeToString(b)}}()),h=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}}),o}),Za)(c,i),(sn||(sn=1,tn=function(o,l){var d=et(),h=l.history||{},p=l.document,u=function(g,S){var b;l.CustomEvent?b=new CustomEvent(g,{detail:S}):((b=p.createEvent("HTMLEvents")).initEvent(g,!1,!0),b.detail=S),l.dispatchEvent(b)},f=function(g){var S=h[g];typeof S=="function"&&(h[g]=function(b,v,R){var _=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),y=location.href,A=S.apply(h,_);if(!R||typeof R!="string"||R===y)return A;try{var w=y.split("#"),E=R.split("#"),C=d.cutUrlSearch(w[0]),P=d.cutUrlSearch(E[0]),D=w[1]&&w[1].replace(/^\/?(.*)/,"$1"),U=E[1]&&E[1].replace(/^\/?(.*)/,"$1");D!==U?u("historystatechange",U):C!==P&&u("historystatechange",P)}catch(G){d.warn("[retcode] error in "+g+": "+G)}return A},h[g].toString=d.createFakeToString(g))};d.ext(o.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(f("pushState"),f("replaceState"),this.hasHackedHistoryState=!0),this}})}),tn)(c,i),function(){if(rn)return Ls;rn=1;var o=et(),l=Ns().TIMING_KEYS;return Ls=function(d,h){function p(g,S,b){if(g instanceof h.PerformanceResourceTiming&&g.initiatorType){var v=o.getResType(g.initiatorType,g.name),R=S.resourceTypes||[],_=(S.ignore||{}).ignoreResources;if(v&&R.includes(v)&&!o.ignoreByRule(g.name,_)&&!o.ignoreByRule(o.decode(g.name),_)){var y=g[l[0]],A=g[l[1]],w=g[l[2]],E=g[l[3]],C=g[l[4]],P=g[l[5]],D=g[l[6]],U=g[l[7]],G=g[l[8]],Y=g[l[18]],q=g[l[19]];if(!b.has(g)&&(!o.areInOrder(y,A,w,E,C,P,D,U,G)||y>U))return;if(Y<y&&(Y=y),q<y&&(q=A),o.areInOrder(y,Y,q,A))return{domain:o.getURL(g.name).domain,res_type:v,src_type:o.getSrcType(g.name,S.cdnHostList),success:1,size:Math.round(g.decodedBodySize),duration:Math.round(g.duration),timeStamp:g.responseEnd,timing:g}}}}var u="_resource-"+Date.now(),f="_resource_error-"+Date.now();o.ext(d.prototype,{initResource:function(){var g=this,S=h.performance,b=h.PerformanceObserver;if(g[f]||(g[f]=new WeakMap),!S||!b||typeof S!="object"||typeof S.getEntriesByType!="function")return null;var v=S.getEntriesByType("resource")||[];return setTimeout(function(){g.setResource(v)},10),new b(function(R){setTimeout(function(){g.setResource(R.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(g.resourceComboReport.bind(g),5e3)}),g},setResource:function(g){var S=this._conf,b=this[f];if(o.isArray(g)&&g.length){this[u]||(this[u]={});for(var v=this[u],R=0,_=g.length;R<_;R+=1){var y=g[R];if(o.checkAPI(y.name,!1)){var A=p(y,S,b);if(A){var w=A.res_type+"-"+A.domain;w in v||(v[w]=[]),v[w].push(A)}}}return this}},fixResourceStatus:function(g){var S=h.performance;if(!S||typeof S.getEntriesByName!="function")return null;var b=this[f];if(!g.src||!o.checkAPI(g.src,!1))return this;var v=g.timeStamp||S.now(),R=S.getEntriesByName(g.src,"resource");return o.each(R,function(_){b.has(_)||v-_.responseEnd<100&&b.set(_,{success:0})}),this},resourceComboReport:function(){var g=this[u]||{},S=this._conf.resourceSlow||2e3,b=this[f];this[u]={};var v=Object.keys(g);if(v.length!==0){var R=[];o.each(v,function(w){var E=g[w],C={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};o.each(E,function(P){var D=P.timing||{},U=b.get(P.timing),G=U?U.success:1,Y=P.duration>S?1:0;C.domain=P.domain,C.res_type=P.res_type,C.src_type=P.src_type,C.count+=1,C.duration+=P.duration,C.size+=P.size,G||(C.err_count+=1,C.err_duration+=P.duration),Y&&(C.slow_count+=1,C.slow_duration+=P.duration);try{var q=JSON.parse(JSON.stringify(D));q.success=G,q.resourceSlow=S,q.isSlow=Y,C.timings.push(q)}catch(W){}}),C.count&&(C.size=Math.round(C.size/C.count),C.duration=Math.round(C.duration/C.count)),C.slow_count&&(C.slow_duration=Math.round(C.slow_duration/C.slow_count)),C.err_count&&(C.err_duration=Math.round(C.err_duration/C.err_count)),C.timings.length>20&&(C.timings.sort(function(P,D){return D.duration-P.duration}),C.timings.length=20),C.timings=encodeURIComponent(JSON.stringify(C.timings)),R.push(C)});var _={_combo:1,resource:JSON.stringify(R)},y=h.navigator.connection;_.ct=y?y.effectiveType||y.type:"";var A=y&&(y.downlink||y.downlinkMax||y.bandwidth)||null;(A=A>999?999:A)&&(_.bandwidth=A),this._lg("resource",_,this.getConfig("sample"))}}})},Ls}()(c,i),c._super=r,c._root=r._root,r.Browser=c,_s.exports=c,_s.exports}var pc={getArmsLogger:function(){return function(){if(nn)return ws.exports;function a(s,n){var c=r[t]=new e(s);c.sendPipe(n);var o=c._conf;return o.autoSendPv!==!1&&c.sendPV(),o&&o.useFmp||c.sendPerformance(),o&&o.sendResource&&c.sendResources(),r[i]=!0,c}nn=1;var r=window,e=r.BrowserLogger=uc(),t=et().key,i="__hasInitBlSdk";return e.singleton=function(s,n){return r[i]?r[t]:a(s,n)},e.createExtraInstance=function(s){s&&typeof s=="object"&&s.enableInstanceAutoSend!==!0&&(s.enableInstanceAutoSend=!1);var n=new e(s),c=n._conf;return c.enableInstanceAutoSend&&(c.autoSendPv!==!1&&n.sendPV(),c&&c.useFmp||n.sendPerformance(),c&&c.sendResource&&n.sendResources()),n},typeof window=="object"&&window.navigator&&r[t]&&(e.bl=function(){if(r[i])return r[t];var s={},n=[];return t in r&&(s=r[t].config||{},n=r[t].pipe||[]),a(s,n)}()),ws.exports=e,ws.exports}()}};const cn="https://arms-retcode.aliyuncs.com/r.png?",ln="https://arms-retcode-sg.aliyuncs.com/r.png?",dn="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",hn="e1iftji1w7@7ec1cef2cc88733",un="e1iftji1w7@10a06d1ec260adc",pn="e1iftji1w7@10a06d1ec260adc",xs={cn:{reportUrl:cn,pid:hn},"cn-hangzhou":{reportUrl:cn,pid:hn},sg:{reportUrl:ln,pid:un},"ap-southeast-1":{reportUrl:ln,pid:un},usw:{reportUrl:dn,pid:pn},"us-west-1":{reportUrl:dn,pid:pn}},mc=a=>!!Object.isExtensible(a)&&(r=>Object.prototype.toString.call(r).slice(8,-1))(a)==="Object";function mn(a,r){if(typeof a!="string")return r;if(gn(a,r))return a;const e=a.indexOf(`
131
+ `);return e<0?`${a}${r}`:`${a.slice(0,e)}${r}${a.slice(e)}`}function gn(a,r){if(typeof a!="string")return!1;const e=a.indexOf(r);if(e<0)return!1;const t=a.indexOf(`
132
+ `);return t<0||e<t}function Bt(a,r,e){return typeof a=="function"?function(t,i,s){if(Reflect.get(t,"__v_skip")===!0)return t;const n={MediaboxWrapperFunctionApply(c,o,l){let d;try{d=Reflect.apply(c,o,l)}catch(h){throw s(h),h}return Bt(d,i,s)},MediaboxWrapperFunctionGet(c,o){const l=Object.getOwnPropertyDescriptor(c,o);return!l||l.writable||l.configurable?Bt(c[o],i,s):c[o]},MediaboxWrapperClassConstructor(c,o){let l;try{l=new c(...o)}catch(d){throw s(d),d}return Bt(l,i,s)}};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{apply:n.MediaboxWrapperFunctionApply,get:n.MediaboxWrapperFunctionGet,construct:n.MediaboxWrapperClassConstructor})}(a,r+1,e):a instanceof Promise?a.then(t=>Bt(t,r+1,e)).catch(t=>(e(t),Promise.reject(t))):Array.isArray(a)?(a.forEach((t,i)=>{a[i]=Bt(t,r+1,e)}),a):(t=>t!==null&&typeof t=="object")(a)&&mc(a)?function(t,i,s){var n;if(Reflect.get(t,"__v_skip")===!0)return t;const c=[],o=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors((n=Object.getPrototypeOf(t))!=null?n:{}):{};for(const d of Object.keys(o))o[d].get&&c.push(d);const l={MediaboxWrapperObjectGetter(d,h){if(typeof h=="string"&&c.indexOf(h)>-1){let u;try{u=d[h]}catch(f){throw s(f),f}return Bt(u,i,s)}if(i>10)return d[h];const p=Reflect.getOwnPropertyDescriptor(d,h);return!p||p.writable||p.configurable?Bt(d[h],i,s):d[h]},MediaboxWrapperObjectSetter:(d,h,p)=>(d[h]=Bt(p,i,s),!0)};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{get:l.MediaboxWrapperObjectGetter,set:l.MediaboxWrapperObjectSetter})}(a,r+1,e):a}function Vs(a){return typeof a=="string"&&(a.indexOf("g.alicdn.com/apsara-media-")>-1||a.indexOf("g.alicdn.com/thor-server")>-1||a.indexOf("MediaboxWrapper")>-1)}function fn(a,r){if(Reflect.get(a,"__v_skip")===!0)return a;const e={MediaboxWrapperShallowGet(t,i){const s=t[i];return typeof s=="function"?e.MediaboxWrapperShallowMethod(s,t):s},MediaboxWrapperShallowMethod:(t,i)=>({MediaboxWrapperShallowApply(...s){let n;try{n=t.apply(i,s)}catch(c){throw r(c),c}return n instanceof Promise?n.catch(c=>(r(c),Promise.reject(c))):n}}).MediaboxWrapperShallowApply};return Object.defineProperty(a,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(a,{get:e.MediaboxWrapperShallowGet})}class bn extends Error{constructor(r){super(r),this.name="MQTError"}}let gc=1;class Os{constructor(r){var e,t;ri(this,"armsLogger"),ri(this,"isReady",!1),ri(this,"isDestroyed",!1),ri(this,"options"),ri(this,"queue",[]),ri(this,"marker"),ri(this,"helper",{MediaboxWrapperQueue:i=>new bn(i),MediaboxWrapperInitiative:i=>new bn(i)}),this.options=((i,s)=>rc(i,ac(s)))(As({},r),{region:r.deferRegionSet?void 0:(e=r.region)!=null?e:"cn",env:(t=r.env)!=null?t:"prod"}),this.marker=`-${gc++}-`,this.initArmsLogger()}static get version(){return"0.31.0"}initArmsLogger(r){const{region:e,env:t,disabled:i}=this.options;if(i||this.armsLogger)return;if(r&&!e)throw new Error("region is required");if(!e)return;if(!xs[e])throw new Error(`region ${e} is not supported`);const s=pc.getArmsLogger();this.armsLogger=s.createExtraInstance({enableInstanceAutoSend:!0,pid:xs[e].pid,tag:this.options.businessName,release:`${this.options.businessName}_${this.options.version}`,imgUrl:xs[e].reportUrl,behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:n=>{var c;if(this.isDestroyed||gn(n.stack,this.marker)||n.t!=="pv"&&n.t!=="error"&&n.t!=="health")return!1;if(n.c1=(c=this.options.cid)!=null?c:window.location.host,n.c2=Os.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(function(o){return typeof o=="string"&&(o.indexOf("g.alicdn.com/apsara-media-")>-1||o.indexOf("g.alicdn.com/thor-server")>-1)}(n.file)||Vs(n.stack)){let o=n;return this.options.beforeSend&&(o=this.options.beforeSend(n)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return n}})}wrap(r){return this.options.disabled||typeof Proxy=="undefined"?r:Bt(r,0,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Vs(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=mn(e.stack,this.marker))})}shallowWrapClass(r){return this.options.disabled||typeof Proxy=="undefined"?r:function(e,t){if(Reflect.get(e,"__v_skip")===!0)return e;const i=n=>n instanceof e?fn(n,t):n,s={MediaboxWrapperStaticGet(n,c){const o=n[c];return typeof o=="function"&&c!=="prototype"?s.MediaboxWrapperStaticMethod(o,n):o},MediaboxWrapperStaticMethod(n,c){const o={MediaboxWrapperStaticApply(l,d,h){let p;try{p=n.apply(c,h)}catch(u){throw t(u),u}return p instanceof Promise?p.then(u=>i(u)).catch(u=>(t(u),Promise.reject(u))):i(p)},MediaboxWrapperStaticConstruct(l,d,h){let p;try{p=Reflect.construct(n,d,h)}catch(u){throw t(u),u}return i(p)}};return new Proxy(n,{apply:o.MediaboxWrapperStaticApply,construct:o.MediaboxWrapperStaticConstruct})},MediaboxWrapperConstruct(n,c,o){let l;try{l=Reflect.construct(n,c,o)}catch(d){throw t(d),d}return fn(l,t)}};return Object.defineProperty(e,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(e,{get:s.MediaboxWrapperStaticGet,construct:s.MediaboxWrapperConstruct})}(r,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Vs(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=mn(e.stack,this.marker))})}updateOptions(r){this.options=As(As({},this.options),r)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(r=>{var e;(e=this.armsLogger)==null||e.error(this.helper.MediaboxWrapperQueue(r.msg),{filename:r.file,lineno:r.line,colno:r.col})})}report(r,e){var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperInitiative(r),e)}destroy(){this.isDestroyed=!0}}class fc extends oe{constructor(){super();m(this,"audioContext");m(this,"stream");m(this,"sourceNode");m(this,"analyser");this.audioContext=bt.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(s,n,c,o,l){let d,h=o,p=0;const u=s.createAnalyser();u.fftSize=256;const f=new Uint8Array(u.frequencyBinCount);n.connect(u),u.connect(c);const g=()=>{d&&window.clearInterval(d)},S=()=>{s.state==="suspended"&&s.resume(),d=window.setInterval(()=>{u.getByteFrequencyData(f);let b=Math.round(f.reduce((v,R)=>v+R)/f.length);b=Math.min(100,b),p=b,l&&l(b)},h)};return S(),{updateInterval:b=>{g(),h=b,S()},getLevel:()=>p,dispose:()=>{g(),n.disconnect(),u.disconnect()}}}(this.audioContext,this.sourceNode,i,t,s=>{this.emit("audioLevel",s)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class Sn extends oe{constructor(e,t,i,s){super();m(this,"uid");m(this,"name");m(this,"rtsManager");m(this,"callId","");m(this,"audioLevelMonitor");m(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=s,this.audioLevelMonitor=new fc}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=De.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class vn{static getCurrentStatus(r){let e=0;r.micOpen&&(e+=1),r.micInterrupted&&(e+=2),r.cameraOpen&&(e+=4),r.screenShare&&(e+=128),r.audioDisable&&(e+=8),r.videoDisable&&(e+=16),r.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(r){let e=parseInt(r,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}const k=(a,r)=>(e,t,i)=>{const s=i.value;return i.value=function(...n){var p;const c=this.instanceId||this._loggerInstanceId;c&&T.setActiveInstance(c);const o=`[${this.logName||((p=e.constructor)==null?void 0:p.logName)||""}]`,l=Date.now();let d=[];if(a)try{d=a(n)}catch(u){}T.interface(o,t,...d);const h=s.apply(this,n);return Promise.resolve(h).then(u=>u).catch(u=>u).then(u=>{var b;c&&T.setActiveInstance(c);let f="";const g=u instanceof Error,S=g&&((b=e.constructor)==null?void 0:b.logError);if(r||g){if(S)f=u;else if(g)f=u.message||"";else{if(!r)return;if(u===void 0)f="";else try{f=r(u)}catch(v){}}T.interfaceResult(o,t,!(g&&S),Date.now()-l+"ms",f)}}),h},i},H=a=>a,yn="customVideoProfile",Rn="customScreenProfile",Us={width:1280,height:720,frameRate:30,maxBitrate:2e3},An={width:1920,height:1080,frameRate:30,maxBitrate:2600};var _i=(a=>(a[a.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",a[a.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",a[a.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",a[a.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",a[a.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",a[a.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",a[a.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",a[a.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",a[a.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",a[a.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",a[a.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",a[a.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",a[a.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",a))(_i||{});const bc={1e4:He.AliEngineLocalDeviceExceptionTypeUnknown,2e4:He.AliEngineLocalDeviceExceptionTypeUnknown,10001:He.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:He.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:He.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:He.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:He.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:He.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:He.AliEngineLocalDeviceExceptionTypeDisplayException,10011:He.AliEngineLocalDeviceExceptionTypeDisplayException,10012:He.AliEngineLocalDeviceExceptionTypeDisplayException,10013:He.AliEngineLocalDeviceExceptionTypeDisplayException,10014:He.AliEngineLocalDeviceExceptionTypeDisplayException,10019:He.AliEngineLocalDeviceExceptionTypeDisplayException};var Ye=(a=>(a.CREATE_ENGINE="create_engine",a.JOIN="join",a.WANT_INSERT_PUB_TASK="wantInsertPubTask",a.INSERT_PUB_TASK="InsertPubTask",a.HANDLE_PUB_TASK="HandlePubTask",a.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",a.INSERT_SUB_TASK="InsertSubTask",a.HANDLE_SUB_TASK="HandleSubTask",a.FIRST_REMOTE="first_remote",a))(Ye||{}),tt=(a=>(a.START="start",a.SEND_SIG="send_sig",a.RECV_RST="recv_rst",a.END="end",a.RECEIVED="received",a.DECODED="decoded",a.PLAYED="played",a))(tt||{});const wn=(a,r,e=!1)=>{const t=()=>(a.muted=!0,Promise.race([Ut(500),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&a.srcObject===r?i=Promise.resolve():(a.load(),a.srcObject=r,i=a.play(),a._playPromise=i),i}));return new Promise(i=>{if(K.AliRTS.BrowserUtil.isMicroMessenger){const s=window.top!==window.self,n=window.WeixinJSBridge||window.top.WeixinJSBridge;n?n.invoke("getNetworkType",{},()=>{i(t())}):(s?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{n.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},Pt=a=>{Promise.race([Ut(100),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{a.srcObject=null,a._playPromise=void 0})};var Bs=(a=>(a[a.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",a[a.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",a[a.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",a))(Bs||{});class zi{constructor(r,e,t,i=0){m(this,"msgType");m(this,"msgId");m(this,"protocolVersion");m(this,"tlvVersion");this.msgType=r,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const r=new Uint8Array(4);return r.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),r.set(Uint16Array.from([this.msgId]),2),r}static parse(r){const e=new DataView(r),t=e.getUint8(0),i=e.getUint8(1)>>4,s=15&e.getUint8(1),n=e.getUint16(2);return new zi(s,n,t,i)}}class Ki{constructor(r,e,t){m(this,"_byteArray");if(this._byteArray=new Uint8Array(0),r!==void 0&&e!==void 0&&t!==void 0){const i=new zi(r,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(r,e){const t=this._byteArray,i=new ArrayBuffer(5),s=new DataView(i);s.setUint8(0,r),s.setUint32(1,e.byteLength);const n=new Uint8Array(t.byteLength+5+e.byteLength);n.set(t,0),n.set(new Uint8Array(i),t.byteLength),n.set(new Uint8Array(e),t.byteLength+5),this._byteArray=n}static parse(r){const e={},t=new DataView(r);let i=0;for(;i<r.byteLength;){const s=t.getUint8(i),n=t.getUint32(i+1);if(!(i+5+n<=r.byteLength))break;{const c=r.slice(i+5,i+5+n);e[s]=c,i+=5+n}}return e}get buffer(){return this._byteArray.buffer}}class Ii{constructor(r=0,e=!0,t=1,i=!1,s=0,n=!1,c=!1,o=3){m(this,"_fin",!0);m(this,"_hasExtension",!1);m(this,"_version",0);m(this,"_frameType",1);m(this,"_isEncrypted",!1);m(this,"_isCompressed",!1);m(this,"_signalType",3);m(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=s,this._frameType=t,this._isEncrypted=n,this._isCompressed=c,this._signalType=o,this._payloadLength=r}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const r=new ArrayBuffer(4),e=new DataView(r);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),r}static parse(r){const e=new DataView(r),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,s=(48&e.getUint8(0))>>4,n=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,l=15&e.getUint8(1),d=e.getUint16(2);return new Ii(d,t,n,i,s,c,o,l)}}class Ji{constructor(r,e){m(this,"_body");m(this,"_header",new Ii);this._header=r,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const r=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+r.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(r),t.byteLength),i.set(new Uint8Array(e),t.byteLength+r.byteLength),i.buffer}static parse(r){const e=r.slice(0,4),t=Ii.parse(e);let i=new ArrayBuffer(0);return r.byteLength-4>=t.payloadLength&&(i=r.slice(4,4+t.payloadLength)),new Ji(t,i)}}const Hs=a=>{const r=a.byteLength,e=new DataView(a);let t=0;for(let i=0;i<r;i++)t=256*t+e.getUint8(i);return t};let _n=0;class zt{constructor(r,e=0,t=0,i=0){m(this,"data");m(this,"networkTime");m(this,"futureOrProgress");m(this,"type");this.data=r,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const r=new Ki(0,0,0);r.write(1,Uint8Array.from([0]).buffer),r.write(2,Uint16Array.from([0]).buffer),_n++,r.write(3,Uint32Array.from([_n]).buffer);const e=new Ki;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),r.write(30,e.buffer),r.buffer}static parse(r){if(!r||r.byteLength<4)return;zi.parse(r.slice(0,4));const e=Ki.parse(r.slice(4))[30];if(!e)return;const t=Ki.parse(e),i=t[2],s=t[3],n=t[4],c=t[5];return c.byteLength!==0?new zt(c,Hs(i),Hs(n),Hs(s)):void 0}}var Sc=Object.defineProperty,vc=Object.getOwnPropertyDescriptor,Ce=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?vc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Sc(r,e,s),s};class Ei extends oe{constructor(){super();m(this,"_state");m(this,"time");this._state=ee.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const _e=(mt=class extends Sn{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:s,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);m(this,"sessionId","");m(this,"traceId","");m(this,"_url","");m(this,"joinTime",0);m(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));m(this,"previewElements",[]);m(this,"screenPreviewElements",[]);m(this,"streamManager");m(this,"dc");m(this,"streamTracks");m(this,"publishId",ut());m(this,"signalingManager");m(this,"shouldPublish",!1);m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"candidateDataCache",[]);m(this,"pcMediaStatsMap",{});m(this,"slsReporter");m(this,"audioPubState");m(this,"videoPubState");m(this,"videoSmallPubState");m(this,"screenPubState");m(this,"dataPubState");m(this,"parameter",{});m(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=n,this.slsReporter=s,this.parameter=o,this.streamManager.on("trackended",l=>{this.onTrackEnd(l)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new Ei,this.audioPubState.on("change",(l,d,h)=>{this.emit("audioPublishStateChanged",l,d,h)}),this.videoPubState=new Ei,this.videoPubState.on("change",(l,d,h)=>{this.emit("videoPublishStateChanged",l,d,h)}),this.videoSmallPubState=new Ei,this.videoSmallPubState.on("change",(l,d,h)=>{this.emit("dualStreamPublishStateChanged",l,d,h)}),this.screenPubState=new Ei,this.screenPubState.on("change",(l,d,h)=>{this.emit("screenPublishStateChanged",l,d,h)}),this.dataPubState=new Ei,this.dataPubState.on("change",(l,d,h)=>{this.emit("dataPublishStateChanged",l,d,h)}),this.startStreamMonitor(),this.createCallId()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===M.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===M.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===M.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="audio"&&t&&s===M.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.sessionId=e.sessionId||De.createCallid("web"),this.updatePubId()}setVideoProfile(e){return I(this,null,function*(){yield this.streamManager.setVideoProfile(yn,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return I(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return I(this,null,function*(){yield this.streamManager.setScreenProfile(Rn,e)})}setCameraDirection(e){if(e===yi.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==yi.CAMERA_REAR)throw new O(B.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=ut()}clearPublishState(){this.streamTracks=void 0}leave(){return I(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0,this.dataPubState.setState(ee.AliRtcStateNoPublish)})}clear(){return I(this,null,function*(){lr(mt.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(Pt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(Pt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return I(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:s}=this,{hasMicrophone:n,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,l=!t&&!e&&!i&&s,d=!n&&!c&&o;try{l&&d?yield this.startCameraAndMic():l?yield this.startCameraCapture():d&&(yield this.startAudioCapture())}catch(h){const p=h.errorCode;let u=B.ERR_CAMERA_OPEN_FAIL;throw l?((p===_i.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||_i.ERROR_DEVICE_NOTALLOWED)&&(u=B.ERR_CAMERA_AUTH_FAIL),u=B.ERR_CAMERA_OPEN_FAIL):((p===_i.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||_i.ERROR_DEVICE_NOTALLOWED)&&(u=B.ERR_MIC_AUTH_FAIL),u=B.ERR_MIC_OPEN_FAIL),new O(u,`auto open fail: ${h.message}`)}})}setViewConfig(e,t){if(e){if(![he.AliRtcVideoTrackCamera,he.AliRtcVideoTrackScreen].includes(t))throw new O(B.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===he.AliRtcVideoTrackScreen})})}else t===he.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return I(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return I(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return I(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return I(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let s=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new O(B.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return s?(wn(t,s.mediaStream),this.setPreviewElement(e),s.mediaStream):void T.info(`[${mt.logName}]`,"preview no stream founded")}catch(s){const n=B.ERR_INNER;throw O.fromError(s,n,"preview failed")}})}previewAll(e){return I(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let s=0;s<this.previewElements.length;s++){const n=this.previewElements[s];yield this.preview({videoElement:n})}if(i&&this.screenPreviewElements.length)for(let s=0;s<this.screenPreviewElements.length;s++){const n=this.screenPreviewElements[s];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:s=!0}=e||{};if(t){const n=this.previewElements.findIndex(c=>c===t);if(n>=0)this.previewElements.splice(n,1),Pt(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),Pt(t))}}else i&&(this.previewElements.forEach(n=>{Pt(n)}),this.previewElements=[]),s&&(this.screenPreviewElements.forEach(n=>{Pt(n)}),this.screenPreviewElements=[])}resumePublish(){return I(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),yield this.startPublish(!0))})}createLocalStream(e){return I(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const s=this.previewElements[i];Pt(s)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const s=this.screenPreviewElements[i];Pt(s)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=bc[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",Tt.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",Tt.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",Tt.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",Tt.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return I(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return I(this,null,function*(){var n,c;if(!e&&!t)return;if(e&&!t){const o={};return i===M.Audio?o.audio=!0:i===M.VideoLarge||i===M.VideoSmall?(o.video=!0,o.vMsid=i):i===M.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const s={};if(t!=null&&t.hasVideo&&(s.isScreen=i===M.Screen,s.vMsid=i),t!=null&&t.hasAudio&&(s.aMsid=i),!e&&t)return yield this.publishAdd(t,s,!1);if(e&&t&&e.trackId!==(((n=t.videoTrack)==null?void 0:n.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,s)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=K.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(M.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=K.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=K.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return I(this,null,function*(){if(this.dataPubState.state!==ee.AliRtcStatePublishing){this.dataPubState.setState(ee.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(ee.AliRtcStatePublished)):(this.dataPubState.setState(ee.AliRtcStateNoPublish),this.emit("publishDataError",new O(B.ERR_INNER,"publishDataError")))}catch(e){T.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(ee.AliRtcStateNoPublish)}}})}startPublish(){return I(this,arguments,function*(e=!1,t=kt.MANUAL){var l,d,h;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:s,video:n,videoSmall:c,screen:o}=i;if(s||n||c||o)try{const p=new Date().getTime();s&&this.audioPubState.setState(ee.AliRtcStatePublishing),n&&this.videoPubState.setState(ee.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),o&&this.screenPubState.setState(ee.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,e,t);const{traceId:u,l1ip:f}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=u;const g={type:Ot.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?f:void 0,callid:this.callId,tracks:this.streamTracks,traceid:u};(l=this.parameter.data)!=null&&l.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(g,i,p)}),u&&(this.traceId=u),s&&this.reportAudioProfile(),n&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(g,i,p),s&&this.audioPubState.setState(ee.AliRtcStatePublished),n&&this.videoPubState.setState(ee.AliRtcStatePublished),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),o&&this.screenPubState.setState(ee.AliRtcStatePublished)}catch(p){throw s&&this.audioPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoPubState.setState(ee.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),o&&this.screenPubState.setState(ee.AliRtcStateNoPublish),p}else{if((d=this.parameter.data)!=null&&d.enablePubSubDataWithoutMedia&&((h=this.parameter.data)!=null&&h.enablePubDataChannel)){T.event(`[${mt.logName}]`,"startPublish no media stream, publish data channel only");try{const p=new Date().getTime();if(yield this.publishDataChannel(),this.dc){const u={type:Ot.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:[],traceid:this.traceId};yield this.syncPublishToRoomServer(u,i,p)}}catch(p){T.error(`[${mt.logName}]`,"publishDataChannel without media failed",p)}return}T.event(`[${mt.logName}]`,"startPublish no stream founded")}})}updateStreams(){return I(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return I(this,null,function*(){var n,c,o,l,d;if(T.info(`[${mt.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const s=new Date().getTime();try{const h=(n=this.streamTracks)==null?void 0:n.find(({ssrc:R,type:_,msid:y})=>_==="audio"&&R&&y===M.Audio),p=yield this.compareAndPublish(h,t.audio,M.Audio);p&&(i=p);const u=(c=this.streamTracks)==null?void 0:c.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===M.VideoLarge),f=yield this.compareAndPublish(u,t.video,M.VideoLarge);f&&(i=f);const g=(o=this.streamTracks)==null?void 0:o.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===M.VideoSmall),S=yield this.compareAndPublish(g,t.videoSmall,M.VideoSmall);S&&(i=S);const b=(l=this.streamTracks)==null?void 0:l.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===M.Screen),v=yield this.compareAndPublish(b,t.screen,M.Screen);v&&(i=v),(d=this.parameter.data)!=null&&d.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),i||e!==kt.RECONNECT?i&&(yield this.syncPublishToRoomServer(i,t,s)):this.syncPublishToRoomServer({type:Ot.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},t,Date.now())}catch(h){const{code:p}=h!=null?h:{},u=this.url;throw p===403&&u&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),h}return i})}syncPublishToRoomServer(e,t,i){return I(this,null,function*(){var o;if(!e)return void T.event(`[${mt.logName}]`,"sync publish to room server failed because no publishInfo");let s=e;if(this.dc){const c=e,{tracks:l}=c,d=jt(c,["tracks"]);s=ft(X({},d),{tracks:[...l,{type:"data",msid:M.Data,ssrc:`web_${this.callId.substring(0,8)}_${((o=this.dc.datachannel)==null?void 0:o.id)||"0"}`,codec:"text"}]})}const n=yield this.signalingManager.publish(s);e.signaltid=n.tid})}refreshPushStreamUrl(){return I(this,null,function*(){const e=new O(B.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,s=0){return I(this,null,function*(){const n=(t==null?void 0:t.aMsid)===M.Audio,c=(t==null?void 0:t.vMsid)===M.VideoLarge,o=(t==null?void 0:t.vMsid)===M.VideoSmall,l=(t==null?void 0:t.vMsid)===M.Screen;n&&this.audioPubState.setState(ee.AliRtcStatePublishing),c&&this.videoPubState.setState(ee.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),l&&this.screenPubState.setState(ee.AliRtcStatePublishing);try{const d=yield this.rtsManager.publishAdd(this,e,t,!1,!0);d&&(this.traceId=d),n&&(this.audioPubState.setState(ee.AliRtcStatePublished),this.reportAudioProfile()),c&&(this.videoPubState.setState(ee.AliRtcStatePublished),this.reportVideoProfile()),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),l&&(this.screenPubState.setState(ee.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const h={type:Ot.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:d};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),h}catch(d){let h=B.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(ee.AliRtcStateNoPublish),h=B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(ee.AliRtcStateNoPublish),h=B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),h=B.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),l&&(this.screenPubState.setState(ee.AliRtcStateNoPublish),h=B.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),d.errorCode===15006&&s<3)return this.publishAdd(e,t,i,s+1);throw O.fromError(d,h,"publish add failed")}})}publishReplace(e,t){return I(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===M.VideoLarge,s=(t==null?void 0:t.vMsid)===M.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),s&&this.streamManager.setScreenProfile(void 0,void 0);const n={type:Ot.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),n}catch(i){throw O.fromError(i,B.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return I(this,null,function*(){const t={type:Ot.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(ee.AliRtcStateNoPublish),e.video&&(e.vMsid===M.VideoSmall?this.videoSmallPubState.setState(ee.AliRtcStateNoPublish):this.videoPubState.setState(ee.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(ee.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw O.fromError(i,B.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return I(this,null,function*(){T.info(`[${mt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,s=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(ee.AliRtcStateNoPublish),i&&this.videoPubState.setState(ee.AliRtcStateNoPublish),s&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),n&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Ot.Stop,userid:this.userId,sessionid:this.sessionId,displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw O.fromError(t,B.ERR_INNER,"publish stop failed")}})}unPublish(){return I(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Ot.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,s=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(ee.AliRtcStateNoPublish),s&&this.videoPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),c&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(ee.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw O.fromError(i,B.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(at.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,s,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((n=(s=this.streamManager.screenStreamInfo)==null?void 0:s.originVideoTrack)!=null&&n.enabled),vn.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===M.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.traceId||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){var e,i;try{const s=yield this.rtsManager.getPCStats();let n,c;if(s==null||s.forEach(l=>{l.type==="media-source"||l.type==="media-playout"?l.id&&(this.pcMediaStatsMap[l.id]=l):l.type==="candidate-pair"&&l.state==="succeeded"&&(n=l)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const l=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=l,{_last:d}=t;c=jt(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),n&&(n._last=c,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(l=>{var d;return((d=this.monitorDataCache[l])==null?void 0:d.length)>0});(this.streamTracks||[]).forEach(l=>{const d=l.msid;if(!d)return;let h;o.includes(d)&&(o=o.filter(p=>p!==d)),h=d===M.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,d),h.then(p=>{if(!p.timestamp)return;this.monitorDataCache[d]||(this.monitorDataCache[d]=[]);const u=this.getMediaStats(p.mediaSourceId);p._source=u;const f=this.monitorDataCache[d];let g;if((f==null?void 0:f.length)>0){const b=f[f.length-1]||{},S=b,{_last:v}=S;g=jt(S,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(d),p._last=g,p._codec=l.codec||"",this.monitorDataCache[d].push(p)})}),o.forEach(l=>{this.reportPublishMonitor(l)})}catch(s){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(ee.AliRtcStatePublishIdle),this.videoPubState.setState(ee.AliRtcStatePublishIdle),this.videoSmallPubState.setState(ee.AliRtcStatePublishIdle),this.screenPubState.setState(ee.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return I(this,null,function*(){if(!this.url)return;let s=0;return s=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,s,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new O(B.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new O(B.ERR_INNER,"data channel is not ready");const t=function(s,n){let c=0;const o=[];for(;c<s.byteLength;){const l=Math.min(n,s.byteLength-c),d=s.slice(c,c+l);o.push(d),c+=l}return o}(e.toBuffer(),1156);t.forEach((s,n)=>{const c=new Ji(new Ii(s.byteLength,n===t.length-1,n===0?1:0),s);this.dc.send(c.toGRTNBuffer())})}getStats(){return I(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:Zt.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoLarge);n&&t.push({track:he.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoSmall);n&&t.push({track:he.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.Screen);n&&t.push({track:he.AliRtcVideoTrackScreen,stats:n})}let i;const s=yield this.rtsManager.getPCStats();return s==null||s.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(i=n)}),{audio:e,video:t,candidate:i}})}markReconnect(e){const t=[],i=this.streamManager.publishStreams;!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),!this.dc||e&&!e.includes(M.Data)||t.push(this.dataPubState),t.forEach(s=>{s.setState(ee.AliRtcStateReconnecting)})}markReconnected(e){var s;const t=[],i=this.streamManager.publishStreams;if(!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),this.dc&&(!e||e.includes(M.Data))&&(t.push(this.dataPubState),(s=this.parameter.data)==null?void 0:s.enablePubDataChannel)){const n=this.rtsManager.getDatachannelByMsid({url:this.url,msid:M.Data});this.updateDataChannel(n)}this.publishUpdate(kt.RECONNECT),t.forEach(n=>{n.setState(ee.AliRtcStatePublished)})}},m(mt,"logName","LocalUser"),mt);Ce([k()],_e.prototype,"clearPublishState",1),Ce([k()],_e.prototype,"clear",1),Ce([k(H)],_e.prototype,"startDefaultCameraAndMic",1),Ce([k()],_e.prototype,"setViewConfig",1),Ce([k()],_e.prototype,"startCameraCapture",1),Ce([k()],_e.prototype,"stopCameraCapture",1),Ce([k()],_e.prototype,"startAudioCapture",1),Ce([k()],_e.prototype,"stopAudioCapture",1),Ce([k()],_e.prototype,"startCameraAndMic",1),Ce([k()],_e.prototype,"stopPreview",1),Ce([k()],_e.prototype,"resumePublish",1),Ce([k()],_e.prototype,"createLocalStream",1),Ce([k()],_e.prototype,"stopLocalStream",1),Ce([k()],_e.prototype,"updateDataChannel",1),Ce([k(H)],_e.prototype,"startPublish",1),Ce([k()],_e.prototype,"updateStreams",1),Ce([k(([a])=>[a])],_e.prototype,"syncPublishToRoomServer",1),Ce([k()],_e.prototype,"refreshPushStreamUrl",1),Ce([k(([a,r,e])=>[JSON.stringify(e)])],_e.prototype,"publishAdd",1),Ce([k(([a,r])=>[JSON.stringify(r)])],_e.prototype,"publishReplace",1),Ce([k(H)],_e.prototype,"publishDeleteTracks",1),Ce([k()],_e.prototype,"publishStop",1),Ce([k()],_e.prototype,"unPublish",1),Ce([k(([a,r,e])=>[a.length,r,e])],_e.prototype,"sendSEI",1),Ce([k(H)],_e.prototype,"markReconnect",1),Ce([k(H)],_e.prototype,"markReconnected",1);let yc=_e;var vt=(a=>(a.OPUS="opus",a.H264="H264",a.H265="H265",a.AV1="AV1",a.UNKNOWN="",a))(vt||{}),de=(a=>(a[a.NotSubscribe=0]="NotSubscribe",a[a.Subscribing=1]="Subscribing",a[a.Subscribed=2]="Subscribed",a))(de||{}),ai=(a=>(a.VideoTrackEnded="videoTrackEnded",a.AudioTrackEnded="audioTrackEnded",a.ScreenTrackEnded="screenTrackEnded",a))(ai||{});const In=a=>I(this,null,function*(){return yield K.AliRTS.createStream({custom:!0,mediaStream:a})}),Ti=a=>I(this,null,function*(){const r=(e=>{const t=new MediaStream;return t.addTrack(e),t})(a);return yield In(r)});var Rc=Object.defineProperty,Ac=Object.getOwnPropertyDescriptor;class Fs extends oe{constructor(){super();m(this,"audioInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:vt.UNKNOWN});m(this,"videoLargeInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:vt.UNKNOWN});m(this,"videoSmallInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:vt.UNKNOWN});m(this,"screenInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:vt.UNKNOWN});m(this,"dataInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:vt.UNKNOWN});m(this,"audioVolume",1);m(this,"audioMuted",!1);m(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===de.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===de.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===de.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===de.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===de.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===de.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===de.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===de.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===de.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===de.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===de.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:vt.UNKNOWN}get audioTrackInfo(){return this.hasAudio?Zt.AliRtcAudioTrackMic:Zt.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?he.AliRtcVideoTrackBoth:this.hasVideo?he.AliRtcVideoTrackCamera:this.hasScreen?he.AliRtcVideoTrackScreen:he.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",s="",n="",c="";return e?(e.forEach(o=>{var p;let l=vt.UNKNOWN;const d=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:u}=JSON.parse(o.userdata);u&&(l=u)}var h;(h=o.msid)===M.Audio||h===as.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=l,(d||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=de.NotSubscribe)):(u=>u===M.VideoSmall)(o.msid)?(s=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=l,(d||this.videoSmallInfo.ssrc!==s)&&(this.videoSmallInfo.subscribeState=de.NotSubscribe)):(u=>u===M.VideoLarge||u===as.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=l,(d||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=de.NotSubscribe)):(u=>u===M.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=l,(d||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=de.NotSubscribe)):(u=>u===M.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=l,(d||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=de.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,s,n,c)):this.updateRemoteTrackSsrc(t,i,s,n,c),{}}updateRemoteTrackSsrc(e,t,i,s,n){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=s,this.dataInfo.ssrc=n}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=de.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=de.Subscribing)),e.screen&&(this.screenInfo.subscribeState=de.Subscribing),e.audio&&(this.audioInfo.subscribeState=de.Subscribing),e.data&&(this.dataInfo.subscribeState=de.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?de.Subscribed:de.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?de.Subscribed:de.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?de.Subscribed:de.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=vn.parseStatus(e);const{audioDisable:i,videoDisable:s,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(at.Remote,i?Pe.MuteAudio:Pe.UnmuteAudio)),this.userStatus.videoDisable!=s&&(this.userStatus.videoDisable=s,this.emit(at.Remote,s?Pe.MuteVideo:Pe.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(at.Remote,n?Pe.MuteScreen:Pe.UnmuteScreen))):(this.userStatus=t,this.emit(at.Remote,i?Pe.MuteAudio:Pe.UnmuteAudio),this.emit(at.Remote,s?Pe.MuteVideo:Pe.UnmuteVideo),this.emit(at.Remote,n?Pe.MuteScreen:Pe.UnmuteScreen)),!1}}m(Fs,"logName","RemoteStreamInfo"),((a,r,e,t)=>{for(var i,s=t>1?void 0:t?Ac(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);t&&s&&Rc(r,e,s)})([k()],Fs.prototype,"updateRemoteTrackSubState",1);class En{constructor(r){m(this,"remoteUser");this.remoteUser=r}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var wc=Object.defineProperty,_c=Object.getOwnPropertyDescriptor,We=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?_c(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&wc(r,e,s),s};class mi extends oe{constructor(){super();m(this,"state");m(this,"time");m(this,"_enabled");this.state=ce.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const je=(li=class extends Sn{constructor(e){var u;const{userId:t,displayName:i,rtsManager:s,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:l,audioVolumeIndicationInterval:d,playoutVolume:h,parameter:p}=e;super(t,i,s,d);m(this,"remoteCallId","");m(this,"remoteUserInfo");m(this,"localUser");m(this,"lastPubId","");m(this,"stream");m(this,"screenStream");m(this,"viewMap");m(this,"audioTrack");m(this,"audioElement");m(this,"subscribed",!1);m(this,"mediaStream");m(this,"secondaryMediaStream");m(this,"prevSubConfig");m(this,"signalingManager");m(this,"slsReporter");m(this,"wantSubAudio",!1);m(this,"wantSubVideo",!1);m(this,"wantSubScreen",!1);m(this,"defaultVideoStreamType",Je.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"playoutGainNode");m(this,"audioSubState");m(this,"videoSubState");m(this,"videoLargeSubState",new mi);m(this,"videoSmallSubState",new mi);m(this,"screenSubState");m(this,"dataSubState");m(this,"dc");m(this,"dcMsgWaitingPieces",[]);m(this,"streamInfo");m(this,"_streamUrl","");m(this,"parameter",{});m(this,"_audioResumeHandler",null);m(this,"_videoResumeHandler",null);m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"traceId","");m(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});m(this,"onDataChannelMessage",e=>{var s;const t=Ji.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const n=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(n);let o=0;for(let l=0;l<this.dcMsgWaitingPieces.length;l++){const d=this.dcMsgWaitingPieces[l];new Uint8Array(c,o,d.byteLength).set(new Uint8Array(d)),o+=d.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=zt.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=zt.parse(t.body))}else i=zt.parse(t.body);i||T.event(`[${this.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(T.event(`[${this.logName}]`,`receive dc message, length(${(s=i.data)==null?void 0:s.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});m(this,"onDataChannelError",e=>{this.emit("occurError",O.fromError(e,B.ERR_SDK_SUBSCRIBE_DATA_ERROR))});m(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});m(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new Fs,this.remoteUserInfo=new En(this),this.parameter=p,this.streamInfo.on(at.Remote,f=>{this.emit(at.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(u=n[t])!=null?u:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=c,this.localUser=l,this.audioSubState=new mi,this.audioSubState.on("change",(f,g,S)=>{this.emit("audioSubscribeStateChanged",this.uid,f,g,S)}),this.videoSubState=new mi,this.videoSubState.on("change",(f,g,S)=>{this.emit("videoSubscribeStateChanged",this.uid,f,g,S)}),this.screenSubState=new mi,this.screenSubState.on("change",(f,g,S)=>{this.emit("screenSubscribeStateChanged",this.uid,f,g,S)}),this.dataSubState=new mi,this.dataSubState.on("change",(f,g,S)=>{this.emit("dataSubscribeStateChanged",this.uid,f,g,S)}),this.playoutVolume=h}get logName(){return`${li.logName}(${this.userId})`}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(ge.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=bt.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const s=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),s.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){return this.streamInfo.hasAudio}get audioSSRC(){var e;return this.streamInfo.isAudioSubscribed&&((e=this.streamInfo.getAudioInfo())==null?void 0:e.ssrc)||""}get hasVideoTrack(){return this.streamInfo.hasVideo}get videoSSRC(){var e,t;return this.streamInfo.isVideoSubscribed?((e=this.streamInfo.getVideoLargeInfo())==null?void 0:e.ssrc)||"":this.streamInfo.isVideoSmallSubscribed&&((t=this.streamInfo.getVideoSmallInfo())==null?void 0:t.ssrc)||""}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.isDataSubscribing}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==he.AliRtcVideoTrackScreen&&t!==he.AliRtcVideoTrackCamera)throw new O(B.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?ns(e).forEach(i=>{i.setAttribute("playsinline",""),K.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),K.AliRTS.SystenUtil.isAndroid||K.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===he.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===he.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===he.AliRtcVideoTrackScreen),t===he.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return I(this,null,function*(){var t,i,s,n;lr(li.prototype,this,"clear").call(this),this._removeAudioResumeHandler(),this._removeVideoResumeHandler(),this.stopPlayAudio(),this.stopStreamMonitor(),e&&this.subscribeDeleteAllTracks(this.streamUrl).catch(c=>{T.event(`[${this.logName}]`,`stopSubscribeAllTracks error: ${c.message||c}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,bt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(),(t=this.audioSubState)==null||t.removeAllListeners(),(i=this.videoSubState)==null||i.removeAllListeners(),(s=this.screenSubState)==null||s.removeAllListeners(),(n=this.dataSubState)==null||n.removeAllListeners()})}updateRemoteUserDeviceStatus(e){this.streamInfo.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,s){return I(this,null,function*(){return this.remoteCallId=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.streamInfo.updateTracks(s)})}subscribe(s,n){return I(this,arguments,function*(e,t,i=Date.now()){var u,f;this.createCallId();let c=e;if(!c){const{hasAudio:g,hasVideo:S,hasScreen:b,hasData:v}=(u=this.streamInfo)!=null?u:{};c={audio:this.wantSubAudio&&g,video:this.wantSubVideo&&S,screen:this.wantSubScreen&&b,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:l,video:d,vMsid:h}=c,p=[];(d||l)&&p.push({audio:l,video:d,vMsid:h}),o&&p.push({screen:o}),(p.length!==0||e!=null&&e.data)&&(yield Promise.all(p.map(g=>this.subscribeProxy(g,t||ge.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return I(this,null,function*(){var c,o;let s=new Date().getTime(),n="";if(this.streamUrl)try{e.audio&&this.audioSubState.setState(ce.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==ce.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==ce.AliRtcStateNoSubscribe||this.videoSubState.setState(ce.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(ce.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);if(!l)return e.audio&&this.audioSubState.setState(ce.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ce.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ce.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid});this.streamInfo.updateRemoteTrackSubState(e),n=l.traceId||"";const{stream:d}=l;if(n&&(this.traceId=n),e.audio){const u=d.audioTrack;u&&(this.audioTrack=u,(o=d.mediaStream)==null||o.removeTrack(u),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(u,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(ce.AliRtcStateSubscribed)}e.video&&(this.updateStream(d,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(ce.AliRtcStateSubscribed),e.vMsid===M.VideoSmall?this.videoSmallSubState.setState(ce.AliRtcStateSubscribed):this.videoLargeSubState.setState(ce.AliRtcStateSubscribed)),e.screen&&(this.updateScreenStream(d),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(ce.AliRtcStateSubscribed));const h=new Date().getTime()-s,p=Date.now();setTimeout(()=>{this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,0,"",h,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:t===ge.Join?1:0,url:this.streamUrl,est:s},p)},6e3),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,Ut(1500)]))}catch(l){const d=new Date().getTime()-s;e.audio&&this.audioSubState.setState(ce.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ce.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let h=B.ERR_INNER;e.audio&&(h=B.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(h=e.vMsid===M.VideoSmall?B.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:B.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(h=B.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,h,"",d,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===ge.Join?1:0,url:this.streamUrl,est:s});const p=O.fromError(l,h);this.emit("remoteSubscribeError",p)}else{const l=new O(B.ERR_SDK_SUBSCRIBE_INVAILD,`user(${this.uid}) subscribe failed: streamUrl is not ready. Please subscribe after receiving 'remoteTrackAvailableNotify' event instead of 'remoteUserOnLineNotify'.`);this.emit("remoteSubscribeError",l)}})}subscribeDeleteTracks(e){return I(this,null,function*(){const{audio:t,video:i,screen:s,data:n,vMsid:c}=e,o=[];(t||i||n)&&o.push({audio:t,video:i,vMsid:c}),s&&o.push({screen:s}),o.length!==0&&(yield Promise.all(o.map(l=>this.subscribeDeleteProxy(l))),e.data&&this.subscribeDeleteDataChannel())})}subscribeDeleteProxy(e){return I(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},s={};e.audio===!0&&(s.audio=!1,this.audioSubState.setState(ce.AliRtcStateNoSubscribe)),e.video===!0&&(s.video=!1,e.vMsid===M.VideoSmall?(this.videoSmallSubState.setState(ce.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==ce.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==ce.AliRtcStateSubscribeIdle||this.videoSubState.setState(ce.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(ce.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==ce.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==ce.AliRtcStateSubscribeIdle||this.videoSubState.setState(ce.AliRtcStateNoSubscribe))),e.screen===!0&&(s.screen=!1,this.screenSubState.setState(ce.AliRtcStateNoSubscribe));const{callId:n,remoteCallId:c}=this,o={callid:n,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw O.fromError(t,B.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return I(this,null,function*(){const e=bt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return I(this,null,function*(){return e&&e!==he.AliRtcVideoTrackCamera&&e!==he.AliRtcVideoTrackBoth?e&&e!==he.AliRtcVideoTrackScreen&&e!==he.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return I(this,null,function*(){let t=new Date().getTime();try{e?yield this.subscribeDeleteTracks(e):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,"")}catch(i){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,""),i}})}subscribeDeleteAllTracks(e){return I(this,null,function*(){var s,n,c,o;const{callId:t,remoteCallId:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&e)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const l={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",l}catch(l){if(((o=(c=(n=(s=l==null?void 0:l.extraInfo)==null?void 0:s.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw O.fromError(l,B.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return I(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let s,n;if(e.mediaStream){n=document.createElement("video");const c=()=>{T.event(`[${this.logName}]`,"new mediaStream canplay"),n&&n.removeEventListener("canplaythrough",c,!1),n=void 0,clearTimeout(s),i(!0)};n.addEventListener("canplaythrough",c,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else i(!0);s=window.setTimeout(()=>{T.event(`[${this.logName}]`,"new mediaStream timeout"),n=void 0,i(!0)},3e3)}),this.updateSubscribe(ge.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){var e;if(this.dc)try{this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(t){}if(!((e=this.parameter.data)!=null&&e.enablePubSubDataWithoutMedia||this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen))return this.dataSubState.setState(ce.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({data:!1});this.dataSubState.setState(ce.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(t=>{if(t)return this.dataChannelConnected(t),this.dataSubState.setState(ce.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(t=>{const i=O.fromError(t,B.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",i),this.dataSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({data:!1})})}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(ce.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,s;const e={};this.wantSubAudio&&this.streamInfo.hasAudio&&(e.audio=!0,e.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(e.video=!0,e.vMsid=M.VideoSmall):this.streamInfo.hasVideoLarge&&(e.video=!0,e.vMsid=((s=this.streamInfo.getVideoLargeInfo())==null?void 0:s.msid)||M.VideoLarge)),this.wantSubScreen&&this.streamInfo.hasScreen&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var n,c,o,l,d,h;const t=Date.now(),i={},s={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==ce.AliRtcStateReconnecting?(i.audio=!0,i.aMsid=((n=this.streamInfo.getAudioInfo())==null?void 0:n.msid)||M.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(s.audio=!0,s.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==ce.AliRtcStateReconnecting?(i.video=!0,i.vMsid=M.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall||this.videoLargeSubState.currentState===ce.AliRtcStateReconnecting||(i.video=!0,i.vMsid=((o=this.streamInfo.getVideoLargeInfo())==null?void 0:o.msid)||M.VideoLarge),this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(s.video=!0,s.vMsid=M.VideoLarge):this.defaultVideoStreamType!==Je.AliRtcVideoStreamTypeHigh&&this.streamInfo.hasVideoSmall||!this.isVideoLargeSubscribing||!this.isVideoSmallSubscribing||(s.video=!0,s.vMsid=M.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(s.video=!0,s.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((l=this.streamInfo.getVideoLargeInfo())==null?void 0:l.msid)||M.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==ce.AliRtcStateReconnecting?i.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(s.screen=!0),(d=this.parameter.data)!=null&&d.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==ce.AliRtcStateReconnecting?i.data=!0:(h=this.parameter.data)!=null&&h.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(s.data=!0),this.dc&&i.data&&this.subscribeDeleteDataChannel(),(i.audio||i.video||i.screen||i.data)&&this.subscribe(i,e,t),(s.audio||s.video||s.screen)&&this.subscribeDeleteTracks(s),{addOption:i,deleteOption:s}}handleAutoPlayFailed(){T.event(`[${this.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid),this._removeAudioResumeHandler();const e=()=>{this.resumeAudio().finally(()=>{this._removeAudioResumeHandler()})};this._audioResumeHandler=e,document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}_removeAudioResumeHandler(){this._audioResumeHandler&&(document.removeEventListener("click",this._audioResumeHandler,!1),document.removeEventListener("touchstart",this._audioResumeHandler,!1),this._audioResumeHandler=null)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t),this._removeVideoResumeHandler();const i=()=>{var n;const s=(n=t===he.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===s&&this.play(e,t===he.AliRtcVideoTrackScreen),this._removeVideoResumeHandler()};this._videoResumeHandler=i,document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}_removeVideoResumeHandler(){this._videoResumeHandler&&(document.removeEventListener("click",this._videoResumeHandler,!1),document.removeEventListener("touchstart",this._videoResumeHandler,!1),this._videoResumeHandler=null)}playAudio(){return I(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(T.event(`[${this.logName}]`,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(s=>{i.removeTrack(s)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(K.AliRTS.SystenUtil.isIos&&parseInt(K.AliRTS.SystenUtil.systemVersion)<=13){T.event(`[${this.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const s=()=>{i.removeEventListener("playing",s),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",s)}else(()=>{var i;T.event(`[${this.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{T.event(`[${this.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else T.event(`[${this.logName}]`,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const s=t?this.screenStream:this.stream;e&&s&&s.mediaStream&&wn(e,s.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?he.AliRtcVideoTrackScreen:he.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{Pt(t)}):this.viewMap.cameraViews.forEach(t=>{Pt(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return I(this,null,function*(){var i,s,n;const e=[];if(this.isAudioSubscribing){const c=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);c&&e.push({uid:this.uid,track:Zt.AliRtcAudioTrackMic,stats:c})}const t=[];if(this.streamInfo.isVideoLargeSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||M.VideoLarge);c&&t.push({uid:this.uid,track:he.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeHigh,stats:c})}if(this.streamInfo.isVideoSmallSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((s=this.streamInfo.getVideoSmallInfo())==null?void 0:s.msid)||M.VideoSmall);c&&t.push({uid:this.uid,track:he.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeLow,stats:c})}if(this.isScreenSubscribing){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((n=this.streamInfo.getScreenInfo())==null?void 0:n.msid)||M.Screen);c&&t.push({uid:this.uid,track:he.AliRtcVideoTrackScreen,stats:c})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){e&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let s;e.includes(i)&&(e=e.filter(c=>c!==i));const n=i===M.Audio;s=n?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),s.then(c=>{var h;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let l;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},d=p,{_last:u}=d;l=jt(d,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=l,c._codec=t.codec,n&&(c._source=(h=this.localUser)==null?void 0:h.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}markReconnect(e){const t=[];!this.isAudioSubscribing||e&&!e.includes(this.streamInfo.getAudioInfo().msid)||t.push(this.audioSubState),this.isVideoSubscribing&&(!e||e.includes(this.streamInfo.getVideoLargeInfo().msid)||e.includes(this.streamInfo.getVideoSmallInfo().msid))&&t.push(this.videoSubState),!this.isScreenSubscribing||e&&!e.includes(this.streamInfo.getScreenInfo().msid)||t.push(this.screenSubState),!this.isDataSubscribing||e&&!e.includes(M.Data)||t.push(this.dataSubState),t.forEach(i=>{i.setState(ce.AliRtcStateReconnecting)})}markReconnected(e){const t=[],i=this.streamInfo.getAudioInfo().msid||M.Audio;if(this.isAudioSubscribing&&(!e||e.includes(i))){t.push(this.audioSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:i});o&&o.audioTrack&&(this.audioTrack=o.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const s=this.streamInfo.getVideoLargeInfo().msid||M.VideoLarge,n=this.streamInfo.getVideoSmallInfo().msid||M.VideoSmall;if(this.isVideoSubscribing&&(!e||e.includes(s)||e.includes(n))){t.push(this.videoSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?n:s});o&&o.mediaStream&&(this.stream=o,this.playAll(!1))}const c=this.streamInfo.getScreenInfo().msid||M.Screen;if(this.isScreenSubscribing&&(!e||e.includes(c))){t.push(this.screenSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:c});o&&o.mediaStream&&(this.screenStream=o,this.playAll(!0))}if(this.isDataSubscribing&&(!e||e.includes(this.streamInfo.getDataInfo().msid))){t.push(this.dataSubState);const o=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||M.Data});this.dataChannelConnected(o)}t.forEach(o=>{o.setState(ce.AliRtcStateSubscribed)}),e||this.updateSubscribe(ge.Reconnect)}},m(li,"logName","RemoteUser"),li);We([k()],je.prototype,"clear",1),We([k()],je.prototype,"updateRemoteUserDeviceStatus",1),We([k()],je.prototype,"updateRemoteTracks",1),We([k(H)],je.prototype,"subscribe",1),We([k()],je.prototype,"subscribeProxy",1),We([k(H)],je.prototype,"subscribeDeleteProxy",1),We([k()],je.prototype,"restore",1),We([k(H)],je.prototype,"resumeAudio",1),We([k(H)],je.prototype,"stopSubscribe",1),We([k(H)],je.prototype,"subscribeDeleteAllTracks",1),We([k()],je.prototype,"clearStream",1),We([k()],je.prototype,"clearScreenStream",1),We([k()],je.prototype,"updateSubscribe",1),We([k()],je.prototype,"playAudio",1),We([k()],je.prototype,"stopPlayAudio",1),We([k((a,r,e)=>[typeof a=="string"?a:a==null?void 0:a.nodeType,r||"-",e||"-"])],je.prototype,"play",1),We([k()],je.prototype,"stopPlayAll",1),We([k(H)],je.prototype,"markReconnect",1),We([k(H)],je.prototype,"markReconnected",1);let Ic=je;var Kt=(a=>(a[a.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",a[a.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",a[a.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",a[a.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",a[a.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",a[a.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",a[a.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",a[a.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",a))(Kt||{});class Ec extends oe{constructor(){super(...arguments);m(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new O(Kt.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new O(Kt.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);try{t.disable()}catch(i){}if(typeof t.stop=="function")try{t.stop()}catch(i){}if(typeof t.destroy=="function")try{t.destroy()}catch(i){}this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){Array.from(this.plugins.keys()).forEach(e=>{this.remove(e)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}const Tc=a=>I(this,null,function*(){const r=new K.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:r.checkMediaDevices()&&r.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield r.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=r.checkBrowser({errorCode:0,message:""})}if(e.support=t,r.checkWebRtcSupport()&&a!=="sendonly"){const i=yield r.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(r.checkWebRtcSupport()&&a!=="recvonly"){const i=yield r.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=r.checkWebRtcSupport()&&r.checkScreenCapture()&&!K.AliRTS.SystenUtil.isAndroid&&!K.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=r.checkWebRtcSupport()&&r.checkEncodedTransformSupport(),e}),{BrowserUtil:Tn}=K.AliRTS,Dt="RtsManager";class Cc{constructor(r){m(this,"ctx");m(this,"rtsClientMap",new Map);m(this,"pubBaseUrl");this.ctx=r}createPerUserRtsInstance(){return K.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0}})}getOrCreateClientEntry(r){let e=this.rtsClientMap.get(r);if(!e){const t=this.createPerUserRtsInstance();e={client:t,connected:!1,traceId:""},this.rtsClientMap.set(r,e),this.addPerUserRTSListener(t,r)}return e}destroyClientEntry(r){const e=this.rtsClientMap.get(r);if(e){try{e.client.removeAllListeners(),e.client.unsubscribe()}catch(t){}this.rtsClientMap.delete(r)}}addPerUserRTSListener(r,e){r.on("connectStatusChange",t=>{T.event(`[${Dt}]`,`[multi-pc:${e}] connectStatusChange to:`,t.status);const i=this.rtsClientMap.get(e);i&&(t.status===K.EConnectStatus.CONNECT_STATUS_DISCONNECTED?(i.connected=!1,e===this.pubBaseUrl&&(this.ctx.slsReporter.reportWarning("rts disconnected (multi-pc pub)"),this.ctx.emit("disconnected"))):t.status===K.EConnectStatus.CONNECT_STATUS_CONNECTED&&(i.connected=!0,e===this.pubBaseUrl&&this.ctx.emit("connected",!1,Ci.PUBLISH)))}),r.on("reconnect",t=>{var i,s,n;T.debug(`[${Dt}]`,`[multi-pc:${e}] reconnect`,t),this.ctx.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(s=t.extraInfo)==null?void 0:s.msids)==null?void 0:n.map(c=>c.name))}),r.on("reconnectFinish",t=>{var s;T.debug(`[${Dt}]`,`[multi-pc:${e}] reconnectFinish`,t),this.ctx.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(s=t==null?void 0:t.msids)==null?void 0:s.map(n=>n.name));const i=this.rtsClientMap.get(e);if(i&&(i.connected=!0),e===this.pubBaseUrl)try{this.ctx.emit("connected",!0,Ci.PUBLISH)}catch(n){T.error(`[${Dt}]`,"emit connected error:",n)}}),r.on("receivedSEI",t=>{this.ctx.emit("seimessage",t.url,t.sei.payloadType,t.sei.data)}),r.on("traceId",({url:t,traceId:i})=>{if(!t||!i||this.ctx.traceIdMap[t]===i)return;this.ctx.traceIdMap[t]=i;const s=this.rtsClientMap.get(e);s&&(s.traceId=i),this.ctx.emit("traceIdUpdated",t,i)}),r.on("onError",t=>{T.event(`[${Dt}]`,`[multi-pc:${e}] onError:`,t)})}get isConnected(){var r,e;if(this.pubBaseUrl)return(e=(r=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:r.connected)!=null?e:!1;for(const t of this.rtsClientMap.values())if(t.connected)return!0;return!1}get isConnecting(){if(this.pubBaseUrl){const r=this.rtsClientMap.get(this.pubBaseUrl);return!!r&&!r.connected}return!1}publish(r,e,t){return I(this,null,function*(){const i=r.url,s=r.callId,n=i.split("?")[0];this.pubBaseUrl=n;const c=this.getOrCreateClientEntry(n),o=Date.now();let l;const{publishStream:d,vMsid:h}=yield this.ctx.localStreamManager.createHTTPPublishStream();if(!d)return T.warn(`[${Dt}]`,"multiPCPublish: publishStream is null"),{traceId:"",l1ip:l};const p=this.ctx.getPubMsid(d,{vMsid:h});p.answerSdpHook=v=>{const R=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(v);return R!=null&&R[0]&&(l=R[0]),v},this.ctx.handleHTTPConfig(p),p.disableHeartbeat=!0,this.ctx.rtsPeerConnectionType=Ci.PUBLISH;const u=Date.now();let f="";try{const v=this.ctx.suffixHttpUrl(i);f=yield c.client.publish(v,d,p)}catch(v){c.connected=!1;const R=2e3-(Date.now()-u);throw R<=0?this.ctx.emit("disconnected"):setTimeout(()=>{this.ctx.emit("disconnected")},R),this.ctx.slsReporter.reportPublish(e,i,s,d.hasVideo&&(!h||h===M.VideoLarge),d.hasVideo&&h===M.VideoSmall,d.hasVideo&&h===M.Screen,d.hasAudio,(v==null?void 0:v.errorCode)||-1,this.ctx.pcTraceId,"",u,u),O.fromRtsError(v)}f&&(this.ctx.pcTraceId=f,c.traceId=f),c.connected=!0,this.ctx.publishingTracks=c.client.getPublishTrackInfoList(),T.event(`[${Dt}]`,"multiPCPublish success",f);const g=Date.now();setTimeout(()=>{this.ctx.slsReporter.reportPublish(e,i,s,d.hasVideo&&(!h||h===M.VideoLarge),d.hasVideo&&h===M.VideoSmall,d.hasVideo&&h===M.Screen,d.hasAudio,0,this.ctx.pcTraceId,r.traceId,u,g)},6e3),this.ctx.slsReporter.reportConnectionLatencyEvent(Ye.HANDLE_PUB_TASK,tt.START,s,f,o),this.ctx.slsReporter.reportConnectionLatencyEvent(Ye.HANDLE_PUB_TASK,tt.END,s,f,Date.now());const S=!d.hasVideo,b=h;return yield this.waitPublishSender(i,S,b),this.ctx.slsReporter.reportPublishFirstPacket(e,s,u,g,this.ctx.localJoinTime,S?M.Audio:p.vMsid,f||"",f||"",t),this.ctx.emit("connected",!1,Ci.PUBLISH),{traceId:f,l1ip:l}})}publishStop(r){return I(this,null,function*(){if(this.pubBaseUrl){const e=this.rtsClientMap.get(this.pubBaseUrl);e&&(yield e.client.publishStop([{url:r}]),this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0)}return this.ctx.publishingTracks=[],""})}unpublish(){return I(this,null,function*(){this.pubBaseUrl&&(this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0),this.ctx.publishingTracks=[]})}subscribe(r,e,t,i,s){return I(this,null,function*(){const{options:n,remoteUser:c}=r;if(n.screen)return T.warn(`[${Dt}]`,"screen subscribe not supported in multi-PC mode"),null;const o=c.streamUrl,l=o.split("?")[0];this.ctx.subUrlMap[c.userId]=l;const d=this.getOrCreateClientEntry(l),h=this.ctx.getSubConfig(c.streamInfo,n);this.ctx.handleHTTPConfig(h),h.disableHeartbeat=!0;const p=Date.now();let u;try{const w=this.ctx.suffixHttpUrl(o,h);u=yield d.client.subscribe(w,h)}catch(w){throw d.connected=!1,O.fromRtsError(w)}d.connected=!0,d.traceId=u.traceId,this.ctx.reportSubscribeLatency(n,t,p,!0);const f={traceId:u.traceId,stream:u,isHTTP:!0},g=Date.now();let S=M.VideoLarge;const b=n.video,v=n.audio;n.video&&n.vMsid&&(S=n.vMsid);let R=0,_=0,y=0;const A=((w,E)=>{let C=0;const P=()=>{if(!this.rtsClientMap.has(l))return Promise.resolve();let D;return v&&!R&&(D=d.client.getSubscribeAudioStats(o).then(U=>{if(U.packetsReceived>0)R=Date.now();else if(!b)return C<w&&(C++,new Promise(G=>setTimeout(()=>G(P()),E)));return!0})),b&&!y&&(D=d.client.getSubscribeVideoStats(o,S).then(U=>{if(typeof U.packetsReceived=="number"){if(!_&&U.packetsReceived>0&&(_=Date.now()),U.framesDecoded>0)y=Date.now();else if(C<w)return C++,new Promise(G=>setTimeout(()=>G(P()),E));return!0}})),Promise.resolve(D)};return P()})(20,100);return A.then(()=>{_&&this.ctx.slsReporter.reportSubscribeFirstPacket(e===ge.Resume,t,i,S,{fprt:_-p,ifsprtc:y?y-p:0,ajsub:e===ge.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}),y&&this.ctx.slsReporter.reportSubscribeFirstFrame(e===ge.Resume,t,i,S,{fvfrt:y-p,fp2fftc:y-_,ajsub:e===ge.Join?1:0,tffrtc:e===ge.Join?y-this.ctx.localJoinTime:y-s,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",fvfdtc:y-p}),R&&(this.ctx.slsReporter.reportConnectionLatencyEvent(Ye.FIRST_REMOTE,tt.DECODED,t,M.Audio,R),this.ctx.slsReporter.reportSubscribeFirstPacket(e===ge.Resume,t,i,M.Audio,{fprt:R-p,ifsprtc:R-p,ajsub:e===ge.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}))}),f.statsCheckPromise=A,f})}subscribeDelete(r){return I(this,null,function*(){const{remoteUser:e,options:t}=r,i=e.streamUrl.split("?")[0];if(!this.rtsClientMap.get(i))return null;const s=!!t.audio,n=!(!t.video&&!t.screen);if(this.destroyClientEntry(i),s&&n)return null;const c={};s||(c.audio=!0),n||(c.video=!0);const o=this.getOrCreateClientEntry(i),l=this.ctx.getSubConfig(e.streamInfo,c);this.ctx.handleHTTPConfig(l),l.disableHeartbeat=!0;try{const d=this.ctx.suffixHttpUrl(e.streamUrl,l),h=yield o.client.subscribe(d,l);o.connected=!0,o.traceId=h.traceId,T.info(`[${Dt}]`,"multiPCSubscribeDelete: re-subscribed remaining tracks",c)}catch(d){T.error(`[${Dt}]`,"multiPCSubscribeDelete: re-subscribe failed",d),this.destroyClientEntry(i)}return null})}getPublishVideoStats(r,e){return I(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishVideoStats(r,e)}return{}})}getPublishAudioStats(r,e){return I(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishAudioStats(r,e)}return{}})}getSubscribeVideoStats(r,e){return I(this,null,function*(){const t=r.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeVideoStats(r,e):{}})}getSubscribeAudioStats(r,e){return I(this,null,function*(){const t=r.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeAudioStats(r,e):{}})}getNetworkQuality(){return I(this,null,function*(){var i,s;let r=0,e=0,t=!1;for(const n of this.rtsClientMap.values())if(n.connected)try{const c=(s=(i=n.client.commonController)==null?void 0:i.peerCore)==null?void 0:s.pc;if(!c||c.connectionState==="disconnected"||c.connectionState==="failed"||c.connectionState==="closed")continue;t=!0;const o=c.getReceivers();let l=0,d=0,h=0;for(const u of o)(yield u.getStats()).forEach(f=>{f.type==="candidate-pair"&&typeof f.currentRoundTripTime=="number"&&(l=Math.round(1e3*f.currentRoundTripTime)),f.type!=="inbound-rtp"||f.mediaType!=="audio"&&f.mediaType!=="video"||(d+=f.packetsLost||0,h+=f.packetsReceived||0)});const p=h>0?Math.round(d/(d+h)*100):0;l>r&&(r=l),p>e&&(e=p)}catch(c){}return t?{rtt:r,loss:e,quality:cs(e,r)}:{rtt:0,loss:0,quality:Ze.AliRtcNetworkDisconnected}})}getPCStats(){return I(this,null,function*(){var r,e;if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return(e=(r=t.client.commonController.peerCore)==null?void 0:r.pc)==null?void 0:e.getStats()}})}getStreamByMsid(r){if(r!=null&&r.url){const e=r.url.split("?")[0],t=this.rtsClientMap.get(e);if(t)return t.client.commonController.streamManager.getStreamByMsid(r)}}updateAuth(r){const e=r.split("?")[0],t=this.rtsClientMap.get(e);t&&t.client.updateAuth(r)}sendSEI(r,e,t,i){return I(this,null,function*(){if(this.pubBaseUrl){const s=this.rtsClientMap.get(this.pubBaseUrl);if(s)return s.client.sendSEI({url:r,vMsid:M.VideoLarge,data:e,repeatCount:t,payloadType:i})}})}waitPublishSender(r,e=!1,t){return I(this,null,function*(){var s;const i=this.pubBaseUrl?(s=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:s.client:void 0;if(i)return Promise.race([Ut(1e3),((n,c)=>{let o=0;const l=()=>(e?i.getPublishAudioStats(r,t):i.getPublishVideoStats(r,t)).then(d=>!(d.bytesSent>0)&&o<n?(o++,new Promise(h=>setTimeout(()=>h(l()),c))):Promise.resolve());return l()})(5,100)]).catch(()=>{})})}clear(){for(const[r]of this.rtsClientMap)this.destroyClientEntry(r);this.rtsClientMap.clear(),this.pubBaseUrl=void 0}}var kc=Object.defineProperty,Pc=Object.getOwnPropertyDescriptor,ze=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Pc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&kc(r,e,s),s},Ci=(a=>(a.PUBLISH="publish",a.SUBSCRIBE="subscribe",a))(Ci||{});const Gi=([a])=>{const{remoteUser:r,options:e}=a;return[`user(${r.userId})`,e]};class Dc{constructor(r,e=5){m(this,"queue");m(this,"queue2");m(this,"batchFunc");m(this,"maxCount");m(this,"disabled",!1);m(this,"pendingFlush",Promise.resolve());this.queue=[],this.queue2=[],this.batchFunc=r,this.maxCount=e}add(r){return this.disabled?this.batchFunc([r]).then(e=>e.find(t=>t.url===r.url)||e[0]):(this.queue.length>=this.maxCount||this.queue2.length>=this.maxCount?this.flush():(e=>{if(typeof e!="function")throw new TypeError("Callback must be a function");typeof Promise!="undefined"?Promise.resolve().then(e).catch(t=>console.error(t)):setTimeout(e,0)})(this.flush.bind(this)),new Promise((e,t)=>{this.queue.find(i=>i.config.url===r.url)?this.queue2.push({config:r,resolve:e,reject:t}):this.queue.push({config:r,resolve:e,reject:t})}))}waitForPending(){return I(this,null,function*(){(this.queue.length>0||this.queue2.length>0)&&this.flush(),yield this.pendingFlush})}fallbackToSingleRequest(r){r.forEach(e=>{this.batchFunc([e.config]).then(t=>{const i=t.find(s=>s.url===e.config.url)||t[0];e.resolve(i)}).catch(t=>{e.reject(t)})})}handleError(r,e){var t;(t=r==null?void 0:r.message)!=null&&t.includes("Message too large")?(this.disabled=!0,T.warn("[Batcher]","Message too large, batcher disabled, fallback to single request"),this.fallbackToSingleRequest(e)):e.forEach(i=>i.reject(r))}flush(){if(this.queue.length===0&&this.queue2.length===0)return;const r=this.queue.map(i=>i),e=this.queue2.map(i=>i);this.queue=[],this.queue2=[];const t=[];[r,e].forEach(i=>{if(i.length>0)try{const s=this.batchFunc(i.map(n=>n.config)).then(n=>{n.forEach(c=>{const o=i.find(l=>l.config.url===c.url);o&&o.resolve(c)})}).catch(n=>{this.handleError(n,i)});t.push(s)}catch(s){this.handleError(s,i)}}),t.length>0&&(this.pendingFlush=Promise.all(t).then(()=>{}))}}const $e=(se=class extends oe{constructor(e,t,i){var s,n,c,o;super();m(this,"rts");m(this,"encodedInsertableStreams",!0);m(this,"audioRedEnabled",!1);m(this,"localStreamManager");m(this,"slsReporter");m(this,"_rtsPeerConnectionType","publish");m(this,"connecting",!1);m(this,"connected",!1);m(this,"rtsDisconnected",!1);m(this,"_pcTraceId","");m(this,"_localJoinTime",0);m(this,"connectionResolve");m(this,"connectingPromise");m(this,"dcResolve");m(this,"dcReject");m(this,"dcConnectingPromise");m(this,"_dcReady",!1);m(this,"_prevDownlinkStat");m(this,"_publishingTracks",[]);m(this,"parameter",{});m(this,"preferredPubL1Ip");m(this,"preferredSubL1Ip");m(this,"httpPublishUrlMap",{});m(this,"httpSubscribeUrlMap",{});m(this,"traceIdMap",{});m(this,"subUrlMap",{});m(this,"subscribeAddBatcher");m(this,"multiPC");if(this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher=new Dc(this.subscribeAddWithRetry.bind(this),((n=(s=this.parameter)==null?void 0:s.subscribe)==null?void 0:n.maxBatchCount)||3),((o=(c=this.parameter)==null?void 0:c.subscribe)==null?void 0:o.disableBatcher)===!0&&(this.subscribeAddBatcher.disabled=!0),(()=>{const l=(Tn.browserName||"").toLowerCase(),d=parseInt(Tn.browserVersion||"0",10);return l==="firefox"&&d>=148})()){T.info(`[${se.logName}]`,"Multi-PC mode enabled (Firefox 148+)"),this.subscribeAddBatcher.disabled=!0;const l=this,d={emit:(h,...p)=>l.emit(h,...p),suffixHttpUrl:l.suffixHttpUrl.bind(l),handleHTTPConfig:l.handleHTTPConfig.bind(l),getSubConfig:l.getSubConfig.bind(l),getPubMsid:l.getPubMsid.bind(l),reportSubscribeLatency:l.reportSubscribeLatency.bind(l),localStreamManager:l.localStreamManager,slsReporter:l.slsReporter,traceIdMap:l.traceIdMap,subUrlMap:l.subUrlMap,get pcTraceId(){return l._pcTraceId},set pcTraceId(h){l._pcTraceId=h},get localJoinTime(){return l._localJoinTime},get publishingTracks(){return l._publishingTracks},set publishingTracks(h){l._publishingTracks=h},get rtsPeerConnectionType(){return l._rtsPeerConnectionType},set rtsPeerConnectionType(h){l._rtsPeerConnectionType=h}};this.multiPC=new Cc(d)}}subscribeAddWithRetry(e){return hr(t=>I(this,null,function*(){return this._dcReady||(yield this.dcConnectingPromise),t>0&&T.event(`[${se.logName}]`,`subscribeAdd retry times: ${t}`),this.isConnected?this.rts.subscribeAdd(e):Promise.reject()}),10,100,t=>{var i,s,n,c;return(t==null?void 0:t.errorCode)===15006||(t==null?void 0:t.errorCode)===15004&&((c=(n=(s=(i=t.extraInfo)==null?void 0:i.parsedData)==null?void 0:s.streams)==null?void 0:n[0])==null?void 0:c.res_code)===404})}createRtsInstance(){var e,t;return K.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!1,signalDatachannelInitOptions:(t=(e=this.parameter)==null?void 0:e.net)!=null&&t.datachannelInitOptions?this.parameter.net.datachannelInitOptions:void 0})}addRTSListener(){this.rts.on("connectStatusChange",t=>{var i,s,n,c;if(T.event(`[${se.logName}]`,"rts connectStatusChange to:",t.status),t.status===K.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(t.status===K.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const o=(c=(n=(s=(i=this.rts.commonController)==null?void 0:i.peerCore)==null?void 0:s.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:c.readyState;T.event(`[${se.logName}]`,"dcReadyState:",o),o==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",t=>{var i,s,n;T.debug(`[${se.logName}]`,"reconnect",t),this.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(s=t.extraInfo)==null?void 0:s.msids)==null?void 0:n.map(c=>c.name))}),this.rts.on("reconnectFinish",t=>{var i;T.debug(`[${se.logName}]`,"reconnectFinish",t),this.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(i=t==null?void 0:t.msids)==null?void 0:i.map(s=>s.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(s){T.error(`[${se.logName}]`,"emit connected error:",s)}this.logCandidateProtocol("reconnectFinish")}),this.rts.on("datachannelStatusChange",t=>{T.event(`[${se.logName}]`,"rts datachannelStatusChange to:",t.status),t.status===K.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?(this._dcReady=!0,this.dcResolve&&this.dcResolve(!0)):t.status===K.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this._dcReady=!1,this.dcReject&&this.dcReject(new Error("signal datachannel closed")),this.dcConnectingPromise=new Promise((i,s)=>{this.dcResolve=i,this.dcReject=s}))}),this.rts.on("receivedSEI",t=>{var i;if(this.emit("seimessage",t.url,t.sei.payloadType,t.sei.data),t.sei.payloadType===99)try{const s=JSON.parse(new TextDecoder().decode(t.sei.data));this.slsReporter.reportLoopAudioDelay(((i=this.publishingTracks.find(n=>n.type==="audio"))==null?void 0:i.ssrc)||"",s)}catch(s){}}),this.rts.on("onError",t=>{T.event(`[${se.logName}]`,"rts onError event:",t)}),this.rts.on("reconnect",t=>{T.event(`[${se.logName}]`,"rts reconnect event:",t)}),this.rts.on("traceId",({url:t,traceId:i})=>{t&&i&&this.traceIdMap[t]!==i&&(this.traceIdMap[t]=i,this.emit("traceIdUpdated",t,i))});const e={sophon_audio:"audio",sophon_video_camera_large:"vlarge",sophon_video_camera_small:"vsmall",sophon_video_screen_share:"screen",sophon_data:"data"};this.rts.on("signalSent",t=>{const i=t.streams||[],s=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${s.join(", ")}`;T.event(`[${se.logName}]`,"rts signalSent event:",n,t)}),this.rts.on("signalReceived",t=>{const i=t.streams||[],s=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),l+=` ${c.res_code||""}`,c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${s.join(", ")}`;T.event(`[${se.logName}]`,"rts signalReceived event:",n,t)}),this.rts.on("hebtSent",t=>{var i,s,n;if((n=(s=(i=this.parameter)==null?void 0:i.net)==null?void 0:s.heartbeat)!=null&&n.enableLog){const c=Object.keys(this.subUrlMap).find(o=>{var l,d;return this.subUrlMap[o]===((d=(l=t.streams)==null?void 0:l[0])==null?void 0:d.url.split("?")[0])})||(t.streams?"pub":"empty");T.event(`[${se.logName}]`,"rts hebtSent event:",c,t)}}),this.rts.on("hebtReceived",t=>{var i,s,n,c,o,l,d;if((n=(s=(i=this.parameter)==null?void 0:i.net)==null?void 0:s.heartbeat)!=null&&n.enableLog){let h=`${Object.keys(this.subUrlMap).find(p=>{var u,f;return this.subUrlMap[p]===((f=(u=t.streams)==null?void 0:u[0])==null?void 0:f.url.split("?")[0])})||(t.streams?"pub":"empty")} ${((o=(c=t.streams)==null?void 0:c[0])==null?void 0:o.res_code)||""}`;(d=(l=t.streams)==null?void 0:l[0])!=null&&d.msid&&(h+=` ${t.streams[0].msid.map(p=>e[p.name]||p.name).join("+")}`),T.event(`[${se.logName}]`,"rts hebtReceived event:",h,t)}})}updateAuth(e){if(this.multiPC)return this.multiPC.updateAuth(e);this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setReceiverPreferredVideoCodecH265(){var s;let e=(s=RTCRtpReceiver.getCapabilities("video"))==null?void 0:s.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var s;let e=(s=RTCRtpSender.getCapabilities("video"))==null?void 0:s.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,s;return e===vt.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===vt.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===vt.AV1&&((s=RTCRtpSender.getCapabilities("video"))==null?void 0:s.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(T.info(`[${se.logName}]`,"changeVideoCodec to:",e),vt.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):T.warn(`[${se.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const s=i.findIndex(c=>c.mimeType==="audio/red"),n=i.findIndex(c=>c.mimeType==="audio/opus");if(s>-1&&n>-1&&s>n){const c=i[n];i[n]=i[s],i[s]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(i){}this.audioRedEnabled=e}}clear(){this.multiPC&&this.multiPC.clear(),this.setConnected(!1),this.rtsDisconnected=!1,this._dcReady=!1,this._publishingTracks=[],this._prevDownlinkStat=void 0;try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe()}catch(e){}this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher.batchFunc=this.subscribeAddWithRetry.bind(this)}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this._dcReady=!1,this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.multiPC?this.multiPC.isConnecting:this.connecting}get isConnected(){return this.multiPC?this.multiPC.isConnected:this.connected}suffixHttpUrl(e,t){const i=!t;let s=os(e,i?this.preferredPubL1Ip:this.preferredSubL1Ip);const n={ip_migration:"on",exception_detection:"on"},c=new URL(s),o=c.searchParams;Object.keys(n).forEach(p=>{o.has(p)||o.set(p,n[p])});const l=c.toString(),d=e.split("?")[0];i?this.httpPublishUrlMap[d]=l:this.httpSubscribeUrlMap[d]=l;let h="";return t&&(t.vMsid?t.aMsid||(h="@subaudio=no"):h="@subvideo=no"),l+h}getSuffixedUrl(e,t){const i=e.split("?")[0];return t?this.httpPublishUrlMap[i]||e:this.httpSubscribeUrlMap[i]||e}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:s}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[i!=null?i:M.Audio]),e.hasScreen&&(n.vMsid=[M.Screen]),e.hasVideo&&(n.vMsid=[s!=null?s:t!=null&&t.isScreen?M.Screen:M.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:s,codec:n,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${s}`,codec:n!=null?n:"",trackId:o})))}httpPublish(s){return I(this,arguments,function*(e,t=!1,i=kt.MANUAL){let n;const c=Date.now(),o=e.url,l=e.callId;this.startConnect();const{publishStream:d,videoSmallStream:h,screenStream:p,vMsid:u}=yield this.localStreamManager.createHTTPPublishStream();if(!d)return T.warn(`[${se.logName}]`,"publishStream is null"),{traceId:"",l1ip:n};const f=this.getPubMsid(d,{vMsid:u});f.answerSdpHook=_=>{const y=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(_);return y!=null&&y[0]&&(n=y[0]),_},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let g=!d.hasVideo,S=u,b="";const v=Date.now();try{b=yield this.publishWithPreferredL1Fallback(o,d,f)}catch(_){this.setConnected(!1);const y=2e3-(Date.now()-v);throw y<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},y),this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,(_==null?void 0:_.errorCode)||-1,this.pcTraceId,"",v,v),O.fromRtsError(_)}b&&(this._pcTraceId=b),T.event(`[${se.logName}]`,"rts publish success",b);const R=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,0,this.pcTraceId,e.traceId,v,R)},6e3),this.slsReporter.reportConnectionLatencyEvent(Ye.HANDLE_PUB_TASK,tt.START,l,b,c),this.slsReporter.reportConnectionLatencyEvent(Ye.HANDLE_PUB_TASK,tt.END,l,b,Date.now());try{const _=Date.now();return this._pcTraceId=b,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),h&&(yield this.publishAdd(e,h,{vMsid:M.VideoSmall},t),g=!1,S=M.VideoSmall),p&&(yield this.publishAdd(e,p,{vMsid:M.Screen},t),g=!1,S=M.Screen),yield this.waitPublishSender(o,g,S),this.slsReporter.reportPublishFirstPacket(t,l,v,_,this._localJoinTime,g?M.Audio:f.vMsid,b||"",b||"",i),{traceId:b,l1ip:n}}catch(_){throw this.setConnected(!1),O.fromError(_)}})}waitPublishSender(e,t=!1,i){return I(this,null,function*(){return this.multiPC?this.multiPC.waitPublishSender(e,t,i):Promise.race([Ut(1e3),((s,n)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(l=>!(l.bytesSent>0)&&c<s?(c++,new Promise(d=>setTimeout(()=>d(o()),n))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getPublishVideoStats(e,t):yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getPublishAudioStats(e,t):yield this.rts.getPublishAudioStats(e,t)})}publishAdd(o,l,d){return I(this,arguments,function*(e,t,i,s=!1,n=!1,c=kt.MANUAL){var g,S,b,v;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishAdd not supported in multi-PC mode"),"";const h=e.url,p=e.callId;this._dcReady||(yield this.dcConnectingPromise);const u=Date.now(),f=this.getPubMsid(t,i);try{const R=yield hr(_=>I(this,null,function*(){return _>0&&T.event(`[${se.logName}]`,`publishAdd retry times: ${_}`),this.isConnected?(this._dcReady||(yield this.dcConnectingPromise),this.rts.publishAdd([X({url:h,stream:t,updateSourceStream:!1},f)])):Promise.reject(new O(B.ERR_INNER,"rts not connected"))}),10,0,_=>(_==null?void 0:_.errorCode)===15006);if(R){const _=Date.now(),[y]=R,A=Date.now();return setTimeout(()=>{var w,E,C,P;this.slsReporter.reportPublish(!1,h,p,((w=f.vMsid)==null?void 0:w[0])===M.VideoLarge,((E=f.vMsid)==null?void 0:E[0])===M.VideoSmall,((C=f.vMsid)==null?void 0:C[0])===M.Screen,((P=f.aMsid)==null?void 0:P[0])===M.Audio,0,this.pcTraceId,y.traceId||"",u,A)},6e3),y.traceId&&(this._pcTraceId=y.traceId),this.updatePublishingTracks(y.trackInfoList),n&&(yield this.waitPublishSender(h,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(s,p,u,_,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,y.traceId||"",c),y.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,h,p,((g=f.vMsid)==null?void 0:g[0])===M.VideoLarge,((S=f.vMsid)==null?void 0:S[0])===M.VideoSmall,((b=f.vMsid)==null?void 0:b[0])===M.Screen,((v=f.aMsid)==null?void 0:v[0])===M.Audio,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",u),R!=null&&R.errorCode?O.fromRtsError(R):O.fromError(R)}return""})}publishDelete(e,t){return I(this,null,function*(){var l,d,h,p,u,f,g,S;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishDelete not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const i=(d=(l=this.publishingTracks)==null?void 0:l.find(({msid:b})=>b===M.Audio))==null?void 0:d.msid,s=(p=(h=this.publishingTracks)==null?void 0:h.find(({msid:b})=>b===M.VideoLarge))==null?void 0:p.msid,n=(f=(u=this.publishingTracks)==null?void 0:u.find(({msid:b})=>b===M.Screen))==null?void 0:f.msid,c=[];t.screen&&n?c.push(n):t.video&&c.push(t.vMsid||s);const o=[];t.audio&&i&&o.push(i),T.event(se.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[b]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return T.event(se.logName,"publishDelete",{result:b}),b&&this.updatePublishingTracks(b.trackInfoList),((S=(g=b==null?void 0:b.trackInfoList)==null?void 0:g[0])==null?void 0:S.trackId)||""}catch(b){throw O.fromRtsError(b)}})}publishReplace(e,t,i){return I(this,null,function*(){var c,o;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishReplace not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const{vMsid:s,aMsid:n}=i!=null?i:{};try{const l=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:s,aMsid:n}]),[d]=l;return this.updatePublishingTracks(d.trackInfoList),((o=(c=d==null?void 0:d.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(l){throw O.fromRtsError(l)}})}publishStop(e){return I(this,null,function*(){return this.multiPC?(yield this.multiPC.publishStop(e),""):(yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],"")})}publishAddDataChannel(e){return I(this,null,function*(){if(this.multiPC)return T.warn(`[${se.logName}]`,"publishAddDataChannel not supported in multi-PC mode"),null;this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.publishAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!0),label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const s=new ArrayBuffer(4);new DataView(s).setUint8(0,240),i.datachannel.send(s)}return i})}publishStopDataChannel(e,t){return I(this,null,function*(){return this.multiPC?void T.warn(`[${se.logName}]`,"publishStopDataChannel not supported in multi-PC mode"):yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return I(this,null,function*(){if(this.multiPC)return yield this.multiPC.unpublish(),void(this._publishingTracks=[]);yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getMultiPCNetworkQuality(){return I(this,null,function*(){return this.multiPC?this.multiPC.getNetworkQuality():{rtt:0,loss:0,quality:Ze.AliRtcNetworkDisconnected}})}getSubscribeNetworkQuality(){return I(this,null,function*(){var u;if(this.multiPC)return this.getMultiPCNetworkQuality();const e=(u=this.rts.commonController.peerCore)==null?void 0:u.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:Ze.AliRtcNetworkDisconnected};let t=0,i=0,s=0;const n=e.getReceivers();for(const f of n)(yield f.getStats()).forEach(g=>{g.type==="candidate-pair"&&typeof g.currentRoundTripTime=="number"&&(t=Math.round(1e3*g.currentRoundTripTime)),g.type!=="inbound-rtp"||g.mediaType!=="audio"&&g.mediaType!=="video"||(i+=g.packetsLost||0,s+=g.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:0,quality:Ze.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=s-o;let h=0;l>0&&d>=0&&(h=Math.round(l/(l+d)*100));const p=cs(h,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:h,quality:p}})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const s={};return i.audio&&(s.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||M.Audio]),i.video?i.vMsid?s.vMsid=[i.vMsid]:s.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||M.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||M.VideoSmall]:[M.VideoLarge]:i.screen&&(s.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||M.Screen]),s}handleHTTPConfig(e){var i,s,n,c,o,l,d,h,p,u,f,g;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(s=(i=this.parameter)==null?void 0:i.net)!=null&&s.useTCP&&(e.tcpOnly=!0),(c=(n=this.parameter)==null?void 0:n.net)!=null&&c.cumuDelay&&(e.cumuDelay=!0),(l=(o=this.parameter)==null?void 0:o.net)!=null&&l.disableHeartbeat&&(e.disableHeartbeat=!0),(h=(d=this.parameter)==null?void 0:d.net)!=null&&h.heartbeat&&(e.heartbeat=this.parameter.net.heartbeat),(u=(p=this.parameter)==null?void 0:p.net)==null?void 0:u.mediaTimeout){const S=(g=(f=this.parameter)==null?void 0:f.net)==null?void 0:g.mediaTimeout;S>1e3&&S<1e5&&(e.mediaTimeout=S)}e.offerSdpHook=so;let t=0;e.beforeRetry=S=>I(this,null,function*(){if(t++,T.info(`[${se.logName}]`,`before retry, retryCount: ${t}`),t>=2&&S.url.includes("ali_prefer_media_server"))try{const b=new URL(S.url);b.searchParams.delete("ali_prefer_media_server"),S.url=b.toString(),T.info(`[${se.logName}]`,`removed ali_prefer_media_server, fallback url: ${S.url}`)}catch(b){T.error(`[${se.logName}]`,"failed to parse url for removing ali_prefer_media_server",S.url,b)}return S}),e.retryTimes=17,e.retryInterval=5e3,T.info(`[${se.logName}]`,"http config",e)}httpSubscribe(e){return I(this,null,function*(){const{remoteUser:t,options:i}=e,s=t.streamUrl,n=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(n),this._rtsPeerConnectionType="subscribe";try{this.startConnect();const c=yield this.subscribeWithPreferredL1Fallback(s,n);return this._pcTraceId=c.traceId,this.setConnected(!0),{traceId:c.traceId,stream:c}}catch(c){throw this.setConnected(!1),this.emit("disconnected"),O.fromRtsError(c)}})}subscribeWithPreferredL1Fallback(e,t){return I(this,null,function*(){if(this.preferredSubL1Ip){const s=this.suffixHttpUrl(e,t),n=new Promise((c,o)=>{setTimeout(()=>o(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const c=yield Promise.race([this.rts.subscribe(s,t),n]);return this.logCandidateProtocol("subscribe (preferred L1)"),c}catch(c){if(c.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${se.logName}]`,"Preferred L1 subscribe timeout, clearing preferredSubL1Ip and falling back to DNS"),this.preferredSubL1Ip=void 0;const o=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe (fallback)"),o}throw c}}const i=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe"),i})}publishWithPreferredL1Fallback(e,t,i){return I(this,null,function*(){if(this.preferredPubL1Ip){const n=this.suffixHttpUrl(e),c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rts.publish(n,t,i),c]);return this.logCandidateProtocol("publish (preferred L1)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${se.logName}]`,"Preferred L1 publish timeout, clearing preferredPubL1Ip and falling back to DNS"),this.preferredPubL1Ip=void 0;const l=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish (fallback)"),l}throw o}}const s=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish"),s})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,s=ft(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return this.subscribeAddBatcher.disabled?(yield this.subscribeAddWithRetry([s]))[0]:yield this.subscribeAddBatcher.add(s)}catch(d){if((d==null?void 0:d.errorCode)===15011)return T.info(`[${se.logName}]`,"subscribeAdd ignored",d==null?void 0:d.message),null;if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===508)return this.emit("subscribeexceeds"),null;throw O.fromRtsError(d)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,l;if(this.multiPC)return this.multiPC.subscribeDelete(e);yield this.subscribeAddBatcher.waitForPending();const{remoteUser:t,options:i}=e,s=ft(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return T.event(`[${se.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:s.url,subAudio:s.subAudio,subVideo:s.subVideo,aMsid:s.aMsid,vMsid:s.vMsid})),(yield this.rts.subscribeDeleteTracks([s]))[0]}catch(d){if((d==null?void 0:d.errorCode)===15011)return T.info(`[${se.logName}]`,"subscribeDelete ignored",d==null?void 0:d.message),null;if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===404)return null;throw O.fromRtsError(d)}})}updateSubscribeBatcher(e){e.disableBatcher!==void 0&&(this.subscribeAddBatcher.disabled=e.disableBatcher),e.maxBatchCount!==void 0&&(this.subscribeAddBatcher.maxCount=e.maxBatchCount)}subscribeAddDataChannel(e){return I(this,null,function*(){if(this.multiPC)return T.warn(`[${se.logName}]`,"subscribeAddDataChannel not supported in multi-PC mode"),null;yield this.subscribeAddBatcher.waitForPending(),this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!1),label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const s=new ArrayBuffer(4);new DataView(s).setUint8(0,240),i.send(s)}return i})}subscribeDeleteDatachannel(e,t){return I(this,null,function*(){if(this.multiPC)return void T.warn(`[${se.logName}]`,"subscribeDeleteDatachannel not supported in multi-PC mode");let i;yield this.subscribeAddBatcher.waitForPending();try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:M.Data,datachannel:t})}catch(s){}return i})}publish(s){return I(this,arguments,function*(e,t=!1,i=kt.MANUAL){if(this.multiPC)return this.multiPC.publish(e,t,i);const n=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){this._dcReady||(yield this.dcConnectingPromise);let l,d=!1;const{audio:h,video:p,videoSmall:u,screen:f}=this.localStreamManager.publishStreams;h&&(o=yield this.publishAdd(e,h,{aMsid:M.Audio},t),d=!0,l=M.Audio,yield Ut(100)),p&&(o=yield this.publishAdd(e,p,{vMsid:M.VideoLarge},t),d=!1,l=M.VideoLarge,yield Ut(100)),u&&(o=yield this.publishAdd(e,u,{vMsid:M.VideoSmall},t),d=!1,l=M.VideoSmall,yield Ut(100)),f&&(o=yield this.publishAdd(e,f,{isScreen:!0,vMsid:M.Screen},t),d=!1,l=M.Screen),l&&(yield this.waitPublishSender(n,d,l))}else{const l=yield this.httpPublish(e,t,i);o=l.traceId,c=l.l1ip}return{traceId:o,l1ip:c}})}reportSubscribeLatency(e,t,i,s){const n=[];e.audio&&n.push(e.aMsid||M.Audio),e.video?n.push(e.vMsid||M.VideoLarge):e.screen&&n.push(M.Screen),n.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(Ye.HANDLE_SUB_TASK,tt.START,t,c,i,0,s),this.slsReporter.reportConnectionLatencyEvent(Ye.HANDLE_SUB_TASK,tt.END,t,c,Date.now(),0,s)})}subscribe(e,t,i,s,n){return I(this,null,function*(){if(this.multiPC)return this.multiPC.subscribe(e,t,i,s,n);let c=!1;const{options:o,remoteUser:l}=e;if(o.video&&o.screen)throw new O(B.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise),this.subUrlMap[l.userId]=l.streamUrl.split("?")[0];let h=Date.now();if(this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),!d)return null;this.reportSubscribeLatency(o,i,h,c);const p=Date.now();let u=M.VideoLarge,f=o.video||o.screen,g=o.audio;o.video&&o.vMsid?u=o.vMsid:o.screen&&(u=M.Screen);let S=0,b=0,v=0;const R=((_,y)=>{let A=0;const w=()=>{let E;return g&&!S&&(E=this.rts.getSubscribeAudioStats(l.streamUrl).then(C=>{if(C.packetsReceived>0)S=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 音频首包");else if(!f)return A<_&&(A++,new Promise(P=>setTimeout(()=>P(w()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(l.streamUrl,u).then(C=>{if(typeof C.packetsReceived=="number")return!b&&C.packetsReceived>0&&(b=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 视频首包")),C.framesDecoded>0?(v=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 视频首帧数据"),!0):A<_?(A++,new Promise(P=>setTimeout(()=>P(w()),y))):(T.event(`[${se.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)})),Promise.resolve(E)};return w()})(20,100);return R.then(()=>{b&&this.slsReporter.reportSubscribeFirstPacket(t===ge.Resume,i,s,u,{fprt:b-h,ifsprtc:v?v-h:0,ajsub:t===ge.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}),v&&this.slsReporter.reportSubscribeFirstFrame(t===ge.Resume,i,s,u,{fvfrt:v-h,fp2fftc:v-b,ajsub:t===ge.Join?1:0,tffrtc:t===ge.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-h}),S&&(this.slsReporter.reportConnectionLatencyEvent(Ye.FIRST_REMOTE,tt.DECODED,i,M.Audio,S),this.slsReporter.reportSubscribeFirstPacket(t===ge.Resume,i,s,M.Audio,{fprt:S-h,ifsprtc:S-h,ajsub:t===ge.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}))}),d&&(d.isHTTP=c,d.statsCheckPromise=R),d})}getSubscribeVideoStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeVideoStats(e,t):yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeAudioStats(e,t):yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){if(this.multiPC){const t=this.multiPC.getStreamByMsid(e);if(t)return t}return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){var t;return this.multiPC?(T.warn(`[${se.logName}]`,"getDatachannelByMsid not supported in multi-PC mode"),null):(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(e)}getPCStats(){return I(this,null,function*(){var e,t;return this.multiPC?this.multiPC.getPCStats():(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}logCandidateProtocol(e){return I(this,null,function*(){var t,i;try{const s=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.pc;if(!s)return void T.debug(`[${se.logName}]`,`${e} - PC not available`);const n=yield s.getStats();let c,o,l,d;n.forEach(h=>{h.type==="candidate-pair"&&h.state==="succeeded"&&h.nominated&&(c=h.localCandidateId,o=h.remoteCandidateId)}),c||o||n.forEach(h=>{h.type!=="candidate-pair"||h.state!=="succeeded"&&h.state!=="in-progress"||c||(c=h.localCandidateId,o=h.remoteCandidateId)}),n.forEach(h=>{h.type==="local-candidate"&&h.id===c&&(l=h.protocol),h.type==="remote-candidate"&&h.id===o&&(d=h.protocol)}),T.event(`[${se.logName}]`,`${e} - Candidate Protocol: local=${l||"unknown"}, remote=${d||"unknown"}`)}catch(s){T.warn(`[${se.logName}]`,`${e} - Failed to get candidate protocol:`,s)}})}sendSEI(e,t,i,s){return I(this,null,function*(){return this.multiPC?this.multiPC.sendSEI(e,t,i,s):this.rts.sendSEI({url:e,vMsid:M.VideoLarge,data:t,repeatCount:i,payloadType:s})})}},m(se,"logName","RtsManager"),se);ze([k(H)],$e.prototype,"startConnect",1),ze([k()],$e.prototype,"updatePublishingTracks",1),ze([k(H,H)],$e.prototype,"httpPublish",1),ze([k(H,H)],$e.prototype,"waitPublishSender",1),ze([k(([a,r,e])=>[a,JSON.stringify(e)],H)],$e.prototype,"publishAdd",1),ze([k(H,H)],$e.prototype,"publishDelete",1),ze([k(([a,r,e])=>[a,JSON.stringify(e)])],$e.prototype,"publishReplace",1),ze([k(H)],$e.prototype,"publishStop",1),ze([k(H)],$e.prototype,"publishAddDataChannel",1),ze([k(H)],$e.prototype,"publishStopDataChannel",1),ze([k()],$e.prototype,"unpublish",1),ze([k(Gi,({traceId:a})=>a)],$e.prototype,"httpSubscribe",1),ze([k(Gi,({traceId:a})=>a)],$e.prototype,"subscribeAdd",1),ze([k(Gi)],$e.prototype,"subscribeDelete",1),ze([k(H)],$e.prototype,"subscribeAddDataChannel",1),ze([k(H)],$e.prototype,"subscribeDeleteDatachannel",1),ze([k(H)],$e.prototype,"publish",1),ze([k(Gi)],$e.prototype,"subscribe",1),ze([k()],$e.prototype,"sendSEI",1);let Mc=$e;class js{constructor(r=Us){m(this,"defaultProfile");m(this,"profile");m(this,"profileMap",new Map);m(this,"audioProfile");m(this,"contentHint");this.defaultProfile=X({},r)}updateProfile(r,e){this.profileMap.set(r,X(X(X({},this.defaultProfile),this.profileMap.get(r)||{}),e||{})),this.profile=r}get videoProfile(){return this.profile}updateAudioProfile(r){this.audioProfile=r}setContentHint(r,e){e&&(this.contentHint=e),this.contentHint&&r&&(r.contentHint=this.contentHint)}setVideoProfile(r,e,t=!1){return I(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&r&&r.readyState==="live"&&r.applyConstraints)try{yield r.applyConstraints(i)}catch(s){}if(e){const s=X({},i);i.maxSendFrameRate&&(s.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,s),yield e.setVideoProfile(this.profile)}}})}}const Ft=class Ft{static acquire(r){if(!r||!r.id)return;const e=Ft.refCounts.get(r.id);e?e.count++:Ft.refCounts.set(r.id,{track:r,count:1})}static release(r){if(!r||!r.id)return!1;const e=Ft.refCounts.get(r.id);return e?(e.count--,e.count<=0&&(Ft.refCounts.delete(r.id),r.stop(),!0)):(r.stop(),!0)}static getRefCount(r){var e,t;return r&&r.id&&(t=(e=Ft.refCounts.get(r.id))==null?void 0:e.count)!=null?t:0}static reset(){Ft.refCounts.clear()}};m(Ft,"refCounts",new Map);let Jt=Ft;var Ue=(a=>(a[a.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",a[a.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",a))(Ue||{});class $s extends oe{constructor(e){super();m(this,"type");m(this,"originVideoTrack");m(this,"videoSource");m(this,"_videoMuted",!1);m(this,"originAudioTrack");m(this,"audioSource");m(this,"_audioMuted",!1);m(this,"_targetVideoTrack");m(this,"_targetDualVideoTrack");m(this,"_targetAudioTrack");m(this,"_publishVideoStream");m(this,"_publishDualVideoStream");m(this,"_publishAudioStream");m(this,"_previewStream");m(this,"plugins",[]);m(this,"_profileManager");m(this,"cameraVideoConstraints");m(this,"micAudioConstraints");m(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});m(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return I(this,null,function*(){var c,o,l,d;const{videoTrack:s,audioTrack:n}=e;s&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Ue.AliRtcSdkStreamTypeScreen?this.stop():(s&&this.originVideoTrack&&Jt.release(this.originVideoTrack),n&&this.originAudioTrack&&Jt.release(this.originAudioTrack)),s&&(this.originVideoTrack=s,Jt.acquire(s),(l=this.originVideoTrack)==null||l.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||Ri.Camera,this.updateVideoTrack(s)),n&&(this.originAudioTrack=n,Jt.acquire(n),(d=this.originAudioTrack)==null||d.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Ui.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return I(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return I(this,null,function*(){var t,i,s,n,c,o,l,d,h,p,u,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const g of this.plugins)try{yield g.execute(this,e)}catch(S){console.error(`error in plugin-${g.name}, error: ${S}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield Ti(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(s=this.profileManager)==null||s.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield Ti(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Ti(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(h=this._publishAudioStream)==null?void 0:h.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Ti(this._targetAudioTrack),this.audioProfile&&(yield this._publishAudioStream.setAudioProfile(this.audioProfile)),this.setAudioMuted(this._audioMuted),this.previewStream?(u=this.previewStream)==null||u.mergeStream(this._publishAudioStream):this._previewStream=yield Ti(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){this.originVideoTrack&&(this.originVideoTrack.removeEventListener("ended",this.onVideoTrackEnded),Jt.release(this.originVideoTrack),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){this.originAudioTrack&&(this.originAudioTrack.removeEventListener("ended",this.onAudioTrackEnded),Jt.release(this.originAudioTrack),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return I(this,null,function*(){this._profileManager||(this._profileManager=new js(this.type===Ue.AliRtcSdkStreamTypeScreen?An:Us)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new js(this.type===Ue.AliRtcSdkStreamTypeScreen?An:Us)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new js),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return I(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}cloneAudioProfile(e){return I(this,null,function*(){this.audioProfile&&(yield e.setAudioProfile(this.audioProfile))})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var Lc=Object.defineProperty,Nc=Object.getOwnPropertyDescriptor,_t=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Nc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Lc(r,e,s),s};const yt=(Xt=class extends oe{constructor(e,t){super();m(this,"pluginManager");m(this,"slsReporter");m(this,"publishingCameraVideoStream");m(this,"publishingScreenVideoStream");m(this,"cameraStreamInfo",new $s(Ue.AliRtcSdkStreamTypeCapture));m(this,"screenStreamInfo",new $s(Ue.AliRtcSdkStreamTypeScreen));m(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);m(this,"_audioCaptureDisabled",!1);m(this,"_cameraCaptureDisabled",!1);m(this,"_publishLocalAudioStreamEnabled",!0);m(this,"_publishLocalVideoStreamEnabled",!0);m(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",ai.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",ai.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",ai.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(T.info(`[${Xt.logName}]`,"plugin added",i.name),!i.isSupported("7.2.8-beta.3"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(s){i.emit("error",O.fromError(s,Kt.AliRtcPluginErrorInitError))}i.streamType===Ue.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Ue.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>I(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>I(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return I(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return I(this,null,function*(){var e,t,i,s;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield K.AliRTS.getCameraList();c.find(o=>o.deviceId===n)||(n=(s=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?s:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return I(this,null,function*(){var e,t,i,s;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield K.AliRTS.getMicList();c.find(o=>o.deviceId===n)||(n=(s=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?s:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return I(this,null,function*(){var h;const{screen:t,mediaStream:i,videoProfile:s,screenProfile:n}=e;let{video:c,audio:o}=e;const l=(p=>{const{audio:u,video:f,screen:g}=p;if(f&&g)throw new O(B.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||u||g)})(e);let d;if(l){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=X({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=X(X({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=X({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=X(X({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const p=Date.now();try{d=yield K.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),T.info(`[${Xt.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((h=d==null?void 0:d.audioTrack)==null?void 0:h.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p)}catch(u){throw o&&!i&&this.slsReporter.reportAudio(u,Date.now()-p,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p),u}if(t)yield this.screenStreamInfo.updateSource(d,Ri.Screen,Ui.Screen),yield this.setScreenProfile(n||Rn),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,Ri.Camera,Ui.Microphone),d.hasVideo&&(yield this.setVideoProfile(s||yn),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const u=this.cameraStreamInfo.audioProfile;u&&(yield d.setAudioProfile(u))}}return K.AliRTS.SystenUtil.isIos&&K.AliRTS.SystenUtil.compareVersion("15.1")&&!K.AliRTS.SystenUtil.compareVersion("15.2")&&(yield Ut(1e3)),yield this.updateStreams(),d})}stopLocalStream(e){return I(this,null,function*(){const{screen:t,video:i,audio:s}=e!=null?e:{};let n=!1;i&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),s&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return I(this,null,function*(){var o,l,d,h;let e,t,i,s,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw T.error(`[${Xt.logName}]`,"no tracks founded"),new O(B.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,s=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=M.Screen,p.addTrack((h=c.screen)==null?void 0:h.videoTrack),n=!0),e=yield In(p),n?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e),this.cameraStreamInfo.cloneAudioProfile(e)}catch(p){}return{publishStream:e,videoSmallStream:i,screenStream:s,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return I(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return I(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return I(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=X(X({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=X(X({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},m(Xt,"logName","LocalStreamManager"),Xt);_t([k(([a])=>{const{audio:r,video:e,screen:t,custom:i,skipProfile:s,videoProfile:n,screenProfile:c}=a;return[{audio:r,video:e,screen:t,custom:i,skipProfile:s,videoProfile:n,screenProfile:c}]})],yt.prototype,"createLocalStream",1),_t([k(H)],yt.prototype,"stopLocalStream",1),_t([k()],yt.prototype,"createHTTPPublishStream",1),_t([k()],yt.prototype,"stop",1),_t([k(H)],yt.prototype,"setVideoProfile",1),_t([k(H)],yt.prototype,"setVideoContentHint",1),_t([k(H)],yt.prototype,"setAudioProfile",1),_t([k(H)],yt.prototype,"setScreenProfile",1),_t([k(H)],yt.prototype,"setScreenContentHint",1),_t([k(H)],yt.prototype,"setCameraVideoConstraints",1),_t([k(H)],yt.prototype,"setMicAudioConstraints",1);let xc=yt;var Cn=(a=>(a[a.PRE_PROCESSOR=0]="PRE_PROCESSOR",a[a.POST_PROCESSOR=1]="POST_PROCESSOR",a))(Cn||{}),gi=(a=>(a[a.AUDIO=0]="AUDIO",a[a.VIDEO=1]="VIDEO",a[a.BOTH=2]="BOTH",a))(gi||{});class Ht extends oe{constructor(e,t=Ue.AliRtcSdkStreamTypeCapture,i=1){super();m(this,"name");m(this,"options");m(this,"type",0);m(this,"streamType");m(this,"trackType");m(this,"zIndex",1);m(this,"_isEnable",!0);m(this,"shouldCache",!0);m(this,"lastInputAudioTrack");m(this,"lastOutputAudioTrack");m(this,"lastInputVideoTrack");m(this,"lastOutputVideoTrack");m(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return I(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return I(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class Vc extends Ht{constructor(){super("AliRtcScreenStandardize",Ue.AliRtcSdkStreamTypeScreen);m(this,"canvas");m(this,"lastWidth");m(this,"lastHeight");m(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,s=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=s,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,i,s)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===Ri.Screen){const s=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(s){const{width:n,height:c}=s;t=!n||!c||!(n%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return I(this,null,function*(){var n;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const s=(n=this.canvas)==null?void 0:n.getContext("2d");if(this.canvas&&s){s.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return I(this,null,function*(){var d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const h=e.originVideoTrack.getSettings();if(h){const{width:p,height:u}=h;if(!(!p||!u||!(p%this.options.base===0&&u%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),s=new MediaStream([i]),n=this,c=new TransformStream({transform(h,p){return I(this,null,function*(){const u=yield n.handleFrame(h);yield p.enqueue(u),u==null||u.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=s.getVideoTracks())==null?void 0:d[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class Oc extends Ht{constructor(){super("blankAudio",Ue.AliRtcSdkStreamTypeCapture,gi.BOTH);m(this,"hasTrack",!1);m(this,"oscillator",null);m(this,"audioTrack",null);m(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const s=i.stream;return this.audioTrack=s.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return I(this,null,function*(){var s;const i=t.some(n=>n.originVideoTrack||n.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((s=this.oscillator)==null||s.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}var Ws=(a=>(a[a.NONE=0]="NONE",a[a.ERROR=1]="ERROR",a[a.WARN=2]="WARN",a[a.INFO=3]="INFO",a[a.DEBUG=4]="DEBUG",a[a.TRACE=5]="TRACE",a))(Ws||{});const ts=class ts{constructor(r){m(this,"name","COMMON");m(this,"instanceLevel");this.name=r||this.name}setLevel(r){this.instanceLevel=r}getEffectiveLevel(){return this.instanceLevel!==void 0?this.instanceLevel:ts.LEVEL}info(...r){this.getEffectiveLevel()>=3&&this.print(Ws[3],...r)}warn(...r){this.getEffectiveLevel()>=2&&this.print(Ws[2],...r)}print(r,...e){const t=r.toLowerCase();t&&console[t](`[${r}][${this.name}]`,...e)}};m(ts,"LEVEL",0);let zs=ts;class Uc{constructor(){m(this,"logger",new zs("AudioMixer"));m(this,"audioContext",bt.getInstance());m(this,"audioDestination",this.audioContext.createMediaStreamDestination());m(this,"audioTrack",(r=>r.getAudioTracks()[0])(this.audioDestination.stream));m(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.sourceNode).filter(r=>!!r)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.gainNode).filter(r=>!!r)}get sourceCount(){return this.sourceNodeList.length}resume(){var r;return(r=this.audioContext)==null?void 0:r.resume()}addTrack(r){this.connectTrack(r)}hasTrack(r){return!!this.sourceNodeMap[r]}removeTrack(r){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[r]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[r],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${r} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(r,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(r)}`),t.gain.value=this.scale(r)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var r;this.reset(),(r=this.audioTrack)==null||r.stop(),this.audioDestination.disconnect()}connectTrack(r){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(r);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[r.id]={track:r,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(r=>r.disconnect()),this.gainNodeList.forEach(r=>r.disconnect())}scale(r){return r/100}}class Bc extends Ht{constructor(){super("audioMixer",Ue.AliRtcSdkStreamTypeCapture,gi.AUDIO);m(this,"audioMixer");m(this,"primaryAudioTrackId");m(this,"screenAudioTrackId");m(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,c;if(e.type!==Ue.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Ue.AliRtcSdkStreamTypeCapture),s=t.find(o=>o.type===Ue.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=i==null?void 0:i.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((c=s==null?void 0:s.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return I(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(l=>l.type===Ue.AliRtcSdkStreamTypeScreen),s=e.currentAudioTrack,n=i==null?void 0:i.currentAudioTrack;if(!n&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=s==null?void 0:s.id,void e.updateAudioTrack(s);this.audioMixer||(this.audioMixer=new Uc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(s==null?void 0:s.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),s&&!this.audioMixer.hasTrack(s==null?void 0:s.id)&&this.audioMixer.addTrack(s),this.primaryAudioTrackId=s==null?void 0:s.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class Hc extends Ht{constructor(){super(...arguments);m(this,"isProcessing",!1);m(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return ys.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=ys.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function fi(a,r,e,t){return new(e||(e=Promise))(function(i,s){function n(l){try{o(t.next(l))}catch(d){s(d)}}function c(l){try{o(t.throw(l))}catch(d){s(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(h){h(d)})).then(n,c)}o((t=t.apply(a,r||[])).next())})}var Gt,Mt;function kn(){return fi(this,void 0,void 0,function*(){let a=!1;try{a=yield(()=>I(this,null,function*(){return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}))()}catch(r){a=!1}return console.log("isSupportedSIMD",a),a})}typeof SuppressedError=="function"&&SuppressedError,(Mt=Gt||(Gt={}))[Mt.ERROR=0]="ERROR",Mt[Mt.WARN=1]="WARN",Mt[Mt.INFO=2]="INFO",Mt[Mt.LOG=3]="LOG",Mt[Mt.DEBUG=4]="DEBUG";class Ae{static error(...r){var e;Ae.logLevel>=Gt.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${Ae.logTag}] `,...r))}static warn(...r){var e;Ae.logLevel>=Gt.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${Ae.logTag}] `,...r))}static info(...r){var e;Ae.logLevel>=Gt.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${Ae.logTag}] `,...r))}static log(...r){var e;Ae.logLevel>=Gt.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${Ae.logTag}] `,...r))}static debug(...r){var e;Ae.logLevel>=Gt.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${Ae.logTag}] `,...r))}}Ae.logLevel=Gt.WARN,Ae.logTag="aliyun-audio-3a";class Fc{}class Pn extends Fc{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const r="AudioWorklet"in window,e="WebAssembly"in window;return r&&e}return!1}()}static isSupportedSIMD(){return fi(this,void 0,void 0,function*(){return yield kn()})}static setLogger(r){Ae.logLevel=r}constructor(r){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},r||{})}initWASM(r,e,t){return fi(this,void 0,void 0,function*(){Ae.log("initWASM",r,e,t);const i=n=>fi(this,void 0,void 0,function*(){try{const c=yield fetch(n,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${n}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),Ae.error("Error fetching WASM:",c),new Uint8Array(0)}}),s=n=>fi(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield kn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(n?o:c),h=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",u=n?p:h,f=yield s(u);r.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:n,audioModuleScript:f,logLevel:Ae.logLevel},this.options),[d])}catch(n){Ae.error("Error initializing WASM:",n),this.onLoadError(new Error("WASM init error"))}r.port.onmessage=n=>{n.data.type==="init_done"&&this.onLoadSuccess(void 0),n.data.type==="dump_output_data"&&this.onDumpOutputData(n.data.data),n.data.type==="dump_near_data"&&this.onDumpNearInputData(n.data.data),n.data.type==="dump_far_data"&&this.onDumpFarInputData(n.data.data),n.data.type==="dump_meta_data"&&this.onDumpMeatData(n.data.data),n.data.type==="output_log"&&this.onOutputLog(n.data.data),n.data.type==="apm_stat_data"&&this.onStatData(n.data.data)}})}createProcessor(r,e,t,i,s){return fi(this,void 0,void 0,function*(){this.audioContext=r,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var Rl=Object.defineProperty,Al=Object.defineProperties;var wl=Object.getOwnPropertyDescriptors;var ss=Object.getOwnPropertySymbols,_l=Object.getPrototypeOf,to=Object.prototype.hasOwnProperty,io=Object.prototype.propertyIsEnumerable,Il=Reflect.get;var cr=(z,K,oe)=>K in z?Rl(z,K,{enumerable:!0,configurable:!0,writable:!0,value:oe}):z[K]=oe,X=(z,K)=>{for(var oe in K||(K={}))to.call(K,oe)&&cr(z,oe,K[oe]);if(ss)for(var oe of ss(K))io.call(K,oe)&&cr(z,oe,K[oe]);return z},ft=(z,K)=>Al(z,wl(K));var jt=(z,K)=>{var oe={};for(var st in z)to.call(z,st)&&K.indexOf(st)<0&&(oe[st]=z[st]);if(z!=null&&ss)for(var st of ss(z))K.indexOf(st)<0&&io.call(z,st)&&(oe[st]=z[st]);return oe};var m=(z,K,oe)=>(cr(z,typeof K!="symbol"?K+"":K,oe),oe);var lr=(z,K,oe)=>Il(_l(z),oe,K);var I=(z,K,oe)=>new Promise((st,xt)=>{var hi=rt=>{try{bt(oe.next(rt))}catch(St){xt(St)}},ui=rt=>{try{bt(oe.throw(rt))}catch(St){xt(St)}},bt=rt=>rt.done?st(rt.value):Promise.resolve(rt.value).then(hi,ui);bt((oe=oe.apply(z,K)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}catch(o){Ae.error("Failed to add module to audio worklet:",o)}let n=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=n,e.connect(n),s&&(this.farNode=s,s.connect(n,0,1));const c=this.audioContext.createMediaStreamDestination();n.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(n,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(r){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),r&&(this.farNode=r,r.connect(this.workletNode,0,1)))}getStatData(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"get_stat_data"})}catch(e){Ae.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),Ae.log("postMessage destroy")}catch(r){Ae.error("Failed to post message to worklet node:",r)}}startDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"start_dump"})}catch(e){Ae.error("Failed to post message to worklet node:",e)}}stopDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"stop_dump"})}catch(e){Ae.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(r,e=!1){if(r&&r.length>0&&this.collectDumpOutputData.push(r),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpNearInputData.push(r),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpFarInputData.push(r),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(r,e=!1){if(r&&r.length>0&&this.collectDumpMetaData.push(r),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{this.workletNode.port.postMessage({type:"enable"}),Ae.log("postMessage enable")}catch(e){Ae.error("Failed to post message to worklet node:",e)}}disable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{Ae.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){Ae.error("Failed to post message to worklet node:",e)}}on(r,e){r==="loaderror"&&(this.onLoadError=e),r==="loadsuccess"&&(this.onLoadSuccess=e),r==="dumpdata"&&(this.onDumpData=e),r==="outputlog"&&(this.onOutputLog=e),r==="statdata"&&(this.onStatData=e)}onLoadError(r){console.log("onLoadError",r)}onLoadSuccess(r){console.log("onLoadSuccess",r)}onDumpData(r,e){console.log("onDumpData",r,e)}onOutputLog(r){console.log("[WASM]",r)}onStatData(r){console.log("onStatData:",r)}}class jc extends Ht{constructor(e){super("AliRtcAudioProcessPlugin",Ue.AliRtcSdkStreamTypeCapture,gi.AUDIO);m(this,"audioProcessor");m(this,"slsReporter");m(this,"enableSoft3ACheck",!1);m(this,"useHardOnly",!1);m(this,"lastDiffOutputLog","");m(this,"audioContext",new AudioContext({sampleRate:48e3}));m(this,"farNode");m(this,"activeAudioContext",()=>{var e;(e=this.audioContext)==null||e.resume(),document.removeEventListener("click",this.activeAudioContext)});m(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=X(X({},this.options),e))}isSupported(){return Pn.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return I(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){this.audioProcessor=new Pn({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(s,n)=>{let c=3e3;n.includes("far")?c=5e3:n.includes("output")?c=1e4:n.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var s,n;this.enableSoft3ACheck||e.updateAudioTrack((s=this.audioProcessor)==null?void 0:s.targetMediaTrack),this.options.dumpAudioData&&((n=this.audioProcessor)==null||n.startDump())}),this.audioProcessor.on("loaderror",s=>{this.emit("error",s)}),this.audioProcessor.on("outputlog",s=>{s!=null&&s.includes("diff")&&(this.lastDiffOutputLog=s||"")}),this.audioProcessor.on("statdata",s=>{var n;if(s)try{let c=s;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),l=JSON.parse(s);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(c){}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,s;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(s=this.farNode)==null||s.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var ki=(a=>(a[a.Default=0]="Default",a[a.Human=1]="Human",a[a.Robot=2]="Robot",a))(ki||{}),$c=Object.defineProperty,Wc=Object.getOwnPropertyDescriptor,Dn=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Wc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&$c(r,e,s),s};const Ks=(Yt=class extends oe{constructor(e,t){super();m(this,"self");m(this,"remoteUser");m(this,"sendReadyMsg",!1);m(this,"hasPubDataChannel",!1);m(this,"hasSubDataChannel",!1);m(this,"readyMsgSuccess",!1);m(this,"sendReadyMsgTimer");m(this,"startReadyMsgTime");m(this,"robotUserId");m(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg()))});m(this,"onCheckReadyMsg",(e,t)=>{var i,s;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const n=new TextDecoder().decode(t.data),c=JSON.parse(n);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(T.event(`[${Yt.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(s=this.remoteUser)==null||s.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(n){}});m(this,"onDataPublishStateChange",(e,t)=>{t===ee.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){T.event(`[${Yt.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return I(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new zt(new TextEncoder().encode(t).buffer))}catch(n){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const s=Date.now()-this.startReadyMsgTime;i=s<1e3?50:s<2e3?100:s<3e3?500:2e3,e>30?T.event(`[${Yt.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},m(Yt,"logName","DataChannelReadyHelper"),Yt);Dn([k()],Ks.prototype,"destroy",1),Dn([k()],Ks.prototype,"sendReadyMsgLoop",1);let zc=Ks;class Kc{constructor(r){m(this,"_useSysEchoCancellation",!0);m(this,"_useSysNoiseSuppression",!0);m(this,"_useSysAutoGainControl",!0);m(this,"_useAIAEC",!1);m(this,"_enableSoft3A",!1);m(this,"_enableSoft3ACheck",!1);m(this,"_useHardOnly",!1);m(this,"_dumpAudioData",!1);m(this,"_useAudio3AConfigFromServer",!0);r&&Object.assign(this,r)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(r){this._useSysEchoCancellation=r}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(r){this._useSysNoiseSuppression=r}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(r){this._useSysAutoGainControl=r}get useAIAEC(){return this._useAIAEC}set useAIAEC(r){this._useAIAEC=r}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(r){this._enableSoft3A=r}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(r){this._enableSoft3ACheck=r}get useHardOnly(){return this._useHardOnly}set useHardOnly(r){this._useHardOnly=r}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(r){this._dumpAudioData=r}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(r){this._useAudio3AConfigFromServer=r}loadFromLocalConfig(r){var e,t,i,s,n,c,o,l,d;this.useAudio3AConfigFromServer=(e=r.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=r.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=r.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(s=r.useSysAutoGainControl)!=null?s:this.useSysAutoGainControl,this.useAIAEC=(n=r.useAIAEC)!=null?n:this.useAIAEC,this.enableSoft3A=(c=r.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=r.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(l=r.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=r.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(r){if(r&&typeof r=="object"){const e=ei(r,"enableSoft3A"),t=pi(r,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(r.archCfgs){const i=ei(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const s=ei(r,"useAIAEC");s!==void 0&&(this.useAIAEC=s);const n=ei(r,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=ei(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=ei(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(r.config){const i=pi(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const s=pi(r,"useAIAEC");s!==void 0&&(this.useAIAEC=s);const n=pi(r,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=pi(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=pi(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}T.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var Jc=Object.defineProperty,Gc=Object.getOwnPropertyDescriptor,ot=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Gc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Jc(r,e,s),s};class Qe extends oe{constructor(e){super();m(this,"_loggerInstanceId","");m(this,"self");m(this,"userMap",{});m(this,"usersViewMap",{});m(this,"rtsManager");m(this,"localStreamManager");m(this,"authInfo");m(this,"signalingManager");m(this,"pluginManager");m(this,"audioMixerPlugin");m(this,"dualVideoPlugin");m(this,"blankAudioPlugin");m(this,"audioProcessorPlugin");m(this,"slsReporter");m(this,"statsMonitorId");m(this,"autoSubAudio",!0);m(this,"autoSubVideo",!0);m(this,"autoSubScreen",!0);m(this,"wantSubAudio",!0);m(this,"wantSubVideo",!0);m(this,"wantSubScreen",!0);m(this,"defaultStreamType",Je.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"refreshUrlTimer");m(this,"audioVolumeIndicationInterval",0);m(this,"indicationTimer",0);m(this,"parameter",{});m(this,"audio3AConfig",new Kc);m(this,"dcReadyHelper");m(this,"networkQualityTimer");const{signalingManager:t,slsReporter:i,parameter:s}=e;this._loggerInstanceId=e.instanceId||"",this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,s&&(this.parameter=s),this.pluginManager=new Ec,this.localStreamManager=new xc(this.pluginManager,this.slsReporter),this.rtsManager=new Mc(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new yc({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new Bc,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new Hc("dualVideoPlugin"),new K.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new Vc)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(s=>{var n;if(s.msid===M.Audio&&s.userdata)try{const c=JSON.parse(s.userdata);c.agent_instance&&((n=this.slsReporter)==null||n.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(Ye.RECV_NOTIFY_PUBLISH,"","",""),this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(De.removeQueryString(this.self.url)===De.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(s=>De.removeQueryString(s.streamUrl)===De.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(n=>{n.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const s=this.remoteUsers.find(n=>De.removeQueryString(n.streamUrl)===De.removeQueryString(t||""));s==null||s.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(n=>{n.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const s=this.remoteUsers.find(n=>De.removeQueryString(n.streamUrl)===De.removeQueryString(t||""));s==null||s.markReconnected(i)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(ge.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(ge.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(ge.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){if(!e)return this.publisher.setViewConfig(null,t);const i=ns(e);i.length!==0&&i.forEach(s=>{this.publisher.resetElement(s),Object.values(this.usersViewMap).forEach(({cameraViews:n=[],screenViews:c=[]})=>{n.includes(s)&&n.splice(n.indexOf(s),1),c.includes(s)&&c.splice(c.indexOf(s),1)}),this.publisher.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var n,c;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,i);const s=ns(t);s.length!==0&&(s.forEach(o=>{this.publisher.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:l=[],screenViews:d=[]})=>{l.includes(o)&&l.splice(l.indexOf(o),1),d.includes(o)&&d.splice(d.indexOf(o),1)})}),(c=this.userMap[e])==null||c.setViewConfig(s,i))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:s,isScreenSubscribing:n}=t;return i||s||n})}onRemotePublishStateChange(e,t=!0){var u;const{userid:i,callid:s,subscribe:n,pubid:c="",tracks:o}=e,l=(u=n==null?void 0:n.pullstreamurl)!=null?u:"";let d=this.getRemoteUser(i);if(!d)return;const h=d.streamInfo.audioTrackInfo,p=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(s,l,c,o),h===d.streamInfo.audioTrackInfo&&p===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(ge.Publish)}setTimeoutToUpdateAllStreamUrls(e){var s;if(!e)return;let t=354e4;const i=(s=function(n){var c,o;try{const l=new URL(n),[d,h]=l.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(h),u=p==null?void 0:p[1],f=p==null?void 0:p[2],g=new URLSearchParams(l.search);return{appId:d,channelId:u,sessionId:f,timeoutTs:1e3*parseInt((o=(c=g.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){return null}}(e))==null?void 0:s.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>I(this,null,function*(){var c;const n=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});n.pushstreamurl&&(this.self.url=n.pushstreamurl),(c=n.users)==null||c.forEach(o=>{var d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(n.pushstreamurl)}),t)}init(e,t,i){var s;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((s=t==null?void 0:t.config)==null?void 0:s.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===ki.Human&&(this.dcReadyHelper=new zc(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destroy(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(n=>{this.addUser(n,ge.InRoom)}),this.startStatsMonitor(),this.networkQualityTimer=window.setInterval(()=>I(this,null,function*(){if(this.remoteUsers.length===0)return void this.emit("networkQuality",{subscribe:{rtt:0,loss:0,quality:Ze.AliRtcNetworkUnknown}});const n=yield this.rtsManager.getSubscribeNetworkQuality();this.emit("networkQuality",{subscribe:n})}),2e3)}leave(){return I(this,null,function*(){var e;this.stopIndication();try{this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:t=[],screenViews:i=[]})=>{t.forEach(s=>{s.srcObject=null,s._playPromise=void 0}),i.forEach(s=>{s.srcObject=null,s._playPromise=void 0})}),this.usersViewMap={};for(let t in this.userMap)this.userMap[t]&&(this.userMap[t].clear(),delete this.userMap[t]);this.self.leave(),(e=this.dcReadyHelper)==null||e.destroy(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0,window.clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0}finally{this.stopStatsMonitor(),this.stopIndication()}})}clear(){return I(this,null,function*(){yield this.leave(),this.stopIndication(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>I(this,null,function*(){if(this.publisher){const{audio:i,video:s,candidate:n}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),s&&s.length>0&&this.emit("rtcLocalVideoStats",s),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:s,video:n}=yield i.getStats();s&&s.forEach(c=>{e.push(c)}),n&&n.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&(clearInterval(this.statsMonitorId),this.statsMonitorId=void 0)}addUser(e,t){const i=e.userid;let s=this.userMap[i];return s||(s=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=s,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==ge.InRoom),s}executeAddUser(e,t,i){const s=new Ic({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return s.on(at.Remote,this.onRemoteDeviceStatusChange.bind(this)),s.on(Pe.PullStreamStats,this.onRemoteStatReport.bind(this)),s.on(Pe.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),s.on("audioSubscribeStateChanged",(n,c,o,l)=>{this.emit("audioSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("videoSubscribeStateChanged",(n,c,o,l)=>{this.emit("videoSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("screenSubscribeStateChanged",(n,c,o,l)=>{this.emit("screenSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("dataSubscribeStateChanged",(n,c,o,l)=>{var d;o===ce.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),s.on("remoteVideoAutoPlayFail",(n,c)=>{this.emit("remoteVideoAutoPlayFail",n,c)}),s.on("remoteAudioPlayError",(n,c)=>{this.emit("remoteAudioPlayError",n,c)}),s.on("remoteVideoPlayError",(n,c)=>{this.emit("remoteVideoPlayError",n,c)}),s.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n,s.userId)}),s.on("occurError",n=>{this.emit("occurError",n,s.userId)}),s.on("remoteDataChannelMessage",(n,c)=>{this.emit("remoteDataChannelMessage",n,c)}),s.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),s.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),s.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),s.setRemoteDefaultVideoStreamType(this.defaultStreamType),s.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&s.updateSubscribe(i),s}onRemoteDeviceStatusChange(e,t){e===Pe.MuteAudio?this.emit("userAudioMuted",t,!0):e===Pe.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Pe.MuteVideo?this.emit("userVideoMuted",t,!0):e===Pe.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Pe.MuteScreen?this.emit("userScreenMuted",t,!0):e===Pe.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Pe.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Pe.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return I(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(n=>{n.userid&&(this.userMap[n.userid]?i.push(n):t.push(n))});const s=Object.keys(this.userMap).filter(n=>!e.find(c=>c.userid===n)).map(n=>({userid:n,reason:"",leavecode:rs.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:s,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&(window.clearInterval(this.indicationTimer),this.indicationTimer=0)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=X(X({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,s,n,c,o;const t=JSON.parse(e);Object.keys(t).forEach(l=>{const d=this.parameter[l],h=t[l];this.parameter[l]=typeof d=="object"&&typeof h=="object"?X(X({},d),h):h}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new Oc),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((s=this.blankAudioPlugin)==null?void 0:s.name),(n=this.blankAudioPlugin)==null||n.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio)),t.subscribe&&((o=this.rtsManager)==null||o.updateSubscribeBatcher(t.subscribe))}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new jc({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}m(Qe,"logName","BizControl"),ot([k()],Qe.prototype,"init",1),ot([k()],Qe.prototype,"leave",1),ot([k()],Qe.prototype,"clear",1),ot([k(H)],Qe.prototype,"addUser",1),ot([k()],Qe.prototype,"removeLeftUser",1),ot([k()],Qe.prototype,"diffUsers",1),ot([k(H)],Qe.prototype,"updateAudioWant",1),ot([k(H)],Qe.prototype,"updateVideoWant",1),ot([k(H)],Qe.prototype,"updateScreenWant",1),ot([k()],Qe.prototype,"stopIndication",1),ot([k()],Qe.prototype,"startIndication",1),ot([k(H)],Qe.prototype,"setEnableDualVideoStream",1),ot([k(H)],Qe.prototype,"setAudioVolume",1),ot([k()],Qe.prototype,"enableAudioVolumeIndication",1);var Pi=(a=>(a[a.LiveTranscodingSingle=0]="LiveTranscodingSingle",a[a.LiveTranscodingMix=1]="LiveTranscodingMix",a))(Pi||{}),Js=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingAudio=1]="LiveTranscodingAudio",a[a.LiveTranscodingVideo=2]="LiveTranscodingVideo",a))(Js||{}),bi=(a=>(a[a.LiveTranscodingCamera=0]="LiveTranscodingCamera",a[a.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",a))(bi||{});const Di={0:"camera",1:"shareScreen"};var Gs=(a=>(a[a.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",a[a.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",a[a.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",a[a.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",a[a.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",a[a.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",a[a.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",a[a.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",a[a.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",a[a.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",a[a.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",a[a.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",a[a.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",a[a.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",a[a.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",a[a.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",a[a.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",a[a.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",a[a.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",a))(Gs||{});const qc={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var qi=(a=>(a[a.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",a[a.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",a[a.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",a[a.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",a[a.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",a))(qi||{}),Mi=(a=>(a[a.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",a[a.LiveTranscodingBody=1]="LiveTranscodingBody",a))(Mi||{}),Li=(a=>(a[a.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",a[a.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",a[a.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",a[a.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",a[a.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",a[a.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",a))(Li||{}),qs=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingCrop=1]="LiveTranscodingCrop",a[a.LiveTranscodingFill=2]="LiveTranscodingFill",a))(qs||{}),Xi=(a=>(a[a.LiveTranscodingNormal=0]="LiveTranscodingNormal",a[a.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",a))(Xi||{}),Xs=(a=>(a[a.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",a[a.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",a[a.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",a[a.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",a[a.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",a[a.LiveTranscodingState_END=5]="LiveTranscodingState_END",a))(Xs||{}),Lt=(a=>(a[a.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",a[a.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",a[a.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",a[a.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",a[a.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",a[a.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",a[a.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",a[a.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",a[a.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",a))(Lt||{}),Ys=(a=>(a[a.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",a[a.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",a[a.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",a))(Ys||{}),ct=(a=>(a[a.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",a[a.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",a[a.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",a[a.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",a[a.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",a[a.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",a[a.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",a))(ct||{});const Xc={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class Qs{constructor(r,e,t,i,s,n,c,o){m(this,"videoWidth");m(this,"videoHeight");m(this,"videoFramerate",20);m(this,"videoBitrate",2e3);m(this,"videoGop",30);m(this,"audioSamplerate",qi.LiveTranscoding_HZ_44100);m(this,"audioBitrate",500);m(this,"audioChannels",1);this.videoWidth=r,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),s&&(this.videoGop=s),n&&(this.audioSamplerate=n),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const Zs=a=>((16711680&a)>>16)+(65280&a)+((255&a)<<16),Rt=(a=0,r)=>{if(r==0)return 0;let e=a/r;return e<0&&(e=0),e>1&&(e=1),e};class Yi{constructor(r,e,t){m(this,"mixMode",Pi.LiveTranscodingSingle);m(this,"singleParam");m(this,"mixParam");r&&(this.mixMode=r),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(r,e,t,i,s){const n={appid:e.appId,channelid:e.channelId};if(r===ct.MPU_TASK_TRANSACTION_POLLING||r===ct.MPU_TASK_TRANSACTION_LIST||r===ct.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return r===ct.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=s),n;if(n.taskid=t,r!==ct.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===Pi.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===bi.LiveTranscodingShareScreen?n.sourcetype=Di[c.sourceType]:n.sourcetype=Di[bi.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(r===ct.MPU_TASK_TRANSACTION_START||r===ct.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=qc[c.taskProfile]);const o=c.encodeParam||new Qs(1280,720);let l=o.videoWidth,d=o.videoHeight;const h={};Object.keys(o).forEach(u=>{const f=o[u];f>0&&(h[u.toLowerCase()]=f)}),h.lowbitratehighquality=0,n.encodeparam=h,n.backgrounds=c.backgrounds.map(u=>u.toJson(l,d)),n.watermarks=c.watermarks.map(u=>u.toJson(l,d)),n.clockwidgets=c.clockWidgets.map(u=>u.toJson(l,d));const p=c.users.map(u=>u.userId);n.subspecusers=[...new Set(p)],n.layouts=[{audiomixcount:c.users.length,panes:c.users.map((u,f)=>u.toJson(f,l,d,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=Zs(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const er=a=>I(this,null,function*(){const r=new Uint8Array(160).fill(170),e=new TextEncoder().encode(a),t=yield window.crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(s=>s.toString(16).padStart(2,"0")).join("")});class Yc{constructor(r){m(this,"authInfo");m(this,"slsReporter");this.slsReporter=r}doRequest(r,e){var c;const t=this.authInfo;if(!t)return Promise.reject(Lt.LiveTranscodingErrorInvalidParam);const i=Xc[r],s={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:De.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:De.createCallid()},n=Object.keys(s).map(o=>`${o}=${encodeURIComponent(s[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${n}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new O(B.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new O(B.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(r){this.authInfo=r}clear(){this.authInfo=void 0}startPublishLiveStream(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Lt.LiveTranscodingErrorInvalidParam);const t=yield er(r.split("?")[0]),i=ct.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,s)})}startPublishLiveStreamWithTaskId(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Lt.LiveTranscodingErrorInvalidParam);const t=ct.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}updatePublishLiveStream(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Lt.LiveTranscodingErrorInvalidParam);const t=yield er(r.split("?")[0]),i=ct.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,s)})}updatePublishLiveStreamWithTaskId(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Lt.LiveTranscodingErrorInvalidParam);const t=ct.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}stopPublishLiveStream(r){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Lt.LiveTranscodingErrorInvalidParam);const e=yield er(r.split("?")[0]),t=ct.MPU_TASK_TRANSACTION_STOP,i=new Yi().toJson(t,this.authInfo,e,r);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(r){if(!this.authInfo)return Promise.reject(Lt.LiveTranscodingErrorInvalidParam);const e=ct.MPU_TASK_TRANSACTION_STOP,t=new Yi().toJson(e,this.authInfo,r);return this.doRequest(e,t)}refreshAuthInfo(r){this.authInfo&&this.setAuthInfo(X(X({},this.authInfo),r))}}function Mn(a,r){const e=new window.XMLHttpRequest;e.open("POST",`${a}?APIVersion=0.6.0`,!0),e.send(r)}function Qc(a,r){try{if(r.length>=32768)return void Mn(a,r);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(a,r)||Mn(a,r)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
133
+ `+e),console.error("Failed log data:",a))}}function Zc(a,r,e){return t=this,i=null,s=function*(){try{a=a.slice(0,-6);const{data:n,header:c}=yield e.process(a,r),o=new window.XMLHttpRequest;o.open("POST",a,!0);for(let l in c)o.setRequestHeader(l,c[l]);o.send(n)}catch(n){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
134
+ `+n),console.error("Failed log data:",a))}},new Promise((n,c)=>{var o=h=>{try{d(s.next(h))}catch(p){c(p)}},l=h=>{try{d(s.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((s=s.apply(t,i)).next())});var t,i,s}class Ln extends Ia{constructor(r){super(Object.assign({},r,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>{Qc(e,t)}}))}useStsPlugin(r){this.getOpt().sendPayload=(e,t)=>{Zc(e,t,r)},this.overwriteTransString(r)}}fr(window,"SLS_Tracker",Ln);const lt=class lt{constructor(){m(this,"ntpClock");this.ntpClock=new K.AliRTS.Clock}static getInstance(r="DEFAULT"){let e=lt.instances.get(r);e||(e=new lt,lt.instances.set(r,e),lt.refCounts.set(r,0));const t=lt.refCounts.get(r)||0;return lt.refCounts.set(r,t+1),e}static releaseInstance(r="DEFAULT"){const e=lt.refCounts.get(r)||0;if(e<=0)return;const t=e-1;t===0?(lt.instances.delete(r),lt.refCounts.delete(r)):lt.refCounts.set(r,t)}now(){return this.ntpClock.now()}};m(lt,"instances",new Map),m(lt,"refCounts",new Map);let Ni=lt;const Nn=(a="DEFAULT")=>Ni.getInstance(a),{BrowserUtil:tr,SystenUtil:xn}=K.AliRTS,Qi=6e5,el={host:"cn-shanghai.log.aliyuncs.com",project:"apsara-video-client",logstore:"client"},tl={host:"ap-southeast-1.log.aliyuncs.com",project:"apsara-video-client-sgp",logstore:"client"},Se=class Se{constructor(r){m(this,"param");m(this,"msgCacheArr",[]);m(this,"index",0);m(this,"ntpClock");m(this,"globalEnv","DEFAULT");m(this,"envKey");m(this,"stopped",!1);this.ntpClock=Nn(r),r&&(this.globalEnv=r),this.envKey=this.globalEnv;const e=Se.instanceCount.get(this.envKey)||0;Se.instanceCount.set(this.envKey,e+1),e===0&&this.startSTSUpdateTask()}get stsData(){return Se.sharedStsData.get(this.envKey)}set stsData(r){r?Se.sharedStsData.set(this.envKey,r):Se.sharedStsData.delete(this.envKey)}get stsExpiration(){return Se.sharedStsExpiration.get(this.envKey)||Date.now()}set stsExpiration(r){Se.sharedStsExpiration.set(this.envKey,r)}createTracker(){if(Se.sharedTrackers.has(this.envKey)){const s=Se.sharedTrackers.get(this.envKey);return this.msgCacheArr.forEach((n,c)=>{var o;s==null||s.send(X(ft(X({},this.param),{stat_log_id:`${((o=this.param)==null?void 0:o.sesid)||"nosession"}-${c}`}),n))}),this.index=this.index+this.msgCacheArr.length,void(this.msgCacheArr=[])}if(!this.stsData||!this.param)return;const r=this.globalEnv==="SEA"?tl:el,e=new Ln({host:r.host,project:r.project,logstore:r.logstore}),t={accessKeyId:this.stsData.AccessKeyId,accessKeySecret:this.stsData.AccessKeySecret,securityToken:this.stsData.SecurityToken,refreshSTSTokenInterval:Qi,refreshSTSToken:()=>{this.refreshSTSToken().then(s=>{t.accessKeyId=s.AccessKeyId,t.accessKeySecret=s.AccessKeySecret,t.securityToken=s.SecurityToken}).catch(()=>{})}},i=ps(t);e.useStsPlugin(i),Se.sharedTrackers.set(this.envKey,e),this.msgCacheArr.forEach((s,n)=>{var c;e==null||e.send(X(ft(X({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${n}`}),s))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}startSTSUpdateTask(){return I(this,null,function*(){const r=Se.sharedUpdateTimers.get(this.envKey);r&&clearTimeout(r);try{this.stsData=yield this.refreshSTSToken(),this.createTracker()}catch(t){}const e=setTimeout(()=>{this.startSTSUpdateTask()},Qi);Se.sharedUpdateTimers.set(this.envKey,e)})}refreshSTSToken(){return I(this,null,function*(){const r=Se.sharedStsData.get(this.envKey),e=Se.sharedStsExpiration.get(this.envKey)||0;if(!r||e<=Date.now()+Qi){const t=yield this.requestSTSToken(),i=new Date(t==null?void 0:t.Expiration).getTime()||0,s=Date.now()+Qi;return this.stsExpiration=Math.max(i,s),this.stsData=t,t}return r})}requestSTSToken(){const r=Date.now(),e=`${Se.sharedClientId}|woMMssV6jmyol9fr|${r}`,t={Action:"AssumeSlsRoleV2",AuthInfo:si.MD5(e).toString(si.enc.Hex),ClientId:Se.sharedClientId,BusinessType:"rtc",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${r}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Fi(r,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),s=`https://${this.globalEnv==="SEA"?"vod.ap-southeast-1.aliyuncs.com":"vod.cn-shanghai.aliyuncs.com"}/?${i}`;return fetch(s).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}start(r){this.initParam(r),this.createTracker(),this.startSTSUpdateTask()}stop(){if(this.stopped)return;this.stopped=!0,this.param=void 0,this.msgCacheArr=[],this.index=0;const r=Se.instanceCount.get(this.envKey)||0,e=Math.max(0,r-1);if(Se.instanceCount.set(this.envKey,e),e===0){const t=Se.sharedUpdateTimers.get(this.envKey);t&&(clearTimeout(t),Se.sharedUpdateTimers.delete(this.envKey)),Se.sharedTrackers.delete(this.envKey),Se.sharedStsData.delete(this.envKey),Se.sharedStsExpiration.delete(this.envKey),Se.instanceCount.delete(this.envKey)}Ni.releaseInstance(this.envKey)}sendReport(r){var i;let e;r.tm=Date.now();try{e=JSON.parse(JSON.stringify(X(ft(X({bt:tr.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((i=this.param)==null?void 0:i.sesid)||"nosession"}-${this.index}`}),r)))}catch(s){}if(!e)return;const t=Se.sharedTrackers.get(this.envKey);t?(t.send(e),this.index++):this.msgCacheArr.push(e)}initParam(r){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=ut(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:r.appId,usrid:r.userId,statsvrs:"0.6.1",evetid:0,sesid:r.sessionId,sessionId:r.sessionId,channelid:r.channelId,usrn:r.userId,osn:xn.systemName,osv:xn.systemVersion,deb:Yo(),den:Go(),udid:e,sdkvrs:Ai,acs:"Unknown",cput:_a(),dm:`${window.location.protocol}//${window.location.host}`,bt:tr.browserName,bv:tr.browserVersion,envir:"PRODUCT",args:"",instid:ut()})}};m(Se,"sharedTrackers",new Map),m(Se,"sharedStsData",new Map),m(Se,"sharedStsExpiration",new Map),m(Se,"sharedUpdateTimers",new Map),m(Se,"sharedClientId",ut()),m(Se,"instanceCount",new Map);let ir=Se;const Ie=(a,r=1,e=6e4,t=0)=>{let i=a;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*r)))},At=(a,r,e=2e7,t=0)=>{let i=r;(!r||r<0||r>1e4)&&(i=1e3);let s=a;return s||(s=0),Math.min(e,Math.max(t,Math.round(s/(i/1e3))))},ni=(a,r)=>{if(r===0||!r)return"0.00";let e=a;return(!e||e<0)&&(e=0),(e/r*100).toFixed(2)},Vn=a=>a>=0&&a<=1?Ie(Math.floor(32767*a),1,32767):0,ke=(a,r)=>{var t,i,s;let e=((t=a._last)==null?void 0:t[r])||0;return a.ssrc&&((i=a._last)!=null&&i.ssrc)&&a.ssrc!==((s=a._last)==null?void 0:s.ssrc)&&(e=0),((a==null?void 0:a[r])||0)-e},On=(a,r)=>Ie(ke(a,r),1e3,1e4),oi=(a,r=2e7)=>Ie(a,1,r);class il{constructor(r,e){m(this,"engine");m(this,"logClient");m(this,"authInfo");m(this,"ntpClock");m(this,"globalEnv");m(this,"customFields",{});this.globalEnv=e||"DEFAULT",this.logClient=new ir(e),this.engine=r,this.ntpClock=Nn(this.globalEnv)}setCustomFields(r){this.customFields=X(X({},this.customFields),r)}getCustomField(r){return this.customFields[r]}start(r){this.authInfo=r,this.logClient.start(r)}stop(){this.logClient.stop(),Ni.releaseInstance(this.globalEnv)}reportPublishAudio3A(r,e,t,i){const s={};let n=JSON.parse(i);s.publevel=n.capture_audio_cur_level_db||0,s.eleakrate=n.echo_leak_rate||0,s.playbw=n.render_bandwidth||-1,s.capbw=n.capture_bandwidth||-1,s.diff=n.diff||0,s.leak=n.leak||0,this.log({evetid:10070,traceid:t,calid:r,rmtid:"",args:this.data2String(X({calid:r,tckid:e||"audio3a",rmtid:"",traceid:t},s))})}reportPublishMonitor(r,e,t,i,s){if(!t||s.length<=0)return;const n=t===M.Audio,c={ctm:Math.floor(s[0].timestamp||0),src:s[0].ssrc||"",codec:s[0]._codec||""},o=[],l=[],d=[],h=[],p=[],u=[],f=[],g=[],S=[],b=[],v=[],R=[],_=[],y=[],A=[],w=[],E=[],C=[],P=[];try{if(s.forEach(D=>{var V,ue,Le,J,ve,xe;if(!D||!D.timestamp)return;const U=(V=D._last)!=null&&V.timestamp?D.timestamp-D._last.timestamp:1e3,G=ke(D,"bytesSent"),Y=ke(D,"headerBytesSent"),q=At(Ie(G+Y,8,2e7),U);o.push(q);const W=At(Ie(G,8,2e7),U);l.push(W);const Z=At(Ie(Y,8,2e7),U);d.push(Z);const te=ke(D,"packetsSent"),be=At(te,U);h.push(be);const L=ke(D,"packetsLost"),x=At(L,U);p.push(x);const N=ni(L,te);if(u.push(N),n)(ue=D._source)!=null&&ue.audioLevel&&f.push(Vn(D._source.audioLevel)),g.push(0);else{S.push(On(D,"totalEncodeTime")),b.push(oi((Le=D._source)==null?void 0:Le.framesPerSecond,100)),v.push(oi((J=D._source)==null?void 0:J.framesPerSecond,100)),R.push(oi(D.framesPerSecond,100)),_.push(oi((ve=D._source)==null?void 0:ve.height,4400)),y.push(oi((xe=D._source)==null?void 0:xe.width,7700)),A.push(oi(D.frameHeight,4400)),w.push(oi(D.frameWidth,7700));const Ee=ke(D,"totalPacketSendDelay");E.push(Ie(Ee,1/(L||1),2e3));const Me=ke(D,"qpSum");C.push(Ie(Me,1/(D.framesPerSecond||1),51)),P.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=h.join(","),c.pl=p.join(","),c.plr=u.join(","),n){const D=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=g.join(","),c.arsr=D,c.aesr=D,c.publevel=-90,c.rawlevel=-90}else c.em=S.join(","),c.cfps=b.join(","),c.ifps=v.join(","),c.sfps=R.join(","),c.ih=_.join(","),c.iw=y.join(","),c.sh=A.join(","),c.sw=w.join(","),c.sd=E.join(","),c.aqp=C.join(","),c.caf=P.join(","),c.can=P.join(","),c.cav=l.join(","),c.ifimax=P.join(","),c.ifimin=P.join(","),c.efimax=P.join(","),c.efimin=P.join(","),c.sfimax=P.join(","),c.sfimin=P.join(","),c.apsnr=P.join(",")}catch(D){}this.log({evetid:10070,traceid:e,calid:r,rmtid:"",args:this.data2String(X({calid:r,tckid:t,rmtid:"",traceid:e},c))})}reportSubscribeMonitor(r,e,t,i,s){if(!i||!s||s.length<=0)return;const n=i===M.Audio,c={ctm:Math.floor(s[0].timestamp||0),src:s[0].ssrc||"",codec:s[0]._codec||""},o=[],l=[],d=[],h=[],p=[],u=[],f=[],g=[],S=[],b=[],v=[],R=[],_=[],y=[],A=[],w=[],E=[],C=[],P=[],D=[],U=[],G=[],Y=[],q=[],W=[],Z=[],te=[],be=[],L=[],x=[],N=[],V=[],ue=[],Le=[];try{s.forEach(J=>{var me,Ke;if(!J||!J.timestamp)return;const ve=(me=J._last)!=null&&me.timestamp?J.timestamp-J._last.timestamp:1e3,xe=ke(J,"bytesReceived"),Ee=ke(J,"headerBytesReceived"),Me=At(Ie(xe+Ee,8,2e7),ve);o.push(Me);const ye=At(Ie(xe,8,2e7),ve);l.push(ye);const Te=At(Ie(Ee,8,2e7),ve);d.push(Te);const pe=ke(J,"packetsReceived"),Ne=At(pe,ve);h.push(Ne);const we=ke(J,"packetsLost"),Xe=At(we,ve);p.push(Xe);const dt=ni(we,pe);u.push(dt);const le=ke(J,"jitterBufferDelay"),ne=ke(J,"jitterBufferEmittedCount");if(J.jitterBufferDelay&&J.jitterBufferEmittedCount){const Q=Ie(le,1e3/ne,1e4);f.push(Q)}else f.push(0);const ie=ke(J,"fecPacketsReceived");R.push(ni(ie,pe));const Re=ke(J,"retransmittedPacketsReceived"),Be=pe+we-Re;if(S.push(ni(pe-Re,Be)),b.push(ni(we,Be)),g.push(ni(Re,Be)),v.push(Be),ue.push(0),Le.push(""),n){y.push(Vn(J.audioLevel));const Q=((Oe,It)=>{var Nt,Et,Qt;return(((Nt=Oe==null?void 0:Oe._source)==null?void 0:Nt[It])||0)-(((Qt=(Et=Oe==null?void 0:Oe._last)==null?void 0:Et._source)==null?void 0:Qt[It])||0)})(J,"synthesizedSamplesEvents");A.push(Q);const Ve=On(J,"synthesizedSamplesDuration");w.push(Ve);const ht=ni(Ve,ve);_.push(ht),E.push(0)}else{const Q=(Ke=J._last)!=null&&Ke.totalInterFrameDelay?J.totalInterFrameDelay-J._last.totalInterFrameDelay:0;C.push(Ie(Q,1e3/(J.framesDecoded||30),500)),P.push(Ie(J.framesPerSecond,1,100)),D.push(ke(J,"framesReceived")),V.push(ke(J,"framesRendered")),U.push(Ie(J.frameHeight,1,4400)),G.push(Ie(J.frameWidth,1,7700));const Ve=ke(J,"totalProcessingDelay");Y.push(Ie(Ve,1e3/(J.framesDecoded||30),12e4));const ht=ke(J,"nackCount");W.push(ht);const Oe=ke(J,"pliCount");q.push(Oe);const It=ke(J,"qpSum");Z.push(Ie(It,1/(J.framesPerSecond||1),51)),te.push(Ie(J.framesDropped));const Nt=ke(J,"totalFreezesDuration");be.push(Ie(Nt,1e3,3e4));const Et=ke(J,"jitterBufferEmittedCount"),Qt=ke(J,"jitterBufferDelay");Qt&&Et?L.push(Ie(Qt,1e3/Et,3e4)):L.push(0);const Vi=ke(J,"jitterBufferTargetDelay");Vi&&Et?x.push(Ie(Vi,1e3/Et,3e4)):x.push(0);const is=ke(J,"jitterBufferMinimumDelay");is&&Et?N.push(Ie(is,1e3/Et,3e4)):N.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=h.join(","),c.pl=p.join(","),c.plr=u.join(","),c.jd=f.join(","),c.fecr=R.join(","),c.retransr=g.join(","),c.baser=S.join(","),c.basel=b.join(","),c.recoverr=ue.join(","),c.alll=b.join(","),c.totalc=v.join(","),n?(c.er=_.join(","),c.aolevel=y.join(","),c.asrc=E.join(","),c.scnt=A.join(","),c.sdura=w.join(",")):(c.dm=C.join(","),c.dfps=P.join(","),c.rfps=D.join(","),c.rh=U.join(","),c.rw=G.join(","),c.fpt=Le.join(","),c.ns=W.join(","),c.pliss=q.join(","),c.aqp=Z.join(","),c.ofimax=ue.join(","),c.ofimin=ue.join(","),c.dfimax=ue.join(","),c.dfimin=ue.join(","),c.rfimax=ue.join(","),c.rfimin=ue.join(","),c.vrstutter=be.join(","),c.cdm=L.join(","),c.tdm=x.join(","),c.pdm=N.join(","),c.ofps=V.join(","),c.dfbd=te.join(","))}catch(J){}this.log({evetid:10080,traceid:t,rmtid:e,calid:r,args:this.data2String(X({calid:r,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(r){if(r.length<=0)return;const e=[],t=[],i=[],s=[],n=[],c=[],o=[],l=[],d=[],h=[];r.forEach((u,f)=>{var S;if(!u.timestamp)return;const g=(S=u._last)!=null&&S.timestamp?u.timestamp-u._last.timestamp:1e3;e.push(Ie(u.currentRoundTripTime,1e3)),t.push(Ie(u.availableOutgoingBitrate,8,2e8)),i.push(At(Ie(u.bytesSent,8,2e7),g,25e6)),s.push(At(Ie(u.bytesReceived,8,2e7),g,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),h.push(""))});const p={ctm:Math.floor(r[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:s.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:h.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(X({asb:t.join(","),abms:n.join(","),vbms:c.join(",")},p))}),this.log({evetid:10081,args:this.data2String(X({},p))})}reportLoopAudioDelay(r,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:s={},AISub:n={},pub:c={},sub:o={},grtn:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const h={};let p=0;for(let g=0;g<10;g++){const S=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${g}`,b=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${g}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${g}`;if(!l.hasOwnProperty(S))break;p+=l[S]||0,p+=l[b]||0,p+=l[v]||0,h[`_gnd${g}`]=`gnd[${g}]: {${this.data2String({gnirh:l[S]||0,gnbp:l[b]||0,gnpc:l[v]||0})}}`}const u={};for(let g=0;g<10;g++){const S=`aigrtninternalrtthalf_${g}`,b=`aigrtnbeforepacer_${g}`,v=`aigrtnpacercost_${g}`;if(!i.hasOwnProperty(S))break;u[`_lgnd${g}`]=`lgnd[${g}]: {${this.data2String({gnirh:i[S]||0,gnbp:i[b]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(ft(X({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(ft(X({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:s.aAIClientScentenceId||0,quct:65535*(s.aAIClientQuestionTimestampHEAD||0)+(s.aAIClientQuestionTimestampTAIL||0),anct:65535*(s.aAIClientAnswerTimestampHEAD||0)+(s.aAIClientAnswerTimestampTAIL||0),casc:s.aAIClientSourceCost||0,camc:s.aAIClientMixerCost||0,caec:s.aAIClientEncoderCost||0,cantc:s.aIClientNetsdkThrCost||0,caqtc:s.aIClientQosThrCost||0,capc:s.aIClientPacerCost||0,cuphr:s.aIClientUpRTTHalf||0},u),{qgac:0,ldhr:l.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:n.aAILinuxReceiveCost||0,lanqc:n.aAILinuxNeteqCost||0,larsc:n.aAILinuxRemoteSourceCost||0,lapmc:n.aAILinuxPlayMixerCost||0,lapc:n.aAILinuxPlayCost||0,lsdnc:n.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:r,tpd:0,scc:s.aAIClientSourceCost||0,mxc:s.aAIClientMixerCost||0,encc:s.aAIClientEncoderCost||0,netc:s.aIClientNetsdkThrCost||0,qostc:s.aIClientQosThrCost||0,pacerc:s.aIClientPacerCost||0,uphr:s.aIClientUpRTTHalf||0},h),{agac:p,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:n.aAILinuxReceiveCost||0,nqc:n.aAILinuxNeteqCost||0,rscc:n.aAILinuxRemoteSourceCost||0,plmxc:n.aAILinuxPlayMixerCost||0,plc:n.aAILinuxPlayCost||0,dvd:0}))})}reportCumuAudioDelay(r,e){const{pub:t={},sub:i={},grtn:s={}}=e||{};let n=0;n=Object.keys(s).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(s.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,h=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!s.hasOwnProperty(d))break;o+=s[d]||0,o+=s[h]||0,o+=s[p]||0,c[`_gnd${l}`]=`gnd[${l}]: {${this.data2String({gnirh:s[d]||0,gnbp:s[h]||0,gnpc:s[p]||0})}}`}this.log({evetid:10074,args:this.data2String(ft(X({ssrc:r,tpd:n,scc:(t==null?void 0:t.aSourceCCost)||0,mxc:(t==null?void 0:t.aMixerCost)||0,encc:(t==null?void 0:t.aEncodeCCost)||0,netc:(t==null?void 0:t.netsdkThrCost)||0,qostc:(t==null?void 0:t.qosThrCost)||0,pacerc:(t==null?void 0:t.pacerCost)||0,uphr:(t==null?void 0:t.upRTTHalf)||0},c),{agac:o,dnhr:(i==null?void 0:i.downRTTHalf)||0,tsd:(i==null?void 0:i.vTotalCost)||0,rcc:0,nqc:0,rscc:0,plmxc:0,plc:0,device_delay:0,psdkt:0,pub_sdk_version:Ai}))})}reportCumuVideoDelay(r,e){const{pub:t={},sub:i={},grtn:s={}}=e||{};let n=0;n=Object.keys(s).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(s.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,h=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!s.hasOwnProperty(d))break;o+=s[d]||0,o+=s[h]||0,o+=s[p]||0,c[`_gnd${l}`]=`vgnd[${l}]: {${this.data2String({vgnirh:s[d]||0,vgnbp:s[h]||0,vgnpc:s[p]||0})}}`}this.log({evetid:10075,args:this.data2String(ft(X({vssrc:r,valld:n,vcdc:(t==null?void 0:t.capDeviceCost)||0,vpec:(t==null?void 0:t.pushExtCost)||0,vcpc:(t==null?void 0:t.capPlugCost)||0,vptc:(t==null?void 0:t.prepThrCost)||0,vppc:(t==null?void 0:t.prepPlugCost)||0,vdptc:(t==null?void 0:t.dispThrCost)||0,vdppc:(t==null?void 0:t.dispPlugCost)||0,vetc:(t==null?void 0:t.vEncThrCost)||0,vepc:(t==null?void 0:t.vEncPlugCost)||0,vntc:(t==null?void 0:t.netsdkThrCost)||0,vqtc:(t==null?void 0:t.qosThrCost)||0,vvpac:(t==null?void 0:t.pacerCost)||0,vuphr:(t==null?void 0:t.upRTTHalf)||0},c),{vagac:o,vdnhr:(i==null?void 0:i.downRTTHalf)||0,vrc:(i==null?void 0:i.vAssemblyCost)||0,vstc:0,vfbc:i.vJitterBufferDelay||0,vdtc:(i==null?void 0:i.vDecPlugCost)||0,vdvpc:(i==null?void 0:i.vDecPlugCost)||0,vrtc:0,vrpc:0}))})}reportJoin(r,e,t=""){var h,p;const{start:i,rs:s=0,re:n=0}=e,c=Date.now()-i,o=n-s;let l=0;s&&(l=s-i);let d=0;n&&(d=n-s),this.log({evetid:10010,args:this.data2String({sesid:((h=this.authInfo)==null?void 0:h.sessionId)||"",joitm:c,rslt:r,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(p=this.authInfo)==null?void 0:p.userId,mgt:"cdn",cttc:l,iptc:d,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(r){this.log({evetid:20002,args:this.data2String(X({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},r))})}reportLeave(r,e,t){this.log({evetid:10020,args:this.data2String({lvetm:r,rslt:e,tid:t})})}reportPublish(r,e,t,i,s,n,c,o,l,d,h,p){this.log({evetid:r?10032:10030,calid:t,tm:p,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:s?1:0,isvss:n?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-h,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(r,e,t,i,s,n,c,o,l){const d=Date.now();this.log({evetid:r?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:d-s,jorm:l===kt.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(r,e,t,i){var s;this.log({evetid:10040,args:this.data2String({calid:r,unpubtm:e,rslt:t,tid:i,sesid:((s=this.authInfo)==null?void 0:s.sessionId)||""})})}reportSubscribe(r,e,t,i,s,n,c,o,l,d,h){this.log({evetid:10050,calid:r,rmtid:e,tm:h,args:this.data2String(X({calid:r,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:s?1:0,isaudio:n?1:0,rslt:c,tid:o,subtm:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}reportSubscribeFirstPacket(r,e,t,i,s){this.log({evetid:r?10054:10051,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},s))})}reportSubscribeFirstFrame(r,e,t,i,s){this.log({evetid:r?10055:10052,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i},s))}),this.log({evetid:r?10058:10057,args:this.data2String(X({calid:e,rmtid:t,tckid:i},s))})}reportUnsubscribe(r,e,t,i,s){this.log({evetid:10060,calid:r,args:this.data2String({calid:r,rmtid:e,unsubtm:t,rslt:i,tid:s})})}reportMute(r,e,t){this.log({evetid:11030,args:this.data2String({calid:r,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(r,e){this.log({evetid:11040,args:this.data2String({or:r||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(r,e,t,i){this.log({evetid:11041,args:this.data2String({or:r||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_camera_large"})})}reportScreenProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_screenshare"})})}reportError(r){this.log({evetid:10091,args:this.data2String({rslt:(r==null?void 0:r.code)||-1})})}reportWarning(r){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:r})})}reportRoomServerEvent(r,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:r?0:1,dr:r?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(r,e){this.log({evetid:10101,args:this.data2String({rslt:r,taskid:e})})}reportBye(r){var e;this.log({evetid:10093,args:this.data2String({rslt:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(r,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})})}reportScreen(r,e){var t,i,s,n;this.log({evetid:90013,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(t=r==null?void 0:r.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(s=r==null?void 0:r.code)!=null?s:-1,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportScreenStop(r){this.log({evetid:90019,args:this.data2String({rslt:r?r.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:r?r.code||-1:0})})}reportSwitchCamera(r){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(r,e){this.log({evetid:10201,args:this.data2String(X({tckid:r},e))})}reportSDKCreated(r){this.log({evetid:70011,createtm:Date.now()-r,tm:r})}reportJoinInvoked(r){this.log({evetid:70012,jnnonce:r.nonce||"",jntoken:r.token||"",jntm:r.timestamp||""})}reportJoinResult(r){this.log({evetid:70013,rslt:r?r.code||-1:0,dnsrslt:0})}reportSTSResult(r,e){this.log({evetid:70014,rslt:r,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(r,e,t,i,s){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:r,sei_len:e,sei_rep:t,sei_delay:i,sei_key:s})})}reportConnectionLatencyEvent(r,e,t,i,s,n,c=!1){const o={ageniid:this.getCustomField("ageniid")},l=X({tm:s||Date.now(),ntptm:n||this.ntpClock.now(),stage:r,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(l)})}log(r){r&&(r.tm=r.tm||new Date().getTime(),T.debug("[ConsoleLogger]","log",r),this.logClient.sendReport(r))}data2String(r){let e="";for(let t in r)e.length&&(e+="&"),e+=t.startsWith("_")?r[t]:`${t}=${r[t]}`;return e}}const vi=class vi extends oe{constructor(e){super();m(this,"ws");m(this,"socketStatus",0);m(this,"wsUrl","");m(this,"lastConnectStartTime",0);m(this,"connectRetryMinTimeGap",5e3);m(this,"shouldReconnect",!0);m(this,"connectRetryCount",0);m(this,"gotErr",!1);m(this,"closedByInvoke",!0);m(this,"isReconnecting",!1);m(this,"networkAvailableChecked",!0);m(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.uninitWebsocket()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){T.info(`[${vi.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&De.isNetworkAvailable().then(t=>{t&&console.error(vi.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(T.info(`[${vi.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield De.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};m(vi,"logName","Socket");let sr=vi;const gt=class gt extends oe{constructor(e,t,i,s,n,c){super();m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"wsClient");m(this,"packageCreator");m(this,"keepAliveTimer",0);m(this,"lastKeepAliveResponseTime",0);m(this,"maxConnectRetryDuration",90);m(this,"packageCache",new Map);m(this,"isFirstConnect",!0);m(this,"aliveChecker",0);m(this,"reconnectData");m(this,"joinChannelExtraData");m(this,"onOpen",()=>{if(T.info(`[${gt.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Vt.AliRtcSdkInteractiveLive&&this.channelProfile!==Vt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.createReconnectPackage(this.reconnectData);this.sendPackage(e)}});m(this,"onMessage",e=>{try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==Fe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){T.warn(`[${gt.logName}] onMessage err`,t,e)}});m(this,"onError",e=>{T.warn(`[${gt.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()});m(this,"onConnectFail",()=>{T.warn(`[${gt.logName}] onConnectFail`);const e=new O(B.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)});m(this,"onAuthInvalid",()=>{T.warn(`[${gt.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")});m(this,"onNetworkError",()=>{T.warn(`[${gt.logName}] onNetworkError`);const e=new O(B.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)});m(this,"onClose",e=>{T.info(`[${gt.logName}] onClose`,e),this.stopKeepAlive()});m(this,"onWillReconnect",()=>{this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)});m(this,"onReconnectStart",()=>{this.emit("onReconnectStart")});m(this,"onReconnectFail",()=>{this.emit("onReconnectFail",new O(B.ERR_INNER,"signaling reconnect failed."))});this.authInfo=e,this.userName=t,this.packageCreator=new Wi(e,t),this.channelProfile=i,this.clientRole=s,this.slsReporter=n,c&&(this.maxConnectRetryDuration=c),this.wsClient=new sr,this.wsClient.on("onOpen",this.onOpen),this.wsClient.on("onMessage",this.onMessage),this.wsClient.on("onError",this.onError),this.wsClient.on("onClose",this.onClose),this.wsClient.on("onConnectFail",this.onConnectFail),this.wsClient.on("onAuthInvalid",this.onAuthInvalid),this.wsClient.on("onNetworkError",this.onNetworkError),this.wsClient.on("onWillReconnect",this.onWillReconnect),this.wsClient.on("onReconnectStart",this.onReconnectStart),this.wsClient.on("onReconnectFail",this.onReconnectFail)}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=jt(l,["l1ip"]);let s=this.packageCreator.createPublishPackage();s.data.users=[],s.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.2.8-beta.3";o&&(o=o.split("-")[0]),n.forEach(d=>{const{codec:h,ssrc:p}=d;d.userdata=JSON.stringify({sdk_version:o,codec:h}),d.ssrc=`${p}`,c&&(d.attr={reason:"reconnect"})}),s.data.users.push(i),this.sendPackage(s)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=X(ft(X({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){T.info(`[${gt.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen),this.wsClient.off("onMessage",this.onMessage),this.wsClient.off("onError",this.onError),this.wsClient.off("onClose",this.onClose),this.wsClient.off("onConnectFail",this.onConnectFail),this.wsClient.off("onAuthInvalid",this.onAuthInvalid),this.wsClient.off("onNetworkError",this.onNetworkError),this.wsClient.off("onWillReconnect",this.onWillReconnect),this.wsClient.off("onReconnectStart",this.onReconnectStart),this.wsClient.off("onReconnectFail",this.onReconnectFail),this.wsClient.close()}sendPackage(e){[Fe.KEEPALIVE,Fe.RECONNECT,Fe.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Fe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{T.info(`[${gt.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==Fe.KEEPALIVE&&T.info(`[${gt.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Fe.JOINCHANNEL:this.onJoinResult(e);break;case Fe.KEEPALIVE:this.onKeepAliveRsp();break;case Fe.PUBLISH:this.onPublishResult(e);break;case Fe.NOTIFYJOIN:this.onNotifyJoin(e);break;case Fe.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Fe.LEAVECHANNEL:this.onLeaveResult(e);break;case Fe.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Fe.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Fe.STATUSREPORT:this.onStatusReport(e);break;case Fe.BYE:this.onBye(e);break;case Fe.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Fe.REFRESHURL:this.onRefreshUrlResult(e);break;case Fe.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new O(B.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};m(gt,"logName","RSMessageCenter");let rr=gt;var sl=Object.defineProperty,rl=Object.getOwnPropertyDescriptor,ar=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?rl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&sl(r,e,s),s};const Zi=(it=class extends oe{constructor(e,t,i,s=wt.prod){super();m(this,"messageCenter");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"reconnectData");m(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=s===wt.pre?St.pre:St.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){T.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,i,s){return I(this,null,function*(){return new Promise((n,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new rr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var h,p,u;if(T.info(`[${it.logName}]`,"join result: ",d),o.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,d.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(u=this.messageCenter)==null||u.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,B.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new O(B.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),T.info(`[${it.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:ut()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+De.queryingParam(l),s)})})}leave(){return T.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,s)=>{T.info(`[${it.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:s})):t(this.handleSignalError(i,"leave error"))}),T.info(`[${it.logName}]`,"send leave request"),this.messageCenter.leave()):(T.info(`[${it.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var s;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,c,o)=>{T.info(`[${it.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(ft(X({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(s=this.authInfo.sessionId)!=null?s:""),e.callid||(e.callid=ut()),T.info(`[${it.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(s,n,c)=>{var o,l;T.info(`[${it.logName}]`,"recv role update response "+s),s===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):i(this.handleSignalError(s,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return T.info(`[${it.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",s=>{const{code:n,description:c,data:o={}}=s||{};T.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),T.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return T.info(`[${it.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(s,n)=>{s===200?t():i(new O(s,n))}),this.messageCenter.reportStatus(e)):i(new O(-1,"No messageCenter"))})}handleSignalError(e,t,i=B.ERR_INNER){return new O(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return I(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,s,n,c,o,l,d,h,p,u,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",g=>{this.emit("onNotifyJoin",g)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",g=>{this.emit("onNotifyStatus",g)}),(s=this.messageCenter)==null||s.on("onNotifyLeave",g=>{this.emit("onNotifyLeave",g)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",g=>{this.emit("onNotifyPublish",g)}),(c=this.messageCenter)==null||c.on("onBye",(g,S)=>{this.emit("onBye",g,S)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",g=>{this.emit("onReconnectSuccess",g)}),(d=this.messageCenter)==null||d.on("onReconnectFail",g=>{this.emit("onReconnectFail",g)}),(h=this.messageCenter)==null||h.on("onConnectFail",g=>{this.emit("onConnectFail",g),this.reset()}),(p=this.messageCenter)==null||p.on("onNetworkError",g=>{this.emit("onNetworkError",g)}),(u=this.messageCenter)==null||u.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",g=>{this.emit("onUnknownMessage",g)})}},m(it,"logName","RoomServerSignaling"),it);ar([k()],Zi.prototype,"join",1),ar([k()],Zi.prototype,"publish",1),ar([k()],Zi.prototype,"roleUpdate",1);let al=Zi;var nl=Object.defineProperty,ol=Object.getOwnPropertyDescriptor;class nr extends oe{constructor(e,t,i,s=wt.prod){super();m(this,"signaling");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"env",wt.prod);m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=s,this.slsReporter=i}reset(){var e;T.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,i,s,n){return this.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new O(B.ERR_JOIN_ALREADY_JOINED,"already joined")):(T.info("[signalingmanager] create signaling"),this.signaling=new al(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),s&&(s.rs=Date.now()),this.signaling.join(e,t,i,n).then(l=>{this.authInfo=e,s&&(s.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var s;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(s=this.userName)!=null?s:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{i(n)})):i(new O(B.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(s=>{i(s)}):i(new O(-1,"no signaling"))})}setClientRole(e){return I(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const s=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),s}catch(s){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,s.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new O(B.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return I(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=X(X({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,s,n,c,o,l,d,h,p,u,f,g;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(s=this.signaling)==null||s.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(h=this.signaling)==null||h.on("onConnectFail",this.onConnectFail.bind(this)),(p=this.signaling)==null||p.on("onNetworkError",this.onNetworkError.bind(this)),(u=this.signaling)==null||u.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(g=this.signaling)==null||g.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}m(nr,"logName","SignalingManager"),((a,r,e,t)=>{for(var i,s=t>1?void 0:t?ol(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);t&&s&&nl(r,e,s)})([k(H)],nr.prototype,"publish",1);class Un{constructor(r){m(this,"taskProfile");m(this,"encodeParam");m(this,"users",[]);m(this,"backgroundColor",0);m(this,"backgrounds",[]);m(this,"watermarks",[]);m(this,"clockWidgets",[]);m(this,"cropMode");m(this,"mediaProcessMode");this.taskProfile=r}}class Bn{constructor(r,e,t){m(this,"userId");m(this,"streamType");m(this,"sourceType");this.userId=r,this.streamType=e,this.sourceType=t}}class Hn{constructor(r,e,t,i=0,s=16777215,n=Li.NOTO_SERIF_CJKSC_REGULAR){m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.x=r,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=s,this.fontType=n}toJson(r,e){return{x:Rt(this.x,r),y:Rt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Zs(this.fontColor),zorder:this.zOrder}}}var Fn=(a=>(a[a.NOT_DISPLAY=0]="NOT_DISPLAY",a[a.ALWAYS=1]="ALWAYS",a[a.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",a))(Fn||{});class or{constructor(r,e,t,i,s,n=0,c=1,o=1){m(this,"url");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"alpha");m(this,"display",1);m(this,"zOrder");this.url=r,this.x=e,this.y=t,this.width=i,this.height=s,this.zOrder=n,this.alpha=c,this.display=o}toJson(r,e){return{url:this.url,alpha:this.alpha,display:this.display,x:Rt(this.x,r),y:Rt(this.y,e),width:Rt(this.width,r),height:Rt(this.height,e),zorder:this.zOrder}}}m(or,"DisplayType",Fn);class jn{constructor(r,e,t,i,s=0,n=16777215,c=Li.NOTO_SERIF_CJKSC_REGULAR){m(this,"text");m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.text=r,this.x=e,this.y=t,this.fontSize=i,this.zOrder=s,this.fontColor=n,this.fontType=c}toJson(r,e){return{text:this.text,x:Rt(this.x,r),y:Rt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Zs(this.fontColor),zorder:this.zOrder}}}class $n{constructor(r,e,t,i,s,n=0,c){m(this,"userId");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"zOrder");m(this,"sourceType");m(this,"segmentType",Mi.LiveTranscodingNoBody);m(this,"images",[]);m(this,"texts",[]);this.userId=typeof r=="number"?r.toString():r,this.x=e,this.y=t,this.width=i,this.height=s,this.zOrder=n,c&&(this.sourceType=c)}toJson(r,e,t,i){const s={paneid:r,majorpane:0,x:Rt(this.x,e),y:Rt(this.y,t),width:Rt(this.width,e),height:Rt(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&Di[this.sourceType]?s.sourcetype=Di[this.sourceType]:s.sourcetype=Di[bi.LiveTranscodingCamera],this.segmentType&&i===Xi.LiveTranscodingVirtualBackground?s.segmenttype=this.segmentType:s.segmenttype=Mi.LiveTranscodingNoBody,s}}class cl{constructor(r){m(this,"_updateables");m(this,"_useWebworker");m(this,"_inited");m(this,"_active");m(this,"_previousRAFTime");m(this,"_previousWorkerTime");m(this,"_webWorkerString");m(this,"_webWorker");m(this,"_intervalThreshold");m(this,"_rafId");m(this,"_focusHandler",null);m(this,"_blurHandler",null);m(this,"_visibilityHandler",null);this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=r&&r>0&&r<=60?1/r:.1,this._webWorkerString=`
135
135
  var running = false;
136
136
  function tick(){
137
137
  postMessage(Date.now());
@@ -146,4 +146,4 @@ onmessage = function(evt) {
146
146
  tick();
147
147
  }
148
148
  if (data === 'stop') running = false;
149
- });`,this._webWorker=void 0}_initWebWorker(){window.URL=window.URL||window.webkitURL;let s=new Blob([this._webWorkerString],{type:"application/javascript"});this._webWorker=new Worker(URL.createObjectURL(s)),this._webWorker.onmessage=e=>{let t=e.data;this._updateWorkerTime(t)}}_lostVisibility(){var s;this._previousWorkerTime=Date.now(),this._useWebworker=!0,this._webWorker||this._initWebWorker(),this._active&&((s=this._webWorker)==null||s.postMessage("start"))}_gainedVisibility(){this._useWebworker=!1,this._previousRAFTime=void 0,this._webWorker&&this._webWorker.postMessage("stop"),this._active&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)))}_init(){if(window.Worker){if(document.hidden===void 0)return window.addEventListener("focus",this._gainedVisibility.bind(this)),void window.addEventListener("blur",this._lostVisibility.bind(this));document.addEventListener("visibilitychange",()=>{document.hidden===!0?this._lostVisibility():this._gainedVisibility()},!1)}}_updateWorkerTime(s){let e=(s-(this._previousWorkerTime||0))/1e3;e>this._intervalThreshold&&(this._update(e),this._previousWorkerTime=s)}_updateRAFTime(s){this._previousRAFTime===void 0&&(this._previousRAFTime=s);let e=(s-this._previousRAFTime)/1e3;e>this._intervalThreshold&&(this._update(e),this._previousRAFTime=s),!this._useWebworker&&this._active?this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)):this._rafId=0}_update(s){for(let e=0;e<this._updateables.length;e++)this._updateables[e]._update(typeof s=="number"?s:parseFloat(s))}register(s){this._updateables.push(s),this._inited===!1&&(this._inited=!0,this._init()),this._active===!1&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)),this._active=!0)}unregister(s){const e=this._updateables.indexOf(s);e!==-1&&this._updateables.splice(e,1),this._updateables.length===0&&(this._active=!1,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._useWebworker&&this._webWorker&&this._webWorker.postMessage("stop"))}}class Ln extends xt{constructor(e,t=10){super("AliRtcImageHolder");m(this,"url");m(this,"image");m(this,"canvas");m(this,"mediaStream");m(this,"updateableManager");m(this,"updateable");m(this,"hasVideoTrack",!1);this.url=e,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.drawImageToCanvas(),this.updateableManager=new Zc(t)}get initOptions(){return{imageUrl:""}}setOptions(e){e.imageUrl&&(this.options=e,e.imageUrl!==this.url&&this.drawImageToCanvas())}drawImageToCanvas(){return E(this,null,function*(){if(!this.url)return;const e=this.canvas.getContext("2d"),t=document.createElement("img");let i;this.image=t,t.crossOrigin="anonymous",t.src=this.url;const{width:r,height:n}=yield new Promise(c=>{t.onload=()=>{i&&clearTimeout(i),c({width:t.width||16,height:t.height||16})},t.onerror=()=>{i&&clearTimeout(i),c({width:16,height:16})},i=setTimeout(()=>{c({width:16,height:16})},5e3)});this.canvas.width=r,this.canvas.height=n,e.drawImage(t,0,0,r,n)})}start(){return E(this,null,function*(){var i;if(!this.url)throw new Error("no image url founded");if(!this.canvas)throw new Error("get canvas error");const e=this.canvas.captureStream(25),t=this.canvas.getContext("2d");return this.image&&this.image.width&&t.drawImage(this.image,0,0,this.image.width,this.image.height),this.mediaStream=e,t.fillStyle="transparent",this.updateable={_update:()=>{t.fillRect(0,0,1,1)}},this.updateableManager.register(this.updateable),(i=e.getVideoTracks())==null?void 0:i[0]})}stop(){var e,t;this.updateable&&(this.updateableManager.unregister(this.updateable),this.updateable=null),(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null||t.stop(),this.mediaStream=void 0}isSupported(){return!0}shouldUpdate(e){return this.hasVideoTrack===!!e.originVideoTrack}process(e){return E(this,null,function*(){if(this.hasVideoTrack=!!e.originVideoTrack,e.originVideoTrack){const i=e.currentVideoTrack;return i&&i.id===e.originVideoTrack.id||e.updateVideoTrack(e.originVideoTrack),void this.stop()}const t=yield this.start();e.updateVideoTrack(t)})}}class Ii{static checkString(s){return typeof s=="string"}static checkNumber(s){return typeof s=="number"}static checkHtmlVideoElement(s){return s&&s.nodeName==="VIDEO"}static checkHtmlAudioElement(s){return s&&s.nodeName==="AUDIO"}static checkAuthInfo(s){return s?s.appId?s.channelId?Ii.checkString(s.channelId)?s.userId?Ii.checkString(s.userId)?s.timestamp?Ii.checkNumber(s.timestamp)?s.token?null:new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"userId is not string"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"channelId is not string"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded"):new V(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded")}static checkMediaStreamTrack(s){return s instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(s){return s&&(s.width||s.height||s.frameRate||s.bitrateMax)}}var el=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,j=(a,s,e,t)=>{for(var i,r=t>1?void 0:t?tl(s,e):s,n=a.length-1;n>=0;n--)(i=a[n])&&(r=(t?i(s,e,r):i(r))||r);return t&&r&&el(s,e,r),r};let Ft;const F=(z=class extends ne{constructor(e){super();m(this,"channelProfile");m(this,"clientRole");m(this,"signalingManager");m(this,"bizControl");m(this,"liveTranscoding");m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");m(this,"connectState",se.AliRtcConnectionStatusInit);m(this,"networkError",!1);m(this,"_audioOnlyMode",!1);m(this,"_authInfoWillExpireTimer",null);m(this,"_authInfoExpiredTimer",null);m(this,"_serverCheckAuthInfoTimestamp",null);m(this,"_localCheckAuthInfoTimestamp",null);m(this,"_proxyAiTid",null);m(this,"_agentParam",null);m(this,"sessionId");this.config=e;const t=Date.now();C.init(e==null?void 0:e.globalEnv),this.slsReporter=new Jc(this,e==null?void 0:e.globalEnv),this.channelProfile=Rt.AliRtcSdkCommunication,this.clientRole=mt.AliRtcSdkLive,this.liveTranscoding=new Fc(this.slsReporter),this.signalingManager=new Xr(this.channelProfile,this.clientRole,this.slsReporter,(e==null?void 0:e.env)===lt.pre?lt.pre:lt.prod),this.addSignalingManagerListeners(),this.maxSignalingReconnectDuration=e==null?void 0:e.maxSignalingReconnectDuration,this.bizControl=new Ye({slsReporter:this.slsReporter,signalingManager:this.signalingManager,parameter:e==null?void 0:e.parameter}),this.addBizControlListeners(),this.addPublisherListeners(),this.slsReporter.reportConnectionLatencyEvent(Xe.CREATE_ENGINE,tt.START,"","",t),this.slsReporter.reportConnectionLatencyEvent(Xe.CREATE_ENGINE,tt.END,"","",Date.now()),this.slsReporter.reportSDKCreated(t)}static getSdkVersion(){return gi}static setLogLevel(e){C.setLogLevel(e)}static getInstance(e){return z._instance||(J.AliRTS.ENV=(e==null?void 0:e.globalEnv)==="SEA"?"SEA":void 0,Ft==null||Ft.updateOptions({region:(e==null?void 0:e.globalEnv)==="SEA"?"sg":"cn"}),Ft==null||Ft.setReady(),z._instance=new z(e)),z._instance}destroy(){return E(this,null,function*(){z._instance=void 0,yield this.leaveChannel(),yield this.bizControl.clear(),C.destroy()})}get channel(){return this.bizControl.channel}get userId(){return this.bizControl.userId}get remoteUsers(){return this.bizControl.remoteUsers}get publisher(){return this.bizControl.publisher}get publishAudioStream(){return this.publisher.publishStreams.audio}get isPublishing(){const{publisher:e}=this.bizControl;return!!e&&e.isPublishing}get currentRoleCanPublish(){return this.channelProfile===Rt.AliRtcSdkCommunication||this.clientRole===mt.AliRtcSdkInteractive}addPublisherListeners(){this.publisher.on(Ze.Local,e=>{C.event("[Publisher] Device Status Change",e),this.onLocalDeviceStatusChange(e)}),this.publisher.on(Qt.VideoTrackEnded,()=>{C.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",ze.AliEngineLocalDeviceTypeCamera,De.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),this.publisher.on(Qt.ScreenTrackEnded,()=>{C.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",ze.AliEngineLocalDeviceTypeDisplay,De.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),this.publisher.on(Qt.AudioTrackEnded,()=>{C.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",ze.AliEngineLocalDeviceTypeMic,De.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),this.publisher.on("localDeviceException",(e,t,i="")=>{this.emit("localDeviceException",e,t,i)}),this.publisher.on("audioPublishStateChanged",(e,t,i)=>{var r;this.emit("audioPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("videoPublishStateChanged",(e,t,i)=>{var r;this.emit("videoPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("dualStreamPublishStateChanged",(e,t,i)=>{var r;this.emit("dualStreamPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("screenPublishStateChanged",(e,t,i)=>{var r;this.emit("screenSharePublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("dataPublishStateChanged",(e,t,i)=>{var r;this.emit("dataPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")})}occurError(e,t){C.event(`[${z.logName}]`,"Occur Error",e,t),this.emit("onOccurError",e,t),this.emit("occurError",e,t)}addBizControlListeners(){this.bizControl.rtsManager.on("disconnected",()=>E(this,null,function*(){C.event(`[${z.logName}]`,"RTS Disconnected"),(yield ke.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.bizControl.rtsManager.on("subscribeexceeds",()=>E(this,null,function*(){C.event(`[${z.logName}]`,"RTS SubscribeExceeds"),this.bizControl.rtsManager.clear(),yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.bizControl.rtsManager.on("seimessage",(e,t,i)=>E(this,null,function*(){const r=this.remoteUsers.find(n=>ke.removeQueryString(n.streamUrl)===ke.removeQueryString(e));if(r){try{this.emit("mediaExtensionMsgReceived",r.userId,i,t)}catch(n){}if(t===99)try{const n=JSON.parse(new TextDecoder().decode(i));if(r.audioSSRC&&this.slsReporter.reportCumuAudioDelay(r.audioSSRC,n),r.videoSSRC){const c=yield this.bizControl.rtsManager.getSubscribeVideoStats(e);(c==null?void 0:c.frameHeight)===16&&(c==null?void 0:c.frameWidth)===16||this.slsReporter.reportCumuVideoDelay(r.videoSSRC,n)}}catch(n){}}})),this.bizControl.on(Ze.Remote,(e,t)=>{C.event(`[${z.logName}]`,"RemoteUser Device Status Change",e,t)}),this.bizControl.on("remoteUserJoin",(e,t)=>{this.emit("remoteUserOnLineNotify",e,t)}),this.bizControl.on("remoteTrackAvailableChange",(e,t,i)=>{this.emit("remoteTrackAvailableNotify",e,t,i)}),this.bizControl.on("audioSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("audioSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("videoSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("videoSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("screenSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("screenShareSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("dataSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("dataSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("userAudioMuted",(e,t)=>{this.emit("userAudioMuted",e,t)}),this.bizControl.on("userVideoMuted",(e,t)=>{this.emit("userVideoMuted",e,t)}),this.bizControl.on("userScreenMuted",(e,t)=>{this.emit("userScreenMuted",e,t)}),this.bizControl.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.bizControl.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.bizControl.on("remoteVideoAutoPlayFail",(e,t)=>{this.emit("remoteVideoAutoPlayFail",e,t)}),this.bizControl.on("remoteAudioPlayError",(e,t)=>{this.emit("remoteAudioPlayError",e,t)}),this.bizControl.on("remoteVideoPlayError",(e,t)=>{this.emit("remoteVideoPlayError",e,t)}),this.bizControl.on("rtcStats",e=>{this.emit("rtcStats",e)}),this.bizControl.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.bizControl.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.bizControl.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.bizControl.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.bizControl.on("remoteSubscribeError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("occurError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("remoteDataChannelMessage",(e,t)=>{this.emit("dataChannelMsg",e,t)}),this.bizControl.on("remoteUserSubscribedDataChannel",e=>{this.emit("remoteUserSubscribedDataChannel",e)}),this.bizControl.on("networkQuality",e=>{this.emit("networkQuality",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(C.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{C.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e)}),this.signalingManager.on("onNotifyStatus",e=>{C.event("[Signaling] Notify Status ",e),e.forEach(t=>{this.bizControl.updateRemoteUserDeviceStatus(t)})}),this.signalingManager.on("onNotifyLeave",e=>{C.event("[Signaling] Notify Leave ",e),e.forEach(t=>E(this,null,function*(){yield this.bizControl.removeLeftUser(t),this.emit("remoteUserOffLineNotify",t.userid,t.leavecode)}))}),this.signalingManager.on("onBye",(e,t)=>{C.event("[Signaling] Bye ",e,t),this.slsReporter.reportError({message:`reason: ${e}, description: ${t}`}),this.emit("bye",e),this.signalingManager.reset(),this.leaveChannel(),this.slsReporter.reportBye(e)}),this.signalingManager.on("onConnectFail",e=>{C.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.bizControl.leave(),this.signalingManager.reset(),this.connectState=se.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",se.AliRtcConnectionStatusFailed,Et.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{this.slsReporter.reportWarning("signaling network error"),C.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{C.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{this.onNetworkError(),C.event("[Signaling] Reconnect Start "),this.connectState=se.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",se.AliRtcConnectionStatusReconnecting,Et.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{C.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{this.slsReporter.reportWarning("signaling reconnect fail: ${err.code}"),C.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{this.slsReporter.reportWarning("signaling error: ${err.message}"),C.event("[Signaling] Error ",e),this.onError(e)}),this.signalingManager.on("onUnknownMessage",e=>{if(e.msgtype==="proxyai"&&e.tid===this._proxyAiTid){let t=e.data.retcode;t===200&&(t=0),this.emit("AIAgentResult",t,this._agentParam.action,e.data.body)}})}backToUnpublishStatus(){this.connectState=se.AliRtcConnectionStatusDisconnected,this.publisher.isPublishing&&this.publisher.clearPublishState(),this.networkError=!1}handleUsersJoin(e){e.forEach(t=>{this.bizControl.addUser(t,me.Join)})}onLocalDeviceStatusChange(e){C.event(`[${z.logName}]`,Ze.Local,e),this.signalingManager.reportStatus(e).then(()=>{C.debug("[signaling] reportStatus suc")}).catch(t=>{C.error("[signaling] reportStatus failed",t)})}resumePublishForNetworkRecovery(){return E(this,null,function*(){try{yield this.publisher.resumePublish()}catch(e){const{code:t}=e;if(t===10205){let r=1;try{yield new Promise((n,c)=>{const o=setInterval(()=>E(this,null,function*(){r>1&&(clearInterval(o),c()),r+=1;try{yield this.publisher.resumePublish(),clearInterval(o),n()}catch(l){const{code:d}=l;d!==10205&&(clearInterval(o),c())}}),1e3)})}catch(n){}}throw e}})}onNetworkRecovery(e){return E(this,null,function*(){C.event(z.logName,"onNetworkRecovery",`rts isConnected: ${this.bizControl.rtsManager.isConnected}; rts isConnecting: ${this.bizControl.rtsManager.isConnecting}`,{users:e}),yield this.resumeSubList(e),this.networkError&&(this.networkError=!1,this.publisher.reportSelfDeviceStatus(),this.connectState=se.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",se.AliRtcConnectionStatusConnected,Et.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return E(this,null,function*(){if(e){const{joinList:t,leaveList:i,presentList:r}=this.bizControl.diffUsers(e);C.info(`[${z.logName}]`,"resumeSubList",{joinList:t,leaveList:i,presentList:r}),this.handleUsersJoin(t),i.forEach(n=>{C.event(z.logName,Ce.UserLeft,n.userid,n.reason),this.bizControl.onRemotePublishStateChange({userid:n.userid,displayname:"",callid:"",tracks:[]}),this.bizControl.removeLeftUser(n),this.emit("remoteUserOffLineNotify",n.userid,Xi.AliRtcUserOfflineQuit)}),r.forEach(n=>{this.bizControl.onRemotePublishStateChange(n)})}else for(let t=0;t<this.remoteUsers.length;t++){const i=this.remoteUsers[t];try{i.restore(),i.updateSubscribe(me.Resume)}catch(r){}}})}retrySubscribe(e){return E(this,null,function*(){const t=this.bizControl.getRemoteUser(e);if(!t)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);t.restore(),t.updateSubscribe(me.Retry)})}onNetworkError(){this.connectState===se.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=se.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",se.AliRtcConnectionStatusDisconnected,Et.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.slsReporter.reportError(e),C.event(z.logName,Ce.Error,e)}setEnableDualVideoStream(e,t){this.bizControl.setEnableDualVideoStream(e,t)}hadPushStream(e){if(!this.publisher||!e)throw new V(B.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){return this.publisher.getCurrentMicDeviceId()}setChannelProfile(e){if(![se.AliRtcConnectionStatusInit,se.AliRtcConnectionStatusDisconnected,se.AliRtcConnectionStatusFailed].includes(this.connectState))throw new V(B.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===Rt.AliRtcSdkCommunication&&(this.clientRole=mt.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}startDefaultDevices(){return E(this,null,function*(){if(!this.publisher)return;const{hasCamera:e,hasMicrophone:t,hasScreenShare:i}=this.publisher;if(!e&&!t&&!i){try{yield this.publisher.startDefaultCameraAndMic(this._audioOnlyMode)}catch(r){C.warn(`[${z.logName}]`,"startDefaultDevices failed",r.code,r.message),r instanceof V&&this.occurError(r);const n=r.code;this.occurError(new V(n>=B.ERR_CAMERA_OPEN_FAIL&&n<=B.ERR_CAMERA_NOT_AVAILABLE?B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED:B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED,`auto publish device failed, ${r.message||""}`))}yield this.publisher.previewAll()}})}startPublish(e){return E(this,null,function*(){try{yield this.publisher.startPublish(!1,e)}catch(t){const i=this.publisher.publishStreams||{},r=[];i!=null&&i.audio&&r.push(B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),i!=null&&i.video&&r.push(B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),r.forEach(n=>{this.occurError(new V(n,`auto publish stream failed, ${t.message||""}`))})}})}setClientRole(e){return E(this,null,function*(){try{if(this.channelProfile===Rt.AliRtcSdkCommunication)return;if(!Object.values(mt).includes(e))throw new V(B.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.slsReporter.reportRoleUpdate(this.clientRole,e),this.isInCall()?this.clientRole===mt.AliRtcSdkInteractive?(this.publisher.isPublishing?yield this.publisher.unPublish():yield this.publisher.clearStream(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevices(),yield this.startPublish(Tt.ROLE_CHANGE)):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(t){throw t.code===403&&this.emit("authInfoExpired"),t}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new V(B.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new V(B.ERR_INNER,"can not change audioRedEnabled in call");this.bizControl.setAudioRedEnabled(e)}setVideoCodec(e){this.bizControl.setVideoCodec(e)}setCheckAuthInfoTimer(e,t){const i=1e3*(e-t);this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},i),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},i-3e4),this._serverCheckAuthInfoTimestamp=t,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}joinChannel(r,n){return E(this,arguments,function*(e,t,i={}){const c=Date.now();let o,l=typeof t=="string"?t:t==null?void 0:t.userName;if(typeof e=="string")try{const p=JSON.parse(window.atob(e));o={appId:p.appid,channelId:p.channelid,userId:p.userid,timestamp:p.timestamp,nonce:p.nonce,token:p.token}}catch(p){throw new V(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${p.message||""}`)}else o=e;l||(l=o.userId);const d={start:Date.now()};let u=Ii.checkAuthInfo(o);if(se.AliRtcConnectionStatusInit!==this.connectState&&se.AliRtcConnectionStatusDisconnected!==this.connectState&&se.AliRtcConnectionStatusFailed!==this.connectState){const p=new V(B.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===se.AliRtcConnectionStatusConnecting&&(p.message="Repeated operation during login"),this.slsReporter.reportJoin(p.code,d,""),p}{if(u)throw this.connectState=se.AliRtcConnectionStatusFailed,this.slsReporter.reportJoin(u.code,d,""),this.slsReporter.reportJoinResult(u),u;o.sessionId=ke.createCallid("web"),this.sessionId=o.sessionId,this.slsReporter.start(o),this.slsReporter.reportConnectionLatencyEvent(Xe.JOIN,tt.START,"","",c),this.connectState=se.AliRtcConnectionStatusConnecting,this.emit("connectionStatusChange",se.AliRtcConnectionStatusConnecting,Et.AliRtcConnectionSignalingConnecting),C.setSessionID(o.appId,o.sessionId);const p=()=>E(this,null,function*(){var g,S;try{let b="Conference";typeof t=="object"&&t.capabilityProfile===Ai.Human&&(b="AIUser");const v=JSON.parse(this.getParameter());v.joinMode&&(b=v.joinMode);const R=new fi(((g=this.config)==null?void 0:g.env)||lt.prod,o,b);if(R.result){const w=(h=R.result.config,f=rt.EnableNonOnePcDefaultJoinMode,Kt(h==null?void 0:h.data,f));R.result.useonepc&&w!==!1||(b=""),C.info(`[${fi.logName}]`,"got allocate result from localStorage",`joinMode: ${b}`,R.result.useonepc,w)}else C.info(`[${fi.logName}]`,"no allocate result in localStorage",`joinMode: ${b}`);b&&(i.joinmode=b);const _=Date.now(),y=yield this.signalingManager.join(o,l,this.maxSignalingReconnectDuration,d,i);y.l1ip?(C.info("allocate l1 pub ip with mode",b,y.l1ip),this.bizControl.rtsManager.preferredPubL1Ip=y.l1ip):this.bizControl.rtsManager.preferredPubL1Ip=void 0,y.l1subip?(C.info("allocate l1 sub ip with mode",b,y.l1subip),this.bizControl.rtsManager.preferredSubL1Ip=y.l1subip):this.bizControl.rtsManager.preferredSubL1Ip=void 0;const A=Date.now();this.connectState=se.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",se.AliRtcConnectionStatusConnected,Et.AliRtcConnectionSignalingJoinRoomSuccess),R.fetchAndUpdate(),this.bizControl.init(o,y,{capabilityProfile:typeof t=="object"?t.capabilityProfile:Ai.Default,robotUserId:typeof t=="object"?t.robotUserId:void 0}),this.setCheckAuthInfoTimer(o.timestamp,y.timestamp),this.liveTranscoding.setAuthInfo(o),this.slsReporter.reportJoin(0,d,y.tid),this.slsReporter.reportJoinResult(null),this.slsReporter.reportConnectionLatencyEvent(Xe.JOIN,tt.SEND_SIG,"","",_),this.slsReporter.reportConnectionLatencyEvent(Xe.JOIN,tt.RECV_RST,"","",A),this.slsReporter.reportConnectionLatencyEvent(Xe.JOIN,tt.END,"","")}catch(b){const v=(S=b.code)!=null?S:-1,R=b.reason||b.message||"";throw this.connectState=se.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",se.AliRtcConnectionStatusDisconnected,Et.AliRtcConnectionSignalingJoinRoomFailure),this.slsReporter.reportJoin(v,d,""),this.slsReporter.reportJoinResult(b),new V(v,R)}var h,f});this.currentRoleCanPublish?(yield Promise.all([p(),this.startDefaultDevices()]),yield this.startPublish(Tt.JOIN_CHANNEL)):yield p(),this.publisher.reportSelfDeviceStatus(),this.remoteUsers.forEach(h=>{h.updateSubscribe(me.Join)})}})}joinAIChannel(e,t,i){return E(this,null,function*(){return this._proxyAiTid=dt(),this._agentParam=i,this.joinChannel(e,t,{proxyai:{tid:this._proxyAiTid,region:i.region,proxydata:JSON.stringify({Region:i.region,Action:i.action,ActionParams:i.params})}})})}leaveChannel(){return E(this,null,function*(){var t;this.slsReporter.reportLeaveInvoked(),yield this.bizControl.leave();let e=new Date().getTime();if(se.AliRtcConnectionStatusConnected===this.connectState)try{let i;i=yield this.signalingManager.leave(),this.slsReporter.reportLeave(new Date().getTime()-e,0,(t=i==null?void 0:i.tid)!=null?t:"")}catch(i){this.slsReporter.reportLeave(new Date().getTime()-e,i.code,i.reason)}else this.slsReporter.reportLeave(0,0,"");this.sessionId=void 0,this.networkError=!1,this.connectState=se.AliRtcConnectionStatusDisconnected,this.clearCheckAuthInfoTimer(),this.liveTranscoding.clear(),this.slsReporter.stop(),this.signalingManager.reset(),C.reportEnd()})}isInCall(){return this.connectState===se.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return E(this,null,function*(){let t;if(typeof e=="string")try{const d=JSON.parse(window.atob(e));t={userId:d.userid,timestamp:d.timestamp,nonce:d.nonce,token:d.token}}catch(d){throw new V(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${d.message||""}`)}else t=e;const{userId:i,nonce:r,timestamp:n,token:c,role:o}=t,l={userId:i,nonce:r,timestamp:n,token:c,role:o};try{yield this.signalingManager.refreshAuthInfo(l),this.bizControl.refreshAuthInfo(l),this.liveTranscoding.refreshAuthInfo(l),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&t.timestamp&&this.setCheckAuthInfoTimer(t.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(d){throw d}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return E(this,null,function*(){this.publisher.setPublishLocalAudioStreamEnabled(e),this.connectState===se.AliRtcConnectionStatusConnected&&(e?this.publisher.hasMicrophone?yield this.publisher.updateStreams():yield this.startAudioCapture():yield this.publisher.publishUpdate())})}isLocalAudioStreamPublished(){var e;return(e=this.publisher.publishLocalAudioStreamEnabled)!=null?e:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.bizControl.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.bizControl.setWantSubAudio(e)}subscribeRemoteAudioStream(e,t){if(t&&!this.bizControl.isWantSubAudio)throw new V(B.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.bizControl.updateAudioWant(e,t)}resumeRemoteAudioStream(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);t.resumeAudio()}stopRemoteAudioPlay(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);t.stopPlayAudio()}publishLocalVideoStream(e){return E(this,null,function*(){this.publisher.setPublishLocalVideoStreamEnabled(e),this.connectState===se.AliRtcConnectionStatusConnected&&(e?this.publisher.hasCamera?yield this.publisher.updateStreams():yield this.enableLocalVideo():yield this.publisher.publishUpdate())})}isLocalVideoStreamPublished(){var e;return(e=this.publisher.publishLocalVideoStreamEnabled)!=null?e:!0}setRemoteDefaultVideoStreamType(e){[Ke.AliRtcVideoStreamTypeHigh,Ke.AliRtcVideoStreamTypeLow].includes(e)&&this.bizControl.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,t){[Ke.AliRtcVideoStreamTypeHigh,Ke.AliRtcVideoStreamTypeLow].includes(t)&&this.bizControl.setRemoteUserVideoStreamType(e,t)}setDefaultSubscribeAllRemoteVideoStreams(e){this.bizControl.setAutoSubVideo(e),this.bizControl.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.bizControl.setWantSubVideo(e),this.bizControl.setWantSubScreen(e)}subscribeRemoteMediaStream(e,t,i,r){const n=this.bizControl.getRemoteUser(e);if(!n)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);!i||t!==le.AliRtcVideoTrackScreen&&t!==le.AliRtcVideoTrackBoth?n.setWantSubScreen(!1):n.setWantSubScreen(!0),!i||t!==le.AliRtcVideoTrackCamera&&t!==le.AliRtcVideoTrackBoth?n.setWantSubVideo(!1):n.setWantSubVideo(!0),n.setWantSubAudio(r),i||r?n.subscribe({video:i,audio:r},me.User):n.stopSubscribe({video:!0,audio:!0})}resumeRemoteMediaStream(e,t){const i=this.bizControl.getRemoteUser(e);i&&i.resumeVideo(t)}getOnlineRemoteUsers(){return this.bizControl.remoteUsers.map(e=>e.userId)}getUserInfo(e){var t;return(t=this.bizControl.getRemoteUser(e))==null?void 0:t.remoteUserInfo}isUserOnline(e){return!!this.bizControl.remoteUsers.find(t=>t.userId===e)}startScreenShare(e){return E(this,null,function*(){const t={video:!1,audio:!1},{audio:i=!1,videoTrack:r,audioTrack:n}=e||{};if(r||n){t.screen=!0;const c=new MediaStream;r&&c.addTrack(r),n&&c.addTrack(n),t.mediaStream=c}else t.screen=!i||{audio:!0};yield this.publisher.createLocalStream(t)})}stopScreenShare(){return E(this,null,function*(){this.publisher.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return E(this,null,function*(){const{width:t,height:i}=e;if(t&&!isNaN(t)&&i&&!isNaN(i)&&t*i>9437184)throw new V(B.ERR_INVALID_ARGUMENTS,"width * height must be less than 9437184");const o=e,{bitrate:r}=o,n=Ot(o,["bitrate"]),c=X({},n);r&&(c.maxBitrate=e.bitrate),yield this.publisher.setScreenProfile(c)})}setScreenShareContentHint(e){return E(this,null,function*(){e&&this.publisher.setScreenContentHint(e)})}publishLocalScreenShareStream(e,t){return E(this,null,function*(){this.publisher.setPublishLocalScreenStreamEnabled(e),this.connectState===se.AliRtcConnectionStatusConnected&&(e?this.publisher.hasScreenShare?yield this.publisher.updateStreams():yield this.startScreenShare(t):yield this.publisher.publishUpdate())})}isScreenSharePublished(){var e;return(e=this.publisher.publishLocalScreenStreamEnabled)!=null?e:!0}setAudioShareVolume(e){if(typeof e!="number")throw new V(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.bizControl.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){this.publisher.muteLocalMic(e),this.connectState===se.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()}muteRemoteAudioPlaying(e,t=!1){const i=this.bizControl.getRemoteUser(e);if(!i)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);i.setAudioMuted(t)}muteAllRemoteAudioPlaying(e=!1){this.bizControl.setAudioMuted(e)}startAudioCapture(e){return E(this,null,function*(){const t={audio:e||!0};yield this.publisher.createLocalStream(t)})}setAudioConstraints(e){return E(this,null,function*(){yield this.publisher.setMicrophoneConstraints(e)})}stopAudioCapture(){this.publisher.stopAudioCapture()}switchMicrophone(e,t){return E(this,null,function*(){if(yield this.publisher.setMicrophoneDeviceId(e),!this.publisher.audioCaptureDisabled){if(t)return void(yield this.publisher.createLocalStream({audio:!0,mediaStream:new MediaStream([t])}));yield this.publisher.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new V(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({audio:Math.max(0,Math.min(e,400))/100})}setPlayoutVolume(e){if(typeof e!="number")throw new V(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setRemoteAudioVolume(e,t){const i=this.bizControl.getRemoteUser(e);if(!i)throw new V(B.ERR_INNER,`no remote user(${e}) founded`);if(typeof t!="number")throw new V(B.ERR_INVALID_ARGUMENTS,"volume must be a number");i.setPlayoutVolume(Math.max(0,Math.min(t,100))/100)}setAudioProfile(e){return E(this,null,function*(){yield this.publisher.setAudioProfile(e)})}getAudioTrack(e){return E(this,null,function*(){if(!e)return this.publisher.audioTrack;const t=this.bizControl.getRemoteUser(e);return t==null?void 0:t.getAudioTrack})}setLocalViewConfig(e,t){return E(this,null,function*(){var i;if(this._audioOnlyMode)throw new V(B.ERR_INNER,"Cannot set local view in audio only mode");(i=this.bizControl)==null||i.setLocalViewConfig(e,t),t===le.AliRtcVideoTrackCamera&&this.publisher.hasCamera?yield this.startPreview():t===le.AliRtcVideoTrackScreen&&this.publisher.hasScreenShare&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return E(this,null,function*(){const l=e,{cameraDirection:t,deviceId:i,bitrate:r,maxSendFrameRate:n}=l,c=Ot(l,["cameraDirection","deviceId","bitrate","maxSendFrameRate"]),o=X({},c);r&&(o.maxBitrate=r),n&&(o.maxSendFrameRate=n),Object.keys(o).length>0&&(yield this.publisher.setVideoProfile(o)),t!==void 0&&this.publisher.setCameraDirection(t),i&&this.publisher.setCameraDeviceId(i)})}setCameraCapturerContentHint(e){return E(this,null,function*(){e&&this.publisher.setVideoContentHint(e)})}enableLocalVideo(e=!0){return E(this,null,function*(){var t,i,r,n,c,o;if(this._audioOnlyMode)throw new V(B.ERR_INNER,"Cannot enable local video in audio only mode");e?((t=this.publisher.publishStreams)!=null&&t.video&&((r=(i=this.publisher.publishStreams)==null?void 0:i.video)==null||r.disableVideo(),(o=(c=(n=this.publisher.publishStreams)==null?void 0:n.video)==null?void 0:c.videoTrack)==null||o.stop()),yield this.publisher.startCameraCapture()):yield this.publisher.stopCameraCapture()})}muteLocalCamera(e){return E(this,null,function*(){this.publisher.muteLocalCamera(e),this.connectState===se.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}muteLocalScreen(e){return E(this,null,function*(){this.publisher.muteLocalScreen(e),this.connectState===se.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}setRemoteViewConfig(e,t,i){this.bizControl.setRemoteViewConfig(t,e,i)}isCameraOn(){var e;return(e=this.publisher.hasCamera)!=null?e:!1}switchCamera(e,t){return E(this,null,function*(){var r;if(this._audioOnlyMode)throw new V(B.ERR_INNER,"Cannot switch camera in audio only mode");const i={};if(e?(i.deviceId=e,this.slsReporter.reportSwitchCamera(e)):t||(i.cameraDirection=this.publisher.cameraDirection==="environment"?pi.CAMERA_FRONT:pi.CAMERA_REAR,this.slsReporter.reportSwitchCamera(this.publisher.cameraDirection||"")),yield this.setCameraCapturerConfiguration(i),!this.publisher.cameraCaptureDisabled){(r=this.publisher.cameraTrack)==null||r.stop();const n={video:!0};t&&(n.mediaStream=new MediaStream([t])),yield this.publisher.createLocalStream(n)}})}getCurrentCameraDeviceId(){return this.publisher.getCurrentCameraDeviceId()}startPreview(){return E(this,null,function*(){if(this._audioOnlyMode)throw new V(B.ERR_INNER,"Cannot start preview camera in audio only mode");this.publisher.hasCamera||(yield this.enableLocalVideo(!0)),yield this.publisher.previewAll({screen:!1})})}startPreviewScreen(e){return E(this,null,function*(){if(this._audioOnlyMode)throw new V(B.ERR_INNER,"Cannot start preview screen share in audio only mode");this.publisher.hasScreenShare||(yield this.startScreenShare(e)),yield this.publisher.previewAll({primary:!1})})}stopPreview(){return E(this,null,function*(){yield this.publisher.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return E(this,null,function*(){yield this.publisher.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return E(this,null,function*(){var n,c;const{userId:t,streamType:i}=e;if(!t)return i===Ve.AliRtcSdkStreamTypeCapture?this.publisher.cameraTrack:this.publisher.screenTrack;const r=this.bizControl.getRemoteUser(t);return i===Ve.AliRtcSdkStreamTypeCapture?(n=r==null?void 0:r.getCameraStream)==null?void 0:n.videoTrack:(c=r==null?void 0:r.getScreenStream)==null?void 0:c.videoTrack})}startPublishLiveStream(e,t){return E(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,t)})}updatePublishLiveStream(e,t){return E(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,t)})}updatePublishLiveStreamWithTaskId(e,t){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,t)}stopPublishLiveStream(e){return E(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var t;(t=this.bizControl)==null||t.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,t){return E(this,null,function*(){return this.sendMediaExtensionMsgEx(e,t,5)})}sendMediaExtensionMsgEx(e,t,i){return E(this,null,function*(){if(!this.publisher||!this.isPublishing)throw new V(B.ERR_INNER,"you should publish first");return this.slsReporter.reportSEIMessage(i,e.byteLength,t,0,!1),this.publisher.sendSEI(e,t,i)})}enablePlugin(e,t){this.bizControl.pluginManager.add(e,t)}removePlugin(e){this.bizControl.pluginManager.remove(e)}setPluginOption(e,t){const i=this.bizControl.pluginManager.get(e);i&&t&&i.setOptions(t)}getPluginByName(e){return this.bizControl.pluginManager.get(e)}getPluginOption(e){const t=this.bizControl.pluginManager.get(e);return t==null?void 0:t.getOptions()}isBeautyAvailable(){return this.bizControl.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.bizControl.pluginManager.get("AliRtcBeauty");if(!e)throw new V(Bt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i)throw new V(Bt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?i.enable():i.disable(),i.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+t.smoothnessLevel),0),whitening:Math.max(Math.min(1,+t.whiteningLevel),0)}})}enableBackgroundExchange(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i||!i.isEnable)throw new V(Bt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const r={setSegmentBackgroundImage:{backgroundImgUrl:e?t:""}};e&&(r.segmentBackgroundProcess={enable:!1}),i.setOptions(r)}enableBackgroundBlur(e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new V(Bt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const i={segmentBackgroundProcess:{type:0,enable:e}};e&&(i.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),t.setOptions(i)}setParameter(e){this.bizControl.setParameter(e)}getParameter(){return this.bizControl.getParameter()}sendDataChannelMessage(e){this.bizControl.sendDataChannelMessage(e)}subscribeRemoteStream(e){const{currentUserId:t,targetUserId:i}=e;if(i===t)throw new V(B.ERR_INNER,"targetUserId should not be equal to currentUserId");return new lr(e)}},m(z,"logName","AliRtcEngine"),m(z,"logError",!0),m(z,"isSupported",Sc),m(z,"isDualVideoStreamSupported",hr.isSupport),m(z,"getCameraList",()=>E(z,null,function*(){return(yield J.AliRTS.getCameraList()).filter(e=>e.deviceId)})),m(z,"getMicrophoneList",()=>E(z,null,function*(){return(yield J.AliRTS.getMicList()).filter(e=>e.deviceId)})),m(z,"getSpeakerList",()=>E(z,null,function*(){return(yield J.AliRTS.getSpeakerList()).filter(e=>e.deviceId)})),m(z,"_instance"),m(z,"AliRtcSdkChannelProfile",Rt),m(z,"AliRtcSdkClientRole",mt),m(z,"AliRtcVideoStreamType",Ke),m(z,"AliRtcVideoTrack",le),m(z,"AliRtcAudioTrack",zt),m(z,"AliRtcPublishState",ee),m(z,"AliRtcSubscribeState",oe),m(z,"AliRtcRawDataStreamType",Ve),m(z,"AliRtcLogLevel",cr),m(z,"AliRtcEngineLocalDeviceType",ze),m(z,"AliRtcEngineLocalDeviceExceptionType",De),m(z,"AliRtcConnectionStatus",se),m(z,"AliRtcConnectionStatusChangeReason",Et),m(z,"AliRtcPlugin",xt),m(z,"AliRtcPluginTrackType",ci),m(z,"AliRtcImageHolderPlugin",Ln),m(z,"AliRtcLiveTranscodingParam",Wi),m(z,"AliRtcLiveTranscodingEncodeParam",jr),m(z,"AliRtcLiveTranscodingMixParam",Cn),m(z,"AliRtcLiveTranscodingSingleParam",kn),m(z,"AliRtcTranscodingClockWidget",Pn),m(z,"AliRtcTranscodingImage",Yr),m(z,"AliRtcTranscodingText",Mn),m(z,"AliRtcTranscodingUser",Nn),m(z,"AliRtcLiveTranscodingMixMode",wi),m(z,"AliRtcLiveTranscodingStreamType",Vr),m(z,"AliRtcLiveTranscodingSourceType",di),m(z,"AliRtcLiveTranscodingTaskProfile",Ur),m(z,"AliRtcLiveTranscodingAudioSampleRate",ji),m(z,"AliRtcLiveTranscodingSegmentType",Ei),m(z,"AliRtcLiveTranscodingFontType",Ti),m(z,"AliRtcLiveTranscodingCropMode",Br),m(z,"AliRtcLiveTranscodingMediaProcessMode",$i),m(z,"AliRtcLiveTranscodingState",Hr),m(z,"AliRtcLiveTranscodingErrorCode",Pt),m(z,"AliRtcTrascodingPublishTaskStatus",Fr),m(z,"AliRtcDataChannelMsg",Ut),m(z,"AliRtcDataMsgType",Dr),m(z,"Plugin",xt),z);j([k()],F.prototype,"destroy",1),j([k()],F.prototype,"backToUnpublishStatus",1),j([k()],F.prototype,"resumePublishForNetworkRecovery",1),j([k()],F.prototype,"onNetworkRecovery",1),j([k()],F.prototype,"resumeSubList",1),j([k(H)],F.prototype,"retrySubscribe",1),j([k(H)],F.prototype,"setEnableDualVideoStream",1),j([k(H)],F.prototype,"setChannelProfile",1),j([k(H)],F.prototype,"setClientRole",1),j([k(H)],F.prototype,"setAudioOnlyMode",1),j([k()],F.prototype,"clearCheckAuthInfoTimer",1),j([k(H)],F.prototype,"joinChannel",1),j([k(H)],F.prototype,"joinAIChannel",1),j([k(H)],F.prototype,"leaveChannel",1),j([k(H)],F.prototype,"refreshAuthInfo",1),j([k(H)],F.prototype,"publishLocalAudioStream",1),j([k(H)],F.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),j([k(H)],F.prototype,"subscribeAllRemoteAudioStreams",1),j([k(H)],F.prototype,"subscribeRemoteAudioStream",1),j([k(H)],F.prototype,"resumeRemoteAudioStream",1),j([k(H)],F.prototype,"stopRemoteAudioPlay",1),j([k(H)],F.prototype,"publishLocalVideoStream",1),j([k(H)],F.prototype,"setRemoteDefaultVideoStreamType",1),j([k(H)],F.prototype,"setRemoteUserVideoStreamType",1),j([k(H)],F.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),j([k(H)],F.prototype,"subscribeAllRemoteVideoStreams",1),j([k(H)],F.prototype,"subscribeRemoteMediaStream",1),j([k(H)],F.prototype,"resumeRemoteMediaStream",1),j([k(([a])=>[`${a==null?void 0:a.audio}`])],F.prototype,"startScreenShare",1),j([k()],F.prototype,"stopScreenShare",1),j([k(H)],F.prototype,"setScreenShareConfiguration",1),j([k(H)],F.prototype,"setScreenShareContentHint",1),j([k()],F.prototype,"publishLocalScreenShareStream",1),j([k(H)],F.prototype,"setAudioShareVolume",1),j([k(H)],F.prototype,"enableAudioVolumeIndication",1),j([k(H)],F.prototype,"muteLocalMic",1),j([k(H)],F.prototype,"muteRemoteAudioPlaying",1),j([k(H)],F.prototype,"muteAllRemoteAudioPlaying",1),j([k(H)],F.prototype,"startAudioCapture",1),j([k(H)],F.prototype,"setAudioConstraints",1),j([k()],F.prototype,"stopAudioCapture",1),j([k(H)],F.prototype,"switchMicrophone",1),j([k(H)],F.prototype,"setRecordingVolume",1),j([k(H)],F.prototype,"setPlayoutVolume",1),j([k(H)],F.prototype,"setRemoteAudioVolume",1),j([k(H)],F.prototype,"setAudioProfile",1),j([k(H)],F.prototype,"getAudioTrack",1),j([k(H)],F.prototype,"setLocalViewConfig",1),j([k(H)],F.prototype,"setCameraCapturerConfiguration",1),j([k(H)],F.prototype,"setCameraCapturerContentHint",1),j([k(H)],F.prototype,"enableLocalVideo",1),j([k(H)],F.prototype,"muteLocalCamera",1),j([k(H)],F.prototype,"muteLocalScreen",1),j([k(H)],F.prototype,"setRemoteViewConfig",1),j([k(H)],F.prototype,"switchCamera",1),j([k()],F.prototype,"startPreview",1),j([k()],F.prototype,"startPreviewScreen",1),j([k()],F.prototype,"stopPreview",1),j([k()],F.prototype,"stopPreviewScreen",1),j([k()],F.prototype,"startPublishLiveStream",1),j([k()],F.prototype,"updatePublishLiveStream",1),j([k()],F.prototype,"updatePublishLiveStreamWithTaskId",1),j([k()],F.prototype,"stopPublishLiveStream",1),j([k()],F.prototype,"stopPublishLiveStreamWithTaskId",1),j([k(H)],F.prototype,"setEnableMediaExtensionMsg",1),j([k(([a,s,e])=>[a.byteLength,s,e])],F.prototype,"sendMediaExtensionMsgEx",1),j([k(([a,s])=>[a.name||"",s])],F.prototype,"enablePlugin",1),j([k(H)],F.prototype,"removePlugin",1),j([k(H)],F.prototype,"setPluginOption",1),j([k(H)],F.prototype,"getPluginByName",1),j([k(H)],F.prototype,"getPluginOption",1),j([k(H)],F.prototype,"setBeautyEffect",1),j([k(H)],F.prototype,"enableBackgroundExchange",1),j([k(H)],F.prototype,"enableBackgroundBlur",1),j([k(H)],F.prototype,"setParameter",1),j([k(([a])=>{var s;return[(s=a.data)==null?void 0:s.byteLength]})],F.prototype,"sendDataChannelMessage",1),j([k(H)],F.prototype,"subscribeRemoteStream",1),j([k(H)],F,"setLogLevel",1);let xn=F;Ft=new kr({businessName:"imp-web-rtc",version:(On=xn.getSdkVersion())!=null?On:"unknown",env:"prod",disabled:window.AliRtcOptionsDisableProxy===!0,deferRegionSet:!0});const il=Ft.shallowWrapClass(xn);W.AliRtcAudioTrack=zt,W.AliRtcCapabilityProfile=Ai,W.AliRtcConnectionStatus=se,W.AliRtcConnectionStatusChangeReason=Et,W.AliRtcDataChannelMsg=Ut,W.AliRtcDataMsgType=Dr,W.AliRtcEngineLocalDeviceExceptionType=De,W.AliRtcEngineLocalDeviceType=ze,W.AliRtcErrorCode=B,W.AliRtcImageHolderPlugin=Ln,W.AliRtcLiveTranscodingAudioSampleRate=ji,W.AliRtcLiveTranscodingCropMode=Br,W.AliRtcLiveTranscodingEncodeParam=jr,W.AliRtcLiveTranscodingErrorCode=Pt,W.AliRtcLiveTranscodingFontType=Ti,W.AliRtcLiveTranscodingMediaProcessMode=$i,W.AliRtcLiveTranscodingMixMode=wi,W.AliRtcLiveTranscodingMixParam=Cn,W.AliRtcLiveTranscodingParam=Wi,W.AliRtcLiveTranscodingSegmentType=Ei,W.AliRtcLiveTranscodingSingleParam=kn,W.AliRtcLiveTranscodingSourceType=di,W.AliRtcLiveTranscodingState=Hr,W.AliRtcLiveTranscodingStreamType=Vr,W.AliRtcLiveTranscodingTaskProfile=Ur,W.AliRtcLocalStreamInfo=xr,W.AliRtcLogLevel=cr,W.AliRtcNetworkQuality=Qe,W.AliRtcPlugin=xt,W.AliRtcPluginTrackType=ci,W.AliRtcPluginType=Sn,W.AliRtcPublishState=ee,W.AliRtcRawDataStreamType=Ve,W.AliRtcRemoteUserInfo=gn,W.AliRtcSdkChannelProfile=Rt,W.AliRtcSdkClientRole=mt,W.AliRtcSubscribeState=oe,W.AliRtcTranscodingClockWidget=Pn,W.AliRtcTranscodingImage=Yr,W.AliRtcTranscodingText=Mn,W.AliRtcTranscodingUser=Nn,W.AliRtcTrascodingPublishTaskStatus=Fr,W.AliRtcVideoStreamType=Ke,W.AliRtcVideoTrack=le,W.default=il,Object.defineProperties(W,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
149
+ });`,this._webWorker=void 0}_initWebWorker(){window.URL=window.URL||window.webkitURL;let r=new Blob([this._webWorkerString],{type:"application/javascript"});this._webWorker=new Worker(URL.createObjectURL(r)),this._webWorker.onmessage=e=>{let t=e.data;this._updateWorkerTime(t)}}_lostVisibility(){var r;this._previousWorkerTime=Date.now(),this._useWebworker=!0,this._webWorker||this._initWebWorker(),this._active&&((r=this._webWorker)==null||r.postMessage("start"))}_gainedVisibility(){this._useWebworker=!1,this._previousRAFTime=void 0,this._webWorker&&this._webWorker.postMessage("stop"),this._active&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)))}_init(){if(window.Worker){if(document.hidden===void 0)return this._focusHandler=this._gainedVisibility.bind(this),this._blurHandler=this._lostVisibility.bind(this),window.addEventListener("focus",this._focusHandler),void window.addEventListener("blur",this._blurHandler);this._visibilityHandler=()=>{document.hidden===!0?this._lostVisibility():this._gainedVisibility()},document.addEventListener("visibilitychange",this._visibilityHandler,!1)}}_stopUpdate(){this._active=!1,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._useWebworker&&this._webWorker&&this._webWorker.postMessage("stop")}destroy(){this._focusHandler&&(window.removeEventListener("focus",this._focusHandler),this._focusHandler=null),this._blurHandler&&(window.removeEventListener("blur",this._blurHandler),this._blurHandler=null),this._visibilityHandler&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=null),this._stopUpdate()}_updateWorkerTime(r){let e=(r-(this._previousWorkerTime||0))/1e3;e>this._intervalThreshold&&(this._update(e),this._previousWorkerTime=r)}_updateRAFTime(r){this._previousRAFTime===void 0&&(this._previousRAFTime=r);let e=(r-this._previousRAFTime)/1e3;e>this._intervalThreshold&&(this._update(e),this._previousRAFTime=r),!this._useWebworker&&this._active?this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)):this._rafId=0}_update(r){for(let e=0;e<this._updateables.length;e++)this._updateables[e]._update(typeof r=="number"?r:parseFloat(r))}register(r){this._updateables.push(r),this._inited===!1&&(this._inited=!0,this._init()),this._active===!1&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)),this._active=!0)}unregister(r){const e=this._updateables.indexOf(r);e!==-1&&this._updateables.splice(e,1),this._updateables.length===0&&this._stopUpdate()}}class Wn extends Ht{constructor(e,t=10){super("AliRtcImageHolder");m(this,"url");m(this,"image");m(this,"canvas");m(this,"mediaStream");m(this,"updateableManager");m(this,"updateable");m(this,"hasVideoTrack",!1);this.url=e,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.drawImageToCanvas(),this.updateableManager=new cl(t)}get initOptions(){return{imageUrl:""}}setOptions(e){e.imageUrl&&(this.options=e,e.imageUrl!==this.url&&this.drawImageToCanvas())}drawImageToCanvas(){return I(this,null,function*(){if(!this.url)return;const e=this.canvas.getContext("2d"),t=document.createElement("img");let i;this.image=t,t.crossOrigin="anonymous",t.src=this.url;const{width:s,height:n}=yield new Promise(c=>{t.onload=()=>{i&&clearTimeout(i),c({width:t.width||16,height:t.height||16})},t.onerror=()=>{i&&clearTimeout(i),c({width:16,height:16})},i=setTimeout(()=>{c({width:16,height:16})},5e3)});this.canvas.width=s,this.canvas.height=n,e.drawImage(t,0,0,s,n)})}start(){return I(this,null,function*(){var i;if(!this.url)throw new Error("no image url founded");if(!this.canvas)throw new Error("get canvas error");const e=this.canvas.captureStream(25),t=this.canvas.getContext("2d");return this.image&&this.image.width&&t.drawImage(this.image,0,0,this.image.width,this.image.height),this.mediaStream=e,t.fillStyle="transparent",this.updateable={_update:()=>{t.fillRect(0,0,1,1)}},this.updateableManager.register(this.updateable),(i=e.getVideoTracks())==null?void 0:i[0]})}stop(){var e,t;this.updateable&&(this.updateableManager.unregister(this.updateable),this.updateable=null),this.updateableManager.destroy(),(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null||t.stop(),this.mediaStream=void 0}isSupported(){return!0}shouldUpdate(e){return this.hasVideoTrack===!!e.originVideoTrack}process(e){return I(this,null,function*(){if(this.hasVideoTrack=!!e.originVideoTrack,e.originVideoTrack){const i=e.currentVideoTrack;return i&&i.id===e.originVideoTrack.id||e.updateVideoTrack(e.originVideoTrack),void this.stop()}const t=yield this.start();e.updateVideoTrack(t)})}}class xi{static checkString(r){return typeof r=="string"}static checkNumber(r){return typeof r=="number"}static checkHtmlVideoElement(r){return r&&r.nodeName==="VIDEO"}static checkHtmlAudioElement(r){return r&&r.nodeName==="AUDIO"}static checkAuthInfo(r){return r?r.appId?r.channelId?xi.checkString(r.channelId)?r.userId?xi.checkString(r.userId)?r.timestamp?xi.checkNumber(r.timestamp)?r.token?null:new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"userId is not string"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"channelId is not string"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded"):new O(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded")}static checkMediaStreamTrack(r){return r instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(r){return r&&(r.width||r.height||r.frameRate||r.bitrateMax)}}var ll=Object.defineProperty,dl=Object.getOwnPropertyDescriptor,$=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?dl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&ll(r,e,s),s};let qt,zn=!1;const j=(F=class extends oe{constructor(e,t){super();m(this,"instanceId");m(this,"_globalEnv");m(this,"channelProfile");m(this,"clientRole");m(this,"signalingManager");m(this,"bizControl");m(this,"liveTranscoding");m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");m(this,"connectState",ae.AliRtcConnectionStatusInit);m(this,"networkError",!1);m(this,"_audioOnlyMode",!1);m(this,"_destroyed",!1);m(this,"_authInfoWillExpireTimer",null);m(this,"_authInfoExpiredTimer",null);m(this,"_serverCheckAuthInfoTimestamp",null);m(this,"_localCheckAuthInfoTimestamp",null);m(this,"_proxyAiTid",null);m(this,"_agentParam",null);m(this,"sessionId");this.config=e,this.instanceId=t||(e==null?void 0:e.instanceId)||`rtc_default_${Date.now()}`,this._globalEnv=e==null?void 0:e.globalEnv;const i=Date.now();T.init(this.instanceId,e==null?void 0:e.globalEnv),this.slsReporter=new il(this,e==null?void 0:e.globalEnv),this.channelProfile=Vt.AliRtcSdkCommunication,this.clientRole=$t.AliRtcSdkLive,this.liveTranscoding=new Yc(this.slsReporter),this.signalingManager=new nr(this.channelProfile,this.clientRole,this.slsReporter,(e==null?void 0:e.env)===wt.pre?wt.pre:wt.prod),this.addSignalingManagerListeners(),this.maxSignalingReconnectDuration=e==null?void 0:e.maxSignalingReconnectDuration,this.bizControl=new Qe({slsReporter:this.slsReporter,signalingManager:this.signalingManager,parameter:e==null?void 0:e.parameter,instanceId:this.instanceId}),this.addBizControlListeners(),this.addPublisherListeners(),this.slsReporter.reportConnectionLatencyEvent(Ye.CREATE_ENGINE,tt.START,"","",i),this.slsReporter.reportConnectionLatencyEvent(Ye.CREATE_ENGINE,tt.END,"","",Date.now()),this.slsReporter.reportSDKCreated(i),hi++,ui||(ui=!0,window.addEventListener("mousedown",rt),window.addEventListener("touchstart",rt))}static getSdkVersion(){return Ai}static setLogLevel(e){T.setLogLevel(e)}static createInstance(e){K.AliRTS.ENV=(e==null?void 0:e.globalEnv)==="SEA"?"SEA":void 0;const t=(e==null?void 0:e.instanceId)||`rtc_${++F._instanceCounter}_${Date.now()}`,i=new F(e,t);return F._instances.set(t,i),i.configureTracer(e),i}static getAllInstances(){return Array.from(F._instances.values())}static getInstanceById(e){return F._instances.get(e)}static destroyAll(){return I(this,null,function*(){const e=Array.from(F._instances.values());yield Promise.all(e.map(t=>t.destroy()))})}static getInstance(e){return F._instance||(K.AliRTS.ENV=(e==null?void 0:e.globalEnv)==="SEA"?"SEA":void 0,F._instance=new F(e),F._instance.configureTracer(e)),F._instance}destroy(){return I(this,null,function*(){var e,t,i;this._destroyed||(this._destroyed=!0,F._instances.delete(this.instanceId),F._instance===this&&(F._instance=void 0),yield this.leaveChannel(),yield this.bizControl.clear(),this.removeAllListeners(),(e=this.bizControl)==null||e.removeAllListeners(),(t=this.signalingManager)==null||t.removeAllListeners(),(i=this.slsReporter)==null||i.stop(),hi--,hi<=0&&(hi=0,ui&&(ui=!1,window.removeEventListener("mousedown",rt),window.removeEventListener("touchstart",rt))),T.destroy(this.instanceId))})}configureTracer(e){zn||(qt==null||qt.updateOptions({region:(e==null?void 0:e.globalEnv)==="SEA"?"sg":"cn"}),qt==null||qt.setReady(),zn=!0)}syncGlobalEnv(){K.AliRTS.ENV=this._globalEnv==="SEA"?"SEA":void 0}get channel(){return this.bizControl.channel}get userId(){return this.bizControl.userId}get remoteUsers(){return this.bizControl.remoteUsers}get publisher(){return this.bizControl.publisher}get publishAudioStream(){return this.publisher.publishStreams.audio}get isPublishing(){const{publisher:e}=this.bizControl;return!!e&&e.isPublishing}get currentRoleCanPublish(){return this.channelProfile===Vt.AliRtcSdkCommunication||this.clientRole===$t.AliRtcSdkInteractive}addPublisherListeners(){this.publisher.on(at.Local,e=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] Device Status Change",e),this.onLocalDeviceStatusChange(e)}),this.publisher.on(ai.VideoTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",Tt.AliEngineLocalDeviceTypeCamera,He.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),this.publisher.on(ai.ScreenTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",Tt.AliEngineLocalDeviceTypeDisplay,He.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),this.publisher.on(ai.AudioTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",Tt.AliEngineLocalDeviceTypeMic,He.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),this.publisher.on("localDeviceException",(e,t,i="")=>{this.emit("localDeviceException",e,t,i)}),this.publisher.on("audioPublishStateChanged",(e,t,i)=>{var s;this.emit("audioPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("videoPublishStateChanged",(e,t,i)=>{var s;this.emit("videoPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("dualStreamPublishStateChanged",(e,t,i)=>{var s;this.emit("dualStreamPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("screenPublishStateChanged",(e,t,i)=>{var s;this.emit("screenSharePublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("dataPublishStateChanged",(e,t,i)=>{var s;this.emit("dataPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")})}occurError(e,t){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"Occur Error",e,t),this.emit("onOccurError",e,t),this.emit("occurError",e,t)}addBizControlListeners(){this.bizControl.rtsManager.on("disconnected",()=>I(this,null,function*(){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RTS Disconnected"),(yield De.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.bizControl.rtsManager.on("subscribeexceeds",()=>I(this,null,function*(){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RTS SubscribeExceeds"),this.bizControl.rtsManager.clear(),yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.bizControl.rtsManager.on("seimessage",(e,t,i)=>I(this,null,function*(){const s=this.remoteUsers.find(n=>De.removeQueryString(n.streamUrl)===De.removeQueryString(e));if(s){try{this.emit("mediaExtensionMsgReceived",s.userId,i,t)}catch(n){}if(t===99)try{const n=JSON.parse(new TextDecoder().decode(i)),c=n.pub||{},o=n.grtn||{},l=n.sub||{};let d;d=Object.keys(o).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(o.totalCost||0)+(l.downRTTHalf||0)+(l.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(l.vJitterBufferDelay||0)+(l.vDecPlugCost||0);const h=s.streamInfo.getVideoLargeInfo(),p=s.streamInfo.getVideoSmallInfo(),u=[h,p,s.streamInfo.getScreenInfo()].filter(f=>f&&f.subscribeState===de.Subscribed&&f.msid);for(const f of u)try{this.emit("rtcCumuDelayReceived",s.userId,f.msid,d)}catch(g){}if(s.audioSSRC&&this.slsReporter.reportCumuAudioDelay(s.audioSSRC,n),s.videoSSRC){const f=yield this.bizControl.rtsManager.getSubscribeVideoStats(e);(f==null?void 0:f.frameHeight)===16&&(f==null?void 0:f.frameWidth)===16||this.slsReporter.reportCumuVideoDelay(s.videoSSRC,n)}}catch(n){}}})),this.bizControl.on(at.Remote,(e,t)=>{T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RemoteUser Device Status Change",e,t)}),this.bizControl.on("remoteUserJoin",(e,t)=>{this.emit("remoteUserOnLineNotify",e,t)}),this.bizControl.on("remoteTrackAvailableChange",(e,t,i)=>{this.emit("remoteTrackAvailableNotify",e,t,i)}),this.bizControl.on("audioSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("audioSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("videoSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("videoSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("screenSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("screenShareSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("dataSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("dataSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("userAudioMuted",(e,t)=>{this.emit("userAudioMuted",e,t)}),this.bizControl.on("userVideoMuted",(e,t)=>{this.emit("userVideoMuted",e,t)}),this.bizControl.on("userScreenMuted",(e,t)=>{this.emit("userScreenMuted",e,t)}),this.bizControl.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.bizControl.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.bizControl.on("remoteVideoAutoPlayFail",(e,t)=>{this.emit("remoteVideoAutoPlayFail",e,t)}),this.bizControl.on("remoteAudioPlayError",(e,t)=>{this.emit("remoteAudioPlayError",e,t)}),this.bizControl.on("remoteVideoPlayError",(e,t)=>{this.emit("remoteVideoPlayError",e,t)}),this.bizControl.on("rtcStats",e=>{this.emit("rtcStats",e)}),this.bizControl.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.bizControl.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.bizControl.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.bizControl.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.bizControl.on("remoteSubscribeError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("occurError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("remoteDataChannelMessage",(e,t)=>{this.emit("dataChannelMsg",e,t)}),this.bizControl.on("remoteUserSubscribedDataChannel",e=>{this.emit("remoteUserSubscribedDataChannel",e)}),this.bizControl.on("networkQuality",e=>{this.emit("networkQuality",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(T.setActiveInstance(this.instanceId),T.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e)}),this.signalingManager.on("onNotifyStatus",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Status ",e),e.forEach(t=>{this.bizControl.updateRemoteUserDeviceStatus(t)})}),this.signalingManager.on("onNotifyLeave",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Leave ",e),e.forEach(t=>I(this,null,function*(){yield this.bizControl.removeLeftUser(t),this.emit("remoteUserOffLineNotify",t.userid,t.leavecode)}))}),this.signalingManager.on("onBye",(e,t)=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Bye ",e,t),this.slsReporter.reportError({message:`reason: ${e}, description: ${t}`}),this.emit("bye",e),this.signalingManager.reset(),this.leaveChannel(),this.slsReporter.reportBye(e)}),this.signalingManager.on("onConnectFail",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.bizControl.leave(),this.signalingManager.reset(),this.connectState=ae.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusFailed,Ct.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{this.slsReporter.reportWarning("signaling network error"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{this.onNetworkError(),T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Start "),this.connectState=ae.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusReconnecting,Ct.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{this.slsReporter.reportWarning("signaling reconnect fail: ${err.code}"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{this.slsReporter.reportWarning("signaling error: ${err.message}"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Error ",e),this.onError(e)}),this.signalingManager.on("onUnknownMessage",e=>{if(e.msgtype==="proxyai"&&e.tid===this._proxyAiTid){let t=e.data.retcode;t===200&&(t=0),this.emit("AIAgentResult",t,this._agentParam.action,e.data.body)}})}backToUnpublishStatus(){this.connectState=ae.AliRtcConnectionStatusDisconnected,this.publisher.isPublishing&&this.publisher.clearPublishState(),this.networkError=!1}handleUsersJoin(e){e.forEach(t=>{this.bizControl.addUser(t,ge.Join)})}onLocalDeviceStatusChange(e){T.event(`[${F.logName}]`,at.Local,e),this.signalingManager.reportStatus(e).then(()=>{T.debug("[signaling] reportStatus suc")}).catch(t=>{T.error("[signaling] reportStatus failed",t)})}resumePublishForNetworkRecovery(){return I(this,null,function*(){try{yield this.publisher.resumePublish()}catch(e){const{code:t}=e;if(t===10205){let s=1;try{yield new Promise((n,c)=>{const o=setInterval(()=>I(this,null,function*(){s>1&&(clearInterval(o),c()),s+=1;try{yield this.publisher.resumePublish(),clearInterval(o),n()}catch(l){const{code:d}=l;d!==10205&&(clearInterval(o),c())}}),1e3)})}catch(n){}}throw e}})}onNetworkRecovery(e){return I(this,null,function*(){T.event(F.logName,"onNetworkRecovery",`rts isConnected: ${this.bizControl.rtsManager.isConnected}; rts isConnecting: ${this.bizControl.rtsManager.isConnecting}`,{users:e}),yield this.resumeSubList(e),this.networkError&&(this.networkError=!1,this.publisher.reportSelfDeviceStatus(),this.connectState=ae.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnected,Ct.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return I(this,null,function*(){if(e){const{joinList:t,leaveList:i,presentList:s}=this.bizControl.diffUsers(e);T.info(`[${F.logName}]`,"resumeSubList",{joinList:t,leaveList:i,presentList:s}),this.handleUsersJoin(t),i.forEach(n=>{T.event(F.logName,Pe.UserLeft,n.userid,n.reason),this.bizControl.onRemotePublishStateChange({userid:n.userid,displayname:"",callid:"",tracks:[]}),this.bizControl.removeLeftUser(n),this.emit("remoteUserOffLineNotify",n.userid,rs.AliRtcUserOfflineQuit)}),s.forEach(n=>{this.bizControl.onRemotePublishStateChange(n)})}else for(let t=0;t<this.remoteUsers.length;t++){const i=this.remoteUsers[t];try{i.restore(),i.updateSubscribe(ge.Resume)}catch(s){}}})}retrySubscribe(e){return I(this,null,function*(){const t=this.bizControl.getRemoteUser(e);if(!t)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);t.restore(),t.updateSubscribe(ge.Retry)})}onNetworkError(){this.connectState===ae.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=ae.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusDisconnected,Ct.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.slsReporter.reportError(e),T.event(F.logName,Pe.Error,e)}setEnableDualVideoStream(e,t){this.bizControl.setEnableDualVideoStream(e,t)}hadPushStream(e){if(!this.publisher||!e)throw new O(B.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){return this.publisher.getCurrentMicDeviceId()}setChannelProfile(e){if(![ae.AliRtcConnectionStatusInit,ae.AliRtcConnectionStatusDisconnected,ae.AliRtcConnectionStatusFailed].includes(this.connectState))throw new O(B.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===Vt.AliRtcSdkCommunication&&(this.clientRole=$t.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}startDefaultDevices(){return I(this,null,function*(){if(!this.publisher)return;const{hasCamera:e,hasMicrophone:t,hasScreenShare:i}=this.publisher;if(!e&&!t&&!i){try{yield this.publisher.startDefaultCameraAndMic(this._audioOnlyMode)}catch(s){T.warn(`[${F.logName}]`,"startDefaultDevices failed",s.code,s.message),s instanceof O&&this.occurError(s);const n=s.code;this.occurError(new O(n>=B.ERR_CAMERA_OPEN_FAIL&&n<=B.ERR_CAMERA_NOT_AVAILABLE?B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED:B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED,`auto publish device failed, ${s.message||""}`))}yield this.publisher.previewAll()}})}startPublish(e){return I(this,null,function*(){try{yield this.publisher.startPublish(!1,e)}catch(t){const i=this.publisher.publishStreams||{},s=[];i!=null&&i.audio&&s.push(B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),i!=null&&i.video&&s.push(B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),s.forEach(n=>{this.occurError(new O(n,`auto publish stream failed, ${t.message||""}`))})}})}setClientRole(e){return I(this,null,function*(){this.syncGlobalEnv();try{if(this.channelProfile===Vt.AliRtcSdkCommunication)return;if(!Object.values($t).includes(e))throw new O(B.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.slsReporter.reportRoleUpdate(this.clientRole,e),this.isInCall()?this.clientRole===$t.AliRtcSdkInteractive?(this.publisher.isPublishing?yield this.publisher.unPublish():yield this.publisher.clearStream(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevices(),yield this.startPublish(kt.ROLE_CHANGE)):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(t){throw t.code===403&&this.emit("authInfoExpired"),t}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new O(B.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new O(B.ERR_INNER,"can not change audioRedEnabled in call");this.bizControl.setAudioRedEnabled(e)}setVideoCodec(e){this.bizControl.setVideoCodec(e)}setCheckAuthInfoTimer(e,t){const i=1e3*(e-t);this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},i),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},i-3e4),this._serverCheckAuthInfoTimestamp=t,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}joinChannel(s,n){return I(this,arguments,function*(e,t,i={}){this.syncGlobalEnv();const c=Date.now();let o,l=typeof t=="string"?t:t==null?void 0:t.userName;if(typeof e=="string")try{const p=JSON.parse(window.atob(e));o={appId:p.appid,channelId:p.channelid,userId:p.userid,timestamp:p.timestamp,nonce:p.nonce,token:p.token}}catch(p){throw new O(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${p.message||""}`)}else o=e;l||(l=o.userId);const d={start:Date.now()};let h=xi.checkAuthInfo(o);if(ae.AliRtcConnectionStatusInit!==this.connectState&&ae.AliRtcConnectionStatusDisconnected!==this.connectState&&ae.AliRtcConnectionStatusFailed!==this.connectState){const p=new O(B.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===ae.AliRtcConnectionStatusConnecting&&(p.message="Repeated operation during login"),this.slsReporter.reportJoin(p.code,d,""),p}{if(h)throw this.connectState=ae.AliRtcConnectionStatusFailed,this.slsReporter.reportJoin(h.code,d,""),this.slsReporter.reportJoinResult(h),h;o.sessionId=De.createCallid("web"),this.sessionId=o.sessionId,this.slsReporter.start(o),this.slsReporter.reportConnectionLatencyEvent(Ye.JOIN,tt.START,"","",c),this.connectState=ae.AliRtcConnectionStatusConnecting,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnecting,Ct.AliRtcConnectionSignalingConnecting),T.setActiveInstance(this.instanceId),T.setSessionID(o.appId,o.sessionId);const p=()=>I(this,null,function*(){var g,S;try{let b="Conference";typeof t=="object"&&t.capabilityProfile===ki.Human&&(b="AIUser");const v=JSON.parse(this.getParameter());v.joinMode&&(b=v.joinMode);const R=new wi(((g=this.config)==null?void 0:g.env)||wt.prod,o,b);if(R.result){const w=(u=R.result.config,f=st.EnableNonOnePcDefaultJoinMode,ei(u==null?void 0:u.data,f));R.result.useonepc&&w!==!1||(b=""),T.info(`[${wi.logName}]`,"got allocate result from localStorage",`joinMode: ${b}`,R.result.useonepc,w)}else T.info(`[${wi.logName}]`,"no allocate result in localStorage",`joinMode: ${b}`);b&&(i.joinmode=b);const _=Date.now(),y=yield this.signalingManager.join(o,l,this.maxSignalingReconnectDuration,d,i);y.l1ip?(T.info("allocate l1 pub ip with mode",b,y.l1ip),this.bizControl.rtsManager.preferredPubL1Ip=y.l1ip):this.bizControl.rtsManager.preferredPubL1Ip=void 0,y.l1subip?(T.info("allocate l1 sub ip with mode",b,y.l1subip),this.bizControl.rtsManager.preferredSubL1Ip=y.l1subip):this.bizControl.rtsManager.preferredSubL1Ip=void 0;const A=Date.now();this.connectState=ae.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnected,Ct.AliRtcConnectionSignalingJoinRoomSuccess),R.fetchAndUpdate(),this.bizControl.init(o,y,{capabilityProfile:typeof t=="object"?t.capabilityProfile:ki.Default,robotUserId:typeof t=="object"?t.robotUserId:void 0}),this.setCheckAuthInfoTimer(o.timestamp,y.timestamp),this.liveTranscoding.setAuthInfo(o),this.slsReporter.reportJoin(0,d,y.tid),this.slsReporter.reportJoinResult(null),this.slsReporter.reportConnectionLatencyEvent(Ye.JOIN,tt.SEND_SIG,"","",_),this.slsReporter.reportConnectionLatencyEvent(Ye.JOIN,tt.RECV_RST,"","",A),this.slsReporter.reportConnectionLatencyEvent(Ye.JOIN,tt.END,"","")}catch(b){const v=(S=b.code)!=null?S:-1,R=b.reason||b.message||"";throw this.connectState=ae.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusDisconnected,Ct.AliRtcConnectionSignalingJoinRoomFailure),this.slsReporter.reportJoin(v,d,""),this.slsReporter.reportJoinResult(b),new O(v,R)}var u,f});this.currentRoleCanPublish?(yield Promise.all([p(),this.startDefaultDevices()]),yield this.startPublish(kt.JOIN_CHANNEL)):yield p(),this.publisher.reportSelfDeviceStatus(),this.remoteUsers.forEach(u=>{u.updateSubscribe(ge.Join)})}})}joinAIChannel(e,t,i){return I(this,null,function*(){return this._proxyAiTid=ut(),this._agentParam=i,this.joinChannel(e,t,{proxyai:{tid:this._proxyAiTid,region:i.region,proxydata:JSON.stringify({Region:i.region,Action:i.action,ActionParams:i.params})}})})}leaveChannel(){return I(this,null,function*(){var t;this.slsReporter.reportLeaveInvoked(),yield this.bizControl.leave();let e=new Date().getTime();if(ae.AliRtcConnectionStatusConnected===this.connectState)try{let i;i=yield this.signalingManager.leave(),this.slsReporter.reportLeave(new Date().getTime()-e,0,(t=i==null?void 0:i.tid)!=null?t:"")}catch(i){this.slsReporter.reportLeave(new Date().getTime()-e,i.code,i.reason)}else this.slsReporter.reportLeave(0,0,"");this.sessionId=void 0,this.networkError=!1,this.connectState=ae.AliRtcConnectionStatusDisconnected,this.clearCheckAuthInfoTimer(),this.liveTranscoding.clear(),this.slsReporter.stop(),this.signalingManager.reset(),T.setActiveInstance(this.instanceId),T.reportEnd()})}isInCall(){return this.connectState===ae.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return I(this,null,function*(){let t;if(this.syncGlobalEnv(),typeof e=="string")try{const d=JSON.parse(window.atob(e));t={userId:d.userid,timestamp:d.timestamp,nonce:d.nonce,token:d.token}}catch(d){throw new O(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${d.message||""}`)}else t=e;const{userId:i,nonce:s,timestamp:n,token:c,role:o}=t,l={userId:i,nonce:s,timestamp:n,token:c,role:o};try{yield this.signalingManager.refreshAuthInfo(l),this.bizControl.refreshAuthInfo(l),this.liveTranscoding.refreshAuthInfo(l),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&t.timestamp&&this.setCheckAuthInfoTimer(t.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(d){throw d}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalAudioStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasMicrophone?yield this.publisher.updateStreams():yield this.startAudioCapture():yield this.publisher.publishUpdate())})}isLocalAudioStreamPublished(){var e;return(e=this.publisher.publishLocalAudioStreamEnabled)!=null?e:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.bizControl.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.bizControl.setWantSubAudio(e)}subscribeRemoteAudioStream(e,t){if(t&&!this.bizControl.isWantSubAudio)throw new O(B.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.bizControl.updateAudioWant(e,t)}resumeRemoteAudioStream(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);t.resumeAudio()}stopRemoteAudioPlay(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);t.stopPlayAudio()}publishLocalVideoStream(e){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalVideoStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasCamera?yield this.publisher.updateStreams():yield this.enableLocalVideo():yield this.publisher.publishUpdate())})}isLocalVideoStreamPublished(){var e;return(e=this.publisher.publishLocalVideoStreamEnabled)!=null?e:!0}setRemoteDefaultVideoStreamType(e){[Je.AliRtcVideoStreamTypeHigh,Je.AliRtcVideoStreamTypeLow].includes(e)&&this.bizControl.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,t){[Je.AliRtcVideoStreamTypeHigh,Je.AliRtcVideoStreamTypeLow].includes(t)&&this.bizControl.setRemoteUserVideoStreamType(e,t)}setDefaultSubscribeAllRemoteVideoStreams(e){this.bizControl.setAutoSubVideo(e),this.bizControl.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.bizControl.setWantSubVideo(e),this.bizControl.setWantSubScreen(e)}subscribeRemoteMediaStream(e,t,i,s){const n=this.bizControl.getRemoteUser(e);if(!n)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);!i||t!==he.AliRtcVideoTrackScreen&&t!==he.AliRtcVideoTrackBoth?n.setWantSubScreen(!1):n.setWantSubScreen(!0),!i||t!==he.AliRtcVideoTrackCamera&&t!==he.AliRtcVideoTrackBoth?n.setWantSubVideo(!1):n.setWantSubVideo(!0),n.setWantSubAudio(s),i||s?n.subscribe({video:i,audio:s},ge.User):n.stopSubscribe({video:!0,audio:!0})}resumeRemoteMediaStream(e,t){const i=this.bizControl.getRemoteUser(e);i&&i.resumeVideo(t)}getOnlineRemoteUsers(){return this.bizControl.remoteUsers.map(e=>e.userId)}getUserInfo(e){var t;return(t=this.bizControl.getRemoteUser(e))==null?void 0:t.remoteUserInfo}isUserOnline(e){return!!this.bizControl.remoteUsers.find(t=>t.userId===e)}startScreenShare(e){return I(this,null,function*(){this.syncGlobalEnv();const t={video:!1,audio:!1},{audio:i=!1,videoTrack:s,audioTrack:n}=e||{};if(s||n){t.screen=!0;const c=new MediaStream;s&&c.addTrack(s),n&&c.addTrack(n),t.mediaStream=c}else t.screen=!i||{audio:!0};yield this.publisher.createLocalStream(t)})}stopScreenShare(){return I(this,null,function*(){this.publisher.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return I(this,null,function*(){const{width:t,height:i}=e;if(t&&!isNaN(t)&&i&&!isNaN(i)&&t*i>9437184)throw new O(B.ERR_INVALID_ARGUMENTS,"width * height must be less than 9437184");const o=e,{bitrate:s}=o,n=jt(o,["bitrate"]),c=X({},n);s&&(c.maxBitrate=e.bitrate),yield this.publisher.setScreenProfile(c)})}setScreenShareContentHint(e){return I(this,null,function*(){e&&this.publisher.setScreenContentHint(e)})}publishLocalScreenShareStream(e,t){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalScreenStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasScreenShare?yield this.publisher.updateStreams():yield this.startScreenShare(t):yield this.publisher.publishUpdate())})}isScreenSharePublished(){var e;return(e=this.publisher.publishLocalScreenStreamEnabled)!=null?e:!0}setAudioShareVolume(e){if(typeof e!="number")throw new O(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.bizControl.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){this.publisher.muteLocalMic(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()}muteRemoteAudioPlaying(e,t=!1){const i=this.bizControl.getRemoteUser(e);if(!i)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);i.setAudioMuted(t)}muteAllRemoteAudioPlaying(e=!1){this.bizControl.setAudioMuted(e)}startAudioCapture(e){return I(this,null,function*(){const t={audio:e||!0};yield this.publisher.createLocalStream(t)})}setAudioConstraints(e){return I(this,null,function*(){yield this.publisher.setMicrophoneConstraints(e)})}stopAudioCapture(){this.publisher.stopAudioCapture()}switchMicrophone(e,t){return I(this,null,function*(){if(yield this.publisher.setMicrophoneDeviceId(e),!this.publisher.audioCaptureDisabled){if(t)return void(yield this.publisher.createLocalStream({audio:!0,mediaStream:new MediaStream([t])}));yield this.publisher.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new O(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({audio:Math.max(0,Math.min(e,400))/100})}setPlayoutVolume(e){if(typeof e!="number")throw new O(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setRemoteAudioVolume(e,t){const i=this.bizControl.getRemoteUser(e);if(!i)throw new O(B.ERR_INNER,`no remote user(${e}) founded`);if(typeof t!="number")throw new O(B.ERR_INVALID_ARGUMENTS,"volume must be a number");i.setPlayoutVolume(Math.max(0,Math.min(t,100))/100)}setAudioProfile(e){return I(this,null,function*(){yield this.publisher.setAudioProfile(e)})}getAudioTrack(e){return I(this,null,function*(){if(!e)return this.publisher.audioTrack;const t=this.bizControl.getRemoteUser(e);return t==null?void 0:t.getAudioTrack})}setLocalViewConfig(e,t){return I(this,null,function*(){var i;if(this._audioOnlyMode)throw new O(B.ERR_INNER,"Cannot set local view in audio only mode");(i=this.bizControl)==null||i.setLocalViewConfig(e,t),t===he.AliRtcVideoTrackCamera&&this.publisher.hasCamera?yield this.startPreview():t===he.AliRtcVideoTrackScreen&&this.publisher.hasScreenShare&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return I(this,null,function*(){const l=e,{cameraDirection:t,deviceId:i,bitrate:s,maxSendFrameRate:n}=l,c=jt(l,["cameraDirection","deviceId","bitrate","maxSendFrameRate"]),o=X({},c);s&&(o.maxBitrate=s),n&&(o.maxSendFrameRate=n),Object.keys(o).length>0&&(yield this.publisher.setVideoProfile(o)),t!==void 0&&this.publisher.setCameraDirection(t),i&&this.publisher.setCameraDeviceId(i)})}setCameraCapturerContentHint(e){return I(this,null,function*(){e&&this.publisher.setVideoContentHint(e)})}enableLocalVideo(e=!0){return I(this,null,function*(){var t,i,s,n,c,o;if(this._audioOnlyMode)throw new O(B.ERR_INNER,"Cannot enable local video in audio only mode");e?((t=this.publisher.publishStreams)!=null&&t.video&&((s=(i=this.publisher.publishStreams)==null?void 0:i.video)==null||s.disableVideo(),(o=(c=(n=this.publisher.publishStreams)==null?void 0:n.video)==null?void 0:c.videoTrack)==null||o.stop()),yield this.publisher.startCameraCapture()):yield this.publisher.stopCameraCapture()})}muteLocalCamera(e){return I(this,null,function*(){this.publisher.muteLocalCamera(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}muteLocalScreen(e){return I(this,null,function*(){this.publisher.muteLocalScreen(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}setRemoteViewConfig(e,t,i){this.bizControl.setRemoteViewConfig(t,e,i)}isCameraOn(){var e;return(e=this.publisher.hasCamera)!=null?e:!1}switchCamera(e,t){return I(this,null,function*(){var s;if(this._audioOnlyMode)throw new O(B.ERR_INNER,"Cannot switch camera in audio only mode");const i={};if(e?(i.deviceId=e,this.slsReporter.reportSwitchCamera(e)):t||(i.cameraDirection=this.publisher.cameraDirection==="environment"?yi.CAMERA_FRONT:yi.CAMERA_REAR,this.slsReporter.reportSwitchCamera(this.publisher.cameraDirection||"")),yield this.setCameraCapturerConfiguration(i),!this.publisher.cameraCaptureDisabled){(s=this.publisher.cameraTrack)==null||s.stop();const n={video:!0};t&&(n.mediaStream=new MediaStream([t])),yield this.publisher.createLocalStream(n)}})}getCurrentCameraDeviceId(){return this.publisher.getCurrentCameraDeviceId()}startPreview(){return I(this,null,function*(){if(this._audioOnlyMode)throw new O(B.ERR_INNER,"Cannot start preview camera in audio only mode");this.publisher.hasCamera||(yield this.enableLocalVideo(!0)),yield this.publisher.previewAll({screen:!1})})}startPreviewScreen(e){return I(this,null,function*(){if(this._audioOnlyMode)throw new O(B.ERR_INNER,"Cannot start preview screen share in audio only mode");this.publisher.hasScreenShare||(yield this.startScreenShare(e)),yield this.publisher.previewAll({primary:!1})})}stopPreview(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return I(this,null,function*(){var n,c;const{userId:t,streamType:i}=e;if(!t)return i===Ue.AliRtcSdkStreamTypeCapture?this.publisher.cameraTrack:this.publisher.screenTrack;const s=this.bizControl.getRemoteUser(t);return i===Ue.AliRtcSdkStreamTypeCapture?(n=s==null?void 0:s.getCameraStream)==null?void 0:n.videoTrack:(c=s==null?void 0:s.getScreenStream)==null?void 0:c.videoTrack})}startPublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,t)})}updatePublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,t)})}updatePublishLiveStreamWithTaskId(e,t){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,t)}stopPublishLiveStream(e){return I(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var t;(t=this.bizControl)==null||t.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,t){return I(this,null,function*(){return this.sendMediaExtensionMsgEx(e,t,5)})}sendMediaExtensionMsgEx(e,t,i){return I(this,null,function*(){if(!this.publisher||!this.isPublishing)throw new O(B.ERR_INNER,"you should publish first");return this.slsReporter.reportSEIMessage(i,e.byteLength,t,0,!1),this.publisher.sendSEI(e,t,i)})}enablePlugin(e,t){this.bizControl.pluginManager.add(e,t)}removePlugin(e){this.bizControl.pluginManager.remove(e)}setPluginOption(e,t){const i=this.bizControl.pluginManager.get(e);i&&t&&i.setOptions(t)}getPluginByName(e){return this.bizControl.pluginManager.get(e)}getPluginOption(e){const t=this.bizControl.pluginManager.get(e);return t==null?void 0:t.getOptions()}isBeautyAvailable(){return this.bizControl.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.bizControl.pluginManager.get("AliRtcBeauty");if(!e)throw new O(Kt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i)throw new O(Kt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?i.enable():i.disable(),i.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+t.smoothnessLevel),0),whitening:Math.max(Math.min(1,+t.whiteningLevel),0)}})}enableBackgroundExchange(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i||!i.isEnable)throw new O(Kt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const s={setSegmentBackgroundImage:{backgroundImgUrl:e?t:""}};e&&(s.segmentBackgroundProcess={enable:!1}),i.setOptions(s)}enableBackgroundBlur(e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new O(Kt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const i={segmentBackgroundProcess:{type:0,enable:e}};e&&(i.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),t.setOptions(i)}setParameter(e){this.bizControl.setParameter(e)}getParameter(){return this.bizControl.getParameter()}sendDataChannelMessage(e){this.bizControl.sendDataChannelMessage(e)}subscribeRemoteStream(e){const{currentUserId:t,targetUserId:i}=e;if(i===t)throw new O(B.ERR_INNER,"targetUserId should not be equal to currentUserId");return new bs(e)}},m(F,"logName","AliRtcEngine"),m(F,"logError",!0),m(F,"isSupported",Tc),m(F,"isDualVideoStreamSupported",ys.isSupport),m(F,"getCameraList",()=>I(F,null,function*(){return(yield K.AliRTS.getCameraList()).filter(e=>e.deviceId)})),m(F,"getMicrophoneList",()=>I(F,null,function*(){return(yield K.AliRTS.getMicList()).filter(e=>e.deviceId)})),m(F,"getSpeakerList",()=>I(F,null,function*(){return(yield K.AliRTS.getSpeakerList()).filter(e=>e.deviceId)})),m(F,"_instances",new Map),m(F,"_instanceCounter",0),m(F,"_instance"),m(F,"AliRtcSdkChannelProfile",Vt),m(F,"AliRtcSdkClientRole",$t),m(F,"AliRtcVideoStreamType",Je),m(F,"AliRtcVideoTrack",he),m(F,"AliRtcAudioTrack",Zt),m(F,"AliRtcPublishState",ee),m(F,"AliRtcSubscribeState",ce),m(F,"AliRtcRawDataStreamType",Ue),m(F,"AliRtcLogLevel",fs),m(F,"AliRtcEngineLocalDeviceType",Tt),m(F,"AliRtcEngineLocalDeviceExceptionType",He),m(F,"AliRtcConnectionStatus",ae),m(F,"AliRtcConnectionStatusChangeReason",Ct),m(F,"AliRtcPlugin",Ht),m(F,"AliRtcPluginTrackType",gi),m(F,"AliRtcImageHolderPlugin",Wn),m(F,"AliRtcLiveTranscodingParam",Yi),m(F,"AliRtcLiveTranscodingEncodeParam",Qs),m(F,"AliRtcLiveTranscodingMixParam",Un),m(F,"AliRtcLiveTranscodingSingleParam",Bn),m(F,"AliRtcTranscodingClockWidget",Hn),m(F,"AliRtcTranscodingImage",or),m(F,"AliRtcTranscodingText",jn),m(F,"AliRtcTranscodingUser",$n),m(F,"AliRtcLiveTranscodingMixMode",Pi),m(F,"AliRtcLiveTranscodingStreamType",Js),m(F,"AliRtcLiveTranscodingSourceType",bi),m(F,"AliRtcLiveTranscodingTaskProfile",Gs),m(F,"AliRtcLiveTranscodingAudioSampleRate",qi),m(F,"AliRtcLiveTranscodingSegmentType",Mi),m(F,"AliRtcLiveTranscodingFontType",Li),m(F,"AliRtcLiveTranscodingCropMode",qs),m(F,"AliRtcLiveTranscodingMediaProcessMode",Xi),m(F,"AliRtcLiveTranscodingState",Xs),m(F,"AliRtcLiveTranscodingErrorCode",Lt),m(F,"AliRtcTrascodingPublishTaskStatus",Ys),m(F,"AliRtcDataChannelMsg",zt),m(F,"AliRtcDataMsgType",Bs),m(F,"Plugin",Ht),F);$([k()],j.prototype,"destroy",1),$([k()],j.prototype,"backToUnpublishStatus",1),$([k()],j.prototype,"resumePublishForNetworkRecovery",1),$([k()],j.prototype,"onNetworkRecovery",1),$([k()],j.prototype,"resumeSubList",1),$([k(H)],j.prototype,"retrySubscribe",1),$([k(H)],j.prototype,"setEnableDualVideoStream",1),$([k(H)],j.prototype,"setChannelProfile",1),$([k(H)],j.prototype,"setClientRole",1),$([k(H)],j.prototype,"setAudioOnlyMode",1),$([k()],j.prototype,"clearCheckAuthInfoTimer",1),$([k(H)],j.prototype,"joinChannel",1),$([k(H)],j.prototype,"joinAIChannel",1),$([k(H)],j.prototype,"leaveChannel",1),$([k(H)],j.prototype,"refreshAuthInfo",1),$([k(H)],j.prototype,"publishLocalAudioStream",1),$([k(H)],j.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),$([k(H)],j.prototype,"subscribeAllRemoteAudioStreams",1),$([k(H)],j.prototype,"subscribeRemoteAudioStream",1),$([k(H)],j.prototype,"resumeRemoteAudioStream",1),$([k(H)],j.prototype,"stopRemoteAudioPlay",1),$([k(H)],j.prototype,"publishLocalVideoStream",1),$([k(H)],j.prototype,"setRemoteDefaultVideoStreamType",1),$([k(H)],j.prototype,"setRemoteUserVideoStreamType",1),$([k(H)],j.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),$([k(H)],j.prototype,"subscribeAllRemoteVideoStreams",1),$([k(H)],j.prototype,"subscribeRemoteMediaStream",1),$([k(H)],j.prototype,"resumeRemoteMediaStream",1),$([k(([a])=>[`${a==null?void 0:a.audio}`])],j.prototype,"startScreenShare",1),$([k()],j.prototype,"stopScreenShare",1),$([k(H)],j.prototype,"setScreenShareConfiguration",1),$([k(H)],j.prototype,"setScreenShareContentHint",1),$([k()],j.prototype,"publishLocalScreenShareStream",1),$([k(H)],j.prototype,"setAudioShareVolume",1),$([k(H)],j.prototype,"enableAudioVolumeIndication",1),$([k(H)],j.prototype,"muteLocalMic",1),$([k(H)],j.prototype,"muteRemoteAudioPlaying",1),$([k(H)],j.prototype,"muteAllRemoteAudioPlaying",1),$([k(H)],j.prototype,"startAudioCapture",1),$([k(H)],j.prototype,"setAudioConstraints",1),$([k()],j.prototype,"stopAudioCapture",1),$([k(H)],j.prototype,"switchMicrophone",1),$([k(H)],j.prototype,"setRecordingVolume",1),$([k(H)],j.prototype,"setPlayoutVolume",1),$([k(H)],j.prototype,"setRemoteAudioVolume",1),$([k(H)],j.prototype,"setAudioProfile",1),$([k(H)],j.prototype,"getAudioTrack",1),$([k(H)],j.prototype,"setLocalViewConfig",1),$([k(H)],j.prototype,"setCameraCapturerConfiguration",1),$([k(H)],j.prototype,"setCameraCapturerContentHint",1),$([k(H)],j.prototype,"enableLocalVideo",1),$([k(H)],j.prototype,"muteLocalCamera",1),$([k(H)],j.prototype,"muteLocalScreen",1),$([k(H)],j.prototype,"setRemoteViewConfig",1),$([k(H)],j.prototype,"switchCamera",1),$([k()],j.prototype,"startPreview",1),$([k()],j.prototype,"startPreviewScreen",1),$([k()],j.prototype,"stopPreview",1),$([k()],j.prototype,"stopPreviewScreen",1),$([k()],j.prototype,"startPublishLiveStream",1),$([k()],j.prototype,"updatePublishLiveStream",1),$([k()],j.prototype,"updatePublishLiveStreamWithTaskId",1),$([k()],j.prototype,"stopPublishLiveStream",1),$([k()],j.prototype,"stopPublishLiveStreamWithTaskId",1),$([k(H)],j.prototype,"setEnableMediaExtensionMsg",1),$([k(([a,r,e])=>[a.byteLength,r,e])],j.prototype,"sendMediaExtensionMsgEx",1),$([k(([a,r])=>[a.name||"",r])],j.prototype,"enablePlugin",1),$([k(H)],j.prototype,"removePlugin",1),$([k(H)],j.prototype,"setPluginOption",1),$([k(H)],j.prototype,"getPluginByName",1),$([k(H)],j.prototype,"getPluginOption",1),$([k(H)],j.prototype,"setBeautyEffect",1),$([k(H)],j.prototype,"enableBackgroundExchange",1),$([k(H)],j.prototype,"enableBackgroundBlur",1),$([k(H)],j.prototype,"setParameter",1),$([k(([a])=>{var r;return[(r=a.data)==null?void 0:r.byteLength]})],j.prototype,"sendDataChannelMessage",1),$([k(H)],j.prototype,"subscribeRemoteStream",1),$([k(H)],j,"setLogLevel",1);let Kn=j;qt=new Os({businessName:"imp-web-rtc",version:(Jn=Kn.getSdkVersion())!=null?Jn:"unknown",env:"prod",disabled:window.AliRtcOptionsDisableProxy===!0,deferRegionSet:!0});const hl=qt.shallowWrapClass(Kn);z.AliRtcAudioTrack=Zt,z.AliRtcCapabilityProfile=ki,z.AliRtcConnectionStatus=ae,z.AliRtcConnectionStatusChangeReason=Ct,z.AliRtcDataChannelMsg=zt,z.AliRtcDataMsgType=Bs,z.AliRtcEngineLocalDeviceExceptionType=He,z.AliRtcEngineLocalDeviceType=Tt,z.AliRtcErrorCode=B,z.AliRtcImageHolderPlugin=Wn,z.AliRtcLiveTranscodingAudioSampleRate=qi,z.AliRtcLiveTranscodingCropMode=qs,z.AliRtcLiveTranscodingEncodeParam=Qs,z.AliRtcLiveTranscodingErrorCode=Lt,z.AliRtcLiveTranscodingFontType=Li,z.AliRtcLiveTranscodingMediaProcessMode=Xi,z.AliRtcLiveTranscodingMixMode=Pi,z.AliRtcLiveTranscodingMixParam=Un,z.AliRtcLiveTranscodingParam=Yi,z.AliRtcLiveTranscodingSegmentType=Mi,z.AliRtcLiveTranscodingSingleParam=Bn,z.AliRtcLiveTranscodingSourceType=bi,z.AliRtcLiveTranscodingState=Xs,z.AliRtcLiveTranscodingStreamType=Js,z.AliRtcLiveTranscodingTaskProfile=Gs,z.AliRtcLocalStreamInfo=$s,z.AliRtcLogLevel=fs,z.AliRtcNetworkQuality=Ze,z.AliRtcPlugin=Ht,z.AliRtcPluginTrackType=gi,z.AliRtcPluginType=Cn,z.AliRtcPublishState=ee,z.AliRtcRawDataStreamType=Ue,z.AliRtcRemoteUserInfo=En,z.AliRtcSdkChannelProfile=Vt,z.AliRtcSdkClientRole=$t,z.AliRtcSubscribeState=ce,z.AliRtcTranscodingClockWidget=Hn,z.AliRtcTranscodingImage=or,z.AliRtcTranscodingText=jn,z.AliRtcTranscodingUser=$n,z.AliRtcTrascodingPublishTaskStatus=Ys,z.AliRtcVideoStreamType=Je,z.AliRtcVideoTrack=he,z.default=hl,Object.defineProperties(z,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});